| [ Index ] |
PHP Cross Reference of WordPress Trunk (Updated Daily) |
[Summary view] [Print] [Text view]
1 <?php 2 /** 3 * Filesystem API: Top-level functionality 4 * 5 * Functions for reading, writing, modifying, and deleting files on the file system. 6 * Includes functionality for theme-specific files as well as operations for uploading, 7 * archiving, and rendering output when necessary. 8 * 9 * @package WordPress 10 * @subpackage Filesystem 11 * @since 2.3.0 12 */ 13 14 /** The descriptions for theme files. */ 15 $wp_file_descriptions = array( 16 'functions.php' => __( 'Theme Functions' ), 17 'header.php' => __( 'Theme Header' ), 18 'footer.php' => __( 'Theme Footer' ), 19 'sidebar.php' => __( 'Sidebar' ), 20 'comments.php' => __( 'Comments' ), 21 'searchform.php' => __( 'Search Form' ), 22 '404.php' => __( '404 Template' ), 23 'link.php' => __( 'Links Template' ), 24 'theme.json' => __( 'Theme Styles & Block Settings' ), 25 // Archives. 26 'index.php' => __( 'Main Index Template' ), 27 'archive.php' => __( 'Archives' ), 28 'author.php' => __( 'Author Template' ), 29 'taxonomy.php' => __( 'Taxonomy Template' ), 30 'category.php' => __( 'Category Template' ), 31 'tag.php' => __( 'Tag Template' ), 32 'home.php' => __( 'Posts Page' ), 33 'search.php' => __( 'Search Results' ), 34 'date.php' => __( 'Date Template' ), 35 // Content. 36 'singular.php' => __( 'Singular Template' ), 37 'single.php' => __( 'Single Post' ), 38 'page.php' => __( 'Single Page' ), 39 'front-page.php' => __( 'Homepage' ), 40 'privacy-policy.php' => __( 'Privacy Policy Page' ), 41 // Attachments. 42 'attachment.php' => __( 'Attachment Template' ), 43 'image.php' => __( 'Image Attachment Template' ), 44 'video.php' => __( 'Video Attachment Template' ), 45 'audio.php' => __( 'Audio Attachment Template' ), 46 'application.php' => __( 'Application Attachment Template' ), 47 // Embeds. 48 'embed.php' => __( 'Embed Template' ), 49 'embed-404.php' => __( 'Embed 404 Template' ), 50 'embed-content.php' => __( 'Embed Content Template' ), 51 'header-embed.php' => __( 'Embed Header Template' ), 52 'footer-embed.php' => __( 'Embed Footer Template' ), 53 // Stylesheets. 54 'style.css' => __( 'Stylesheet' ), 55 'editor-style.css' => __( 'Visual Editor Stylesheet' ), 56 'editor-style-rtl.css' => __( 'Visual Editor RTL Stylesheet' ), 57 'rtl.css' => __( 'RTL Stylesheet' ), 58 // Other. 59 'my-hacks.php' => __( 'my-hacks.php (legacy hacks support)' ), 60 '.htaccess' => __( '.htaccess (for rewrite rules )' ), 61 // Deprecated files. 62 'wp-layout.css' => __( 'Stylesheet' ), 63 'wp-comments.php' => __( 'Comments Template' ), 64 'wp-comments-popup.php' => __( 'Popup Comments Template' ), 65 'comments-popup.php' => __( 'Popup Comments' ), 66 ); 67 68 /** 69 * Gets the description for standard WordPress theme files. 70 * 71 * @since 1.5.0 72 * 73 * @global array $wp_file_descriptions Theme file descriptions. 74 * @global array $allowed_files List of allowed files. 75 * 76 * @param string $file Filesystem path or filename. 77 * @return string Description of file from $wp_file_descriptions or basename of $file if description doesn't exist. 78 * Appends 'Page Template' to basename of $file if the file is a page template. 79 */ 80 function get_file_description( $file ) { 81 global $wp_file_descriptions, $allowed_files; 82 83 $dirname = pathinfo( $file, PATHINFO_DIRNAME ); 84 $file_path = $allowed_files[ $file ]; 85 86 if ( isset( $wp_file_descriptions[ basename( $file ) ] ) && '.' === $dirname ) { 87 return $wp_file_descriptions[ basename( $file ) ]; 88 } elseif ( file_exists( $file_path ) && is_file( $file_path ) ) { 89 $template_data = implode( '', file( $file_path ) ); 90 91 if ( preg_match( '|Template Name:(.*)$|mi', $template_data, $name ) ) { 92 /* translators: %s: Template name. */ 93 return sprintf( __( '%s Page Template' ), _cleanup_header_comment( $name[1] ) ); 94 } 95 } 96 97 return trim( basename( $file ) ); 98 } 99 100 /** 101 * Gets the absolute filesystem path to the root of the WordPress installation. 102 * 103 * @since 1.5.0 104 * 105 * @return string Full filesystem path to the root of the WordPress installation. 106 */ 107 function get_home_path() { 108 $home = set_url_scheme( get_option( 'home' ), 'http' ); 109 $siteurl = set_url_scheme( get_option( 'siteurl' ), 'http' ); 110 111 if ( ! empty( $home ) && 0 !== strcasecmp( $home, $siteurl ) ) { 112 $wp_path_rel_to_home = str_ireplace( $home, '', $siteurl ); /* $siteurl - $home */ 113 $pos = strripos( str_replace( '\\', '/', $_SERVER['SCRIPT_FILENAME'] ), trailingslashit( $wp_path_rel_to_home ) ); 114 $home_path = substr( $_SERVER['SCRIPT_FILENAME'], 0, $pos ); 115 $home_path = trailingslashit( $home_path ); 116 } else { 117 $home_path = ABSPATH; 118 } 119 120 return str_replace( '\\', '/', $home_path ); 121 } 122 123 /** 124 * Returns a listing of all files in the specified folder and all subdirectories up to 100 levels deep. 125 * 126 * The depth of the recursiveness can be controlled by the $levels param. 127 * 128 * @since 2.6.0 129 * @since 4.9.0 Added the `$exclusions` parameter. 130 * @since 6.3.0 Added the `$include_hidden` parameter. 131 * 132 * @param string $folder Optional. Full path to folder. Default empty. 133 * @param int $levels Optional. Levels of folders to follow, Default 100 (PHP Loop limit). 134 * @param string[] $exclusions Optional. List of folders and files to skip. 135 * @param bool $include_hidden Optional. Whether to include details of hidden ("." prefixed) files. 136 * Default false. 137 * @return string[]|false Array of files on success, false on failure. 138 */ 139 function list_files( $folder = '', $levels = 100, $exclusions = array(), $include_hidden = false ) { 140 if ( empty( $folder ) ) { 141 return false; 142 } 143 144 $folder = trailingslashit( $folder ); 145 146 if ( ! $levels ) { 147 return false; 148 } 149 150 $files = array(); 151 152 $dir = @opendir( $folder ); 153 154 if ( $dir ) { 155 while ( ( $file = readdir( $dir ) ) !== false ) { 156 // Skip current and parent folder links. 157 if ( in_array( $file, array( '.', '..' ), true ) ) { 158 continue; 159 } 160 161 // Skip hidden and excluded files. 162 if ( ( ! $include_hidden && '.' === $file[0] ) || in_array( $file, $exclusions, true ) ) { 163 continue; 164 } 165 166 if ( is_dir( $folder . $file ) ) { 167 $files2 = list_files( $folder . $file, $levels - 1, array(), $include_hidden ); 168 if ( $files2 ) { 169 $files = array_merge( $files, $files2 ); 170 } else { 171 $files[] = $folder . $file . '/'; 172 } 173 } else { 174 $files[] = $folder . $file; 175 } 176 } 177 178 closedir( $dir ); 179 } 180 181 return $files; 182 } 183 184 /** 185 * Gets the list of file extensions that are editable in plugins. 186 * 187 * @since 4.9.0 188 * 189 * @param string $plugin Path to the plugin file relative to the plugins directory. 190 * @return string[] Array of editable file extensions. 191 */ 192 function wp_get_plugin_file_editable_extensions( $plugin ) { 193 194 $default_types = array( 195 'bash', 196 'conf', 197 'css', 198 'diff', 199 'htm', 200 'html', 201 'http', 202 'inc', 203 'include', 204 'js', 205 'mjs', 206 'json', 207 'jsx', 208 'less', 209 'md', 210 'patch', 211 'php', 212 'php3', 213 'php4', 214 'php5', 215 'php7', 216 'phps', 217 'phtml', 218 'sass', 219 'scss', 220 'sh', 221 'sql', 222 'svg', 223 'text', 224 'txt', 225 'xml', 226 'yaml', 227 'yml', 228 ); 229 230 /** 231 * Filters the list of file types allowed for editing in the plugin file editor. 232 * 233 * @since 2.8.0 234 * @since 4.9.0 Added the `$plugin` parameter. 235 * 236 * @param string[] $default_types An array of editable plugin file extensions. 237 * @param string $plugin Path to the plugin file relative to the plugins directory. 238 */ 239 $file_types = (array) apply_filters( 'editable_extensions', $default_types, $plugin ); 240 241 return $file_types; 242 } 243 244 /** 245 * Gets the list of file extensions that are editable for a given theme. 246 * 247 * @since 4.9.0 248 * 249 * @param WP_Theme $theme Theme object. 250 * @return string[] Array of editable file extensions. 251 */ 252 function wp_get_theme_file_editable_extensions( $theme ) { 253 254 $default_types = array( 255 'bash', 256 'conf', 257 'css', 258 'diff', 259 'htm', 260 'html', 261 'http', 262 'inc', 263 'include', 264 'js', 265 'mjs', 266 'json', 267 'jsx', 268 'less', 269 'md', 270 'patch', 271 'php', 272 'php3', 273 'php4', 274 'php5', 275 'php7', 276 'phps', 277 'phtml', 278 'sass', 279 'scss', 280 'sh', 281 'sql', 282 'svg', 283 'text', 284 'txt', 285 'xml', 286 'yaml', 287 'yml', 288 ); 289 290 /** 291 * Filters the list of file types allowed for editing in the theme file editor. 292 * 293 * @since 4.4.0 294 * 295 * @param string[] $default_types An array of editable theme file extensions. 296 * @param WP_Theme $theme The active theme object. 297 */ 298 $file_types = apply_filters( 'wp_theme_editor_filetypes', $default_types, $theme ); 299 300 // Ensure that default types are still there. 301 return array_unique( array_merge( $file_types, $default_types ) ); 302 } 303 304 /** 305 * Prints file editor templates (for plugins and themes). 306 * 307 * @since 4.9.0 308 */ 309 function wp_print_file_editor_templates() { 310 ?> 311 <script type="text/html" id="tmpl-wp-file-editor-notice"> 312 <div class="notice inline notice-{{ data.type || 'info' }} {{ data.alt ? 'notice-alt' : '' }} {{ data.dismissible ? 'is-dismissible' : '' }} {{ data.classes || '' }}"> 313 <# if ( 'php_error' === data.code ) { #> 314 <p> 315 <?php 316 printf( 317 /* translators: 1: Line number, 2: File path. */ 318 __( 'Your PHP code changes were not applied due to an error on line %1$s of file %2$s. Please fix and try saving again.' ), 319 '{{ data.line }}', 320 '{{ data.file }}' 321 ); 322 ?> 323 </p> 324 <pre>{{ data.message }}</pre> 325 <# } else if ( 'file_not_writable' === data.code ) { #> 326 <p> 327 <?php 328 printf( 329 /* translators: %s: Documentation URL. */ 330 __( 'You need to make this file writable before you can save your changes. See <a href="%s">Changing File Permissions</a> for more information.' ), 331 __( 'https://developer.wordpress.org/advanced-administration/server/file-permissions/' ) 332 ); 333 ?> 334 </p> 335 <# } else { #> 336 <p>{{ data.message || data.code }}</p> 337 338 <# if ( 'lint_errors' === data.code ) { #> 339 <p> 340 <# var elementId = 'el-' + String( Math.random() ); #> 341 <input id="{{ elementId }}" type="checkbox"> 342 <label for="{{ elementId }}"><?php _e( 'Update anyway, even though it might break your site?' ); ?></label> 343 </p> 344 <# } #> 345 <# } #> 346 <# if ( data.dismissible ) { #> 347 <button type="button" class="notice-dismiss"><span class="screen-reader-text"> 348 <?php 349 /* translators: Hidden accessibility text. */ 350 _e( 'Dismiss' ); 351 ?> 352 </span></button> 353 <# } #> 354 </div> 355 </script> 356 <?php 357 } 358 359 /** 360 * Attempts to edit a file for a theme or plugin. 361 * 362 * When editing a PHP file, loopback requests will be made to the admin and the homepage 363 * to attempt to see if there is a fatal error introduced. If so, the PHP change will be 364 * reverted. 365 * 366 * @since 4.9.0 367 * 368 * @param string[] $args { 369 * Args. Note that all of the arg values are already unslashed. They are, however, 370 * coming straight from `$_POST` and are not validated or sanitized in any way. 371 * 372 * @type string $file Relative path to file. 373 * @type string $plugin Path to the plugin file relative to the plugins directory. 374 * @type string $theme Theme being edited. 375 * @type string $newcontent New content for the file. 376 * @type string $nonce Nonce. 377 * } 378 * @return true|WP_Error True on success or `WP_Error` on failure. 379 */ 380 function wp_edit_theme_plugin_file( $args ) { 381 if ( empty( $args['file'] ) ) { 382 return new WP_Error( 'missing_file' ); 383 } 384 385 if ( 0 !== validate_file( $args['file'] ) ) { 386 return new WP_Error( 'bad_file' ); 387 } 388 389 if ( ! isset( $args['newcontent'] ) ) { 390 return new WP_Error( 'missing_content' ); 391 } 392 393 if ( ! isset( $args['nonce'] ) ) { 394 return new WP_Error( 'missing_nonce' ); 395 } 396 397 $file = $args['file']; 398 $content = $args['newcontent']; 399 400 $plugin = null; 401 $theme = null; 402 $real_file = null; 403 404 if ( ! empty( $args['plugin'] ) ) { 405 $plugin = $args['plugin']; 406 407 if ( ! current_user_can( 'edit_plugins' ) ) { 408 return new WP_Error( 'unauthorized', __( 'Sorry, you are not allowed to edit plugins for this site.' ) ); 409 } 410 411 if ( ! wp_verify_nonce( $args['nonce'], 'edit-plugin_' . $file ) ) { 412 return new WP_Error( 'nonce_failure' ); 413 } 414 415 if ( ! array_key_exists( $plugin, get_plugins() ) ) { 416 return new WP_Error( 'invalid_plugin' ); 417 } 418 419 if ( 0 !== validate_file( $file, get_plugin_files( $plugin ) ) ) { 420 return new WP_Error( 'bad_plugin_file_path', __( 'Sorry, that file cannot be edited.' ) ); 421 } 422 423 $editable_extensions = wp_get_plugin_file_editable_extensions( $plugin ); 424 425 $real_file = WP_PLUGIN_DIR . '/' . $file; 426 427 $is_active = in_array( 428 $plugin, 429 (array) get_option( 'active_plugins', array() ), 430 true 431 ); 432 433 } elseif ( ! empty( $args['theme'] ) ) { 434 $stylesheet = $args['theme']; 435 436 if ( 0 !== validate_file( $stylesheet ) ) { 437 return new WP_Error( 'bad_theme_path' ); 438 } 439 440 if ( ! current_user_can( 'edit_themes' ) ) { 441 return new WP_Error( 'unauthorized', __( 'Sorry, you are not allowed to edit templates for this site.' ) ); 442 } 443 444 $theme = wp_get_theme( $stylesheet ); 445 if ( ! $theme->exists() ) { 446 return new WP_Error( 'non_existent_theme', __( 'The requested theme does not exist.' ) ); 447 } 448 449 if ( ! wp_verify_nonce( $args['nonce'], 'edit-theme_' . $stylesheet . '_' . $file ) ) { 450 return new WP_Error( 'nonce_failure' ); 451 } 452 453 if ( $theme->errors() && 'theme_no_stylesheet' === $theme->errors()->get_error_code() ) { 454 return new WP_Error( 455 'theme_no_stylesheet', 456 __( 'The requested theme does not exist.' ) . ' ' . $theme->errors()->get_error_message() 457 ); 458 } 459 460 $editable_extensions = wp_get_theme_file_editable_extensions( $theme ); 461 462 $allowed_files = array(); 463 foreach ( $editable_extensions as $type ) { 464 switch ( $type ) { 465 case 'php': 466 $allowed_files = array_merge( $allowed_files, $theme->get_files( 'php', -1 ) ); 467 break; 468 case 'css': 469 $style_files = $theme->get_files( 'css', -1 ); 470 $allowed_files['style.css'] = $style_files['style.css']; 471 $allowed_files = array_merge( $allowed_files, $style_files ); 472 break; 473 default: 474 $allowed_files = array_merge( $allowed_files, $theme->get_files( $type, -1 ) ); 475 break; 476 } 477 } 478 479 // Compare based on relative paths. 480 if ( 0 !== validate_file( $file, array_keys( $allowed_files ) ) ) { 481 return new WP_Error( 'disallowed_theme_file', __( 'Sorry, that file cannot be edited.' ) ); 482 } 483 484 $real_file = $theme->get_stylesheet_directory() . '/' . $file; 485 486 $is_active = ( get_stylesheet() === $stylesheet || get_template() === $stylesheet ); 487 488 } else { 489 return new WP_Error( 'missing_theme_or_plugin' ); 490 } 491 492 // Ensure file is real. 493 if ( ! is_file( $real_file ) ) { 494 return new WP_Error( 'file_does_not_exist', __( 'File does not exist! Please double check the name and try again.' ) ); 495 } 496 497 // Ensure file extension is allowed. 498 $extension = null; 499 if ( preg_match( '/\.([^.]+)$/', $real_file, $matches ) ) { 500 $extension = strtolower( $matches[1] ); 501 if ( ! in_array( $extension, $editable_extensions, true ) ) { 502 return new WP_Error( 'illegal_file_type', __( 'Files of this type are not editable.' ) ); 503 } 504 } 505 506 $previous_content = file_get_contents( $real_file ); 507 508 if ( ! is_writable( $real_file ) ) { 509 return new WP_Error( 'file_not_writable' ); 510 } 511 512 $f = fopen( $real_file, 'w+' ); 513 514 if ( false === $f ) { 515 return new WP_Error( 'file_not_writable' ); 516 } 517 518 $written = fwrite( $f, $content ); 519 fclose( $f ); 520 521 if ( false === $written ) { 522 return new WP_Error( 'unable_to_write', __( 'Unable to write to file.' ) ); 523 } 524 525 wp_opcache_invalidate( $real_file, true ); 526 527 if ( $is_active && 'php' === $extension ) { 528 529 $scrape_key = md5( rand() ); 530 $transient = 'scrape_key_' . $scrape_key; 531 $scrape_nonce = (string) rand(); 532 // It shouldn't take more than 60 seconds to make the two loopback requests. 533 set_transient( $transient, $scrape_nonce, 60 ); 534 535 $cookies = wp_unslash( $_COOKIE ); 536 $scrape_params = array( 537 'wp_scrape_key' => $scrape_key, 538 'wp_scrape_nonce' => $scrape_nonce, 539 ); 540 $headers = array( 541 'Cache-Control' => 'no-cache', 542 ); 543 544 // Include Basic auth in loopback requests. 545 if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) { 546 $headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) ); 547 } 548 549 // Make sure PHP process doesn't die before loopback requests complete. 550 if ( function_exists( 'set_time_limit' ) ) { 551 set_time_limit( 5 * MINUTE_IN_SECONDS ); 552 } 553 554 // Time to wait for loopback requests to finish. 555 $timeout = 100; // 100 seconds. 556 557 $needle_start = "###### wp_scraping_result_start:$scrape_key ######"; 558 $needle_end = "###### wp_scraping_result_end:$scrape_key ######"; 559 560 // Attempt loopback request to editor to see if user just whitescreened themselves. 561 if ( $plugin ) { 562 $url = add_query_arg( compact( 'plugin', 'file' ), admin_url( 'plugin-editor.php' ) ); 563 } elseif ( isset( $stylesheet ) ) { 564 $url = add_query_arg( 565 array( 566 'theme' => $stylesheet, 567 'file' => $file, 568 ), 569 admin_url( 'theme-editor.php' ) 570 ); 571 } else { 572 $url = admin_url(); 573 } 574 575 if ( function_exists( 'session_status' ) && PHP_SESSION_ACTIVE === session_status() ) { 576 /* 577 * Close any active session to prevent HTTP requests from timing out 578 * when attempting to connect back to the site. 579 */ 580 session_write_close(); 581 } 582 583 $url = add_query_arg( $scrape_params, $url ); 584 585 /** This filter is documented in wp-includes/class-wp-http-streams.php */ 586 $sslverify = apply_filters( 'https_local_ssl_verify', false, $url ); 587 588 $r = wp_remote_get( $url, compact( 'cookies', 'headers', 'timeout', 'sslverify' ) ); 589 $body = wp_remote_retrieve_body( $r ); 590 $scrape_result_position = strpos( $body, $needle_start ); 591 592 $loopback_request_failure = array( 593 'code' => 'loopback_request_failed', 594 'message' => __( 'Unable to communicate back with site to check for fatal errors, so the PHP change was reverted. You will need to upload your PHP file change by some other means, such as by using SFTP.' ), 595 ); 596 $json_parse_failure = array( 597 'code' => 'json_parse_error', 598 ); 599 600 $result = null; 601 602 if ( false === $scrape_result_position ) { 603 $result = $loopback_request_failure; 604 } else { 605 $error_output = substr( $body, $scrape_result_position + strlen( $needle_start ) ); 606 $error_output = substr( $error_output, 0, strpos( $error_output, $needle_end ) ); 607 $result = json_decode( trim( $error_output ), true ); 608 if ( empty( $result ) ) { 609 $result = $json_parse_failure; 610 } 611 } 612 613 // Try making request to homepage as well to see if visitors have been whitescreened. 614 if ( true === $result ) { 615 $url = home_url( '/' ); 616 $url = add_query_arg( $scrape_params, $url ); 617 $r = wp_remote_get( $url, compact( 'cookies', 'headers', 'timeout', 'sslverify' ) ); 618 $body = wp_remote_retrieve_body( $r ); 619 $scrape_result_position = strpos( $body, $needle_start ); 620 621 if ( false === $scrape_result_position ) { 622 $result = $loopback_request_failure; 623 } else { 624 $error_output = substr( $body, $scrape_result_position + strlen( $needle_start ) ); 625 $error_output = substr( $error_output, 0, strpos( $error_output, $needle_end ) ); 626 $result = json_decode( trim( $error_output ), true ); 627 if ( empty( $result ) ) { 628 $result = $json_parse_failure; 629 } 630 } 631 } 632 633 delete_transient( $transient ); 634 635 if ( true !== $result ) { 636 // Roll-back file change. 637 file_put_contents( $real_file, $previous_content ); 638 wp_opcache_invalidate( $real_file, true ); 639 640 if ( ! isset( $result['message'] ) ) { 641 $message = __( 'An error occurred. Please try again later.' ); 642 } else { 643 $message = $result['message']; 644 unset( $result['message'] ); 645 } 646 647 return new WP_Error( 'php_error', $message, $result ); 648 } 649 } 650 651 if ( $theme instanceof WP_Theme ) { 652 $theme->cache_delete(); 653 } 654 655 return true; 656 } 657 658 659 /** 660 * Returns a filename of a temporary unique file. 661 * 662 * Please note that the calling function must delete or move the file. 663 * 664 * The filename is based off the passed parameter or defaults to the current unix timestamp, 665 * while the directory can either be passed as well, or by leaving it blank, default to a writable 666 * temporary directory. 667 * 668 * @since 2.6.0 669 * 670 * @param string $filename Optional. Filename to base the Unique file off. Default empty. 671 * @param string $dir Optional. Directory to store the file in. Default empty. 672 * @return string A writable filename. 673 */ 674 function wp_tempnam( $filename = '', $dir = '' ) { 675 if ( empty( $dir ) ) { 676 $dir = get_temp_dir(); 677 } 678 679 if ( empty( $filename ) || in_array( $filename, array( '.', '/', '\\' ), true ) ) { 680 $filename = uniqid(); 681 } 682 683 // Use the basename of the given file without the extension as the name for the temporary directory. 684 $temp_filename = basename( $filename ); 685 $temp_filename = preg_replace( '|\.[^.]*$|', '', $temp_filename ); 686 687 // If the folder is falsey, use its parent directory name instead. 688 if ( ! $temp_filename ) { 689 return wp_tempnam( dirname( $filename ), $dir ); 690 } 691 692 // Suffix some random data to avoid filename conflicts. 693 $temp_filename .= '-' . wp_generate_password( 6, false ); 694 $temp_filename .= '.tmp'; 695 $temp_filename = wp_unique_filename( $dir, $temp_filename ); 696 697 /* 698 * Filesystems typically have a limit of 255 characters for a filename. 699 * 700 * If the generated unique filename exceeds this, truncate the initial 701 * filename and try again. 702 * 703 * As it's possible that the truncated filename may exist, producing a 704 * suffix of "-1" or "-10" which could exceed the limit again, truncate 705 * it to 252 instead. 706 */ 707 $characters_over_limit = strlen( $temp_filename ) - 252; 708 if ( $characters_over_limit > 0 ) { 709 $filename = substr( $filename, 0, -$characters_over_limit ); 710 return wp_tempnam( $filename, $dir ); 711 } 712 713 $temp_filename = $dir . $temp_filename; 714 715 $fp = @fopen( $temp_filename, 'x' ); 716 717 if ( ! $fp && is_writable( $dir ) && file_exists( $temp_filename ) ) { 718 return wp_tempnam( $filename, $dir ); 719 } 720 721 if ( $fp ) { 722 fclose( $fp ); 723 } 724 725 return $temp_filename; 726 } 727 728 /** 729 * Makes sure that the file that was requested to be edited is allowed to be edited. 730 * 731 * Function will die if you are not allowed to edit the file. 732 * 733 * @since 1.5.0 734 * 735 * @param string $file File the user is attempting to edit. 736 * @param string[] $allowed_files Optional. Array of allowed files to edit. 737 * `$file` must match an entry exactly. 738 * @return string|null Returns the file name on success, null in case of absolute Windows drive paths, and dies on failure. 739 */ 740 function validate_file_to_edit( $file, $allowed_files = array() ) { 741 $code = validate_file( $file, $allowed_files ); 742 743 if ( ! $code ) { 744 return $file; 745 } 746 747 switch ( $code ) { 748 case 1: 749 wp_die( __( 'Sorry, that file cannot be edited.' ) ); 750 751 // case 2 : 752 // wp_die( __('Sorry, cannot call files with their real path.' )); 753 754 case 3: 755 wp_die( __( 'Sorry, that file cannot be edited.' ) ); 756 } 757 return null; 758 } 759 760 /** 761 * Handles PHP uploads in WordPress. 762 * 763 * Sanitizes file names, checks extensions for mime type, and moves the file 764 * to the appropriate directory within the uploads directory. 765 * 766 * @access private 767 * @since 4.0.0 768 * 769 * @see wp_handle_upload_error 770 * 771 * @param array $file { 772 * Reference to a single element from `$_FILES`. Call the function once for each uploaded file. 773 * 774 * @type string $name The original name of the file on the client machine. 775 * @type string $type The mime type of the file, if the browser provided this information. 776 * @type string $tmp_name The temporary filename of the file in which the uploaded file was stored on the server. 777 * @type int $size The size, in bytes, of the uploaded file. 778 * @type int $error The error code associated with this file upload. 779 * } 780 * @param array|false $overrides { 781 * An array of override parameters for this file, or boolean false if none are provided. 782 * 783 * @type callable $upload_error_handler Function to call when there is an error during the upload process. 784 * See {@see wp_handle_upload_error()}. 785 * @type callable $unique_filename_callback Function to call when determining a unique file name for the file. 786 * See {@see wp_unique_filename()}. 787 * @type string[] $upload_error_strings The strings that describe the error indicated in 788 * `$_FILES[{form field}]['error']`. 789 * @type bool $test_form Whether to test that the `$_POST['action']` parameter is as expected. 790 * @type bool $test_size Whether to test that the file size is greater than zero bytes. 791 * @type bool $test_type Whether to test that the mime type of the file is as expected. 792 * @type string[] $mimes Array of allowed mime types keyed by their file extension regex. 793 * } 794 * @param string $time Time formatted in 'yyyy/mm'. 795 * @param string $action Expected value for `$_POST['action']`. 796 * @return array { 797 * On success, returns an associative array of file attributes. 798 * On failure, returns `$overrides['upload_error_handler']( &$file, $message )` 799 * or `array( 'error' => $message )`. 800 * 801 * @type string $file Filename of the newly-uploaded file. 802 * @type string $url URL of the newly-uploaded file. 803 * @type string $type Mime type of the newly-uploaded file. 804 * } 805 * 806 * @phpstan-return array{ file: non-empty-string, url: non-empty-string, type: non-empty-string } 807 * |array{ error: non-empty-string } 808 */ 809 function _wp_handle_upload( &$file, $overrides, $time, $action ) { 810 // The default error handler. 811 if ( ! function_exists( 'wp_handle_upload_error' ) ) { 812 function wp_handle_upload_error( &$file, $message ) { 813 return array( 'error' => $message ); 814 } 815 } 816 817 /** 818 * Filters the data for a file before it is uploaded to WordPress. 819 * 820 * The dynamic portion of the hook name, `$action`, refers to the post action. 821 * 822 * Possible hook names include: 823 * 824 * - `wp_handle_sideload_prefilter` 825 * - `wp_handle_upload_prefilter` 826 * 827 * @since 2.9.0 as 'wp_handle_upload_prefilter'. 828 * @since 4.0.0 Converted to a dynamic hook with `$action`. 829 * 830 * @param array $file { 831 * Reference to a single element from `$_FILES`. 832 * 833 * @type string $name The original name of the file on the client machine. 834 * @type string $type The mime type of the file, if the browser provided this information. 835 * @type string $tmp_name The temporary filename of the file in which the uploaded file was stored on the server. 836 * @type int $size The size, in bytes, of the uploaded file. 837 * @type int $error The error code associated with this file upload. 838 * } 839 */ 840 $file = apply_filters( "{$action}_prefilter", $file ); 841 842 /** 843 * Filters the override parameters for a file before it is uploaded to WordPress. 844 * 845 * The dynamic portion of the hook name, `$action`, refers to the post action. 846 * 847 * Possible hook names include: 848 * 849 * - `wp_handle_sideload_overrides` 850 * - `wp_handle_upload_overrides` 851 * 852 * @since 5.7.0 853 * 854 * @param array|false $overrides An array of override parameters for this file. Boolean false if none are 855 * provided. See {@see _wp_handle_upload()}. 856 * @param array $file { 857 * Reference to a single element from `$_FILES`. 858 * 859 * @type string $name The original name of the file on the client machine. 860 * @type string $type The mime type of the file, if the browser provided this information. 861 * @type string $tmp_name The temporary filename of the file in which the uploaded file was stored on the server. 862 * @type int $size The size, in bytes, of the uploaded file. 863 * @type int $error The error code associated with this file upload. 864 * } 865 */ 866 $overrides = apply_filters( "{$action}_overrides", $overrides, $file ); 867 868 // You may define your own function and pass the name in $overrides['upload_error_handler']. 869 $upload_error_handler = 'wp_handle_upload_error'; 870 if ( isset( $overrides['upload_error_handler'] ) ) { 871 $upload_error_handler = $overrides['upload_error_handler']; 872 } 873 874 // You may have had one or more 'wp_handle_upload_prefilter' functions error out the file. Handle that gracefully. 875 if ( isset( $file['error'] ) && ! is_numeric( $file['error'] ) && $file['error'] ) { 876 return call_user_func_array( $upload_error_handler, array( &$file, $file['error'] ) ); 877 } 878 879 // Install user overrides. Did we mention that this voids your warranty? 880 881 // You may define your own function and pass the name in $overrides['unique_filename_callback']. 882 $unique_filename_callback = null; 883 if ( isset( $overrides['unique_filename_callback'] ) ) { 884 $unique_filename_callback = $overrides['unique_filename_callback']; 885 } 886 887 /* 888 * This may not have originally been intended to be overridable, 889 * but historically has been. 890 */ 891 if ( isset( $overrides['upload_error_strings'] ) ) { 892 $upload_error_strings = $overrides['upload_error_strings']; 893 } else { 894 // Courtesy of php.net, the strings that describe the error indicated in $_FILES[{form field}]['error']. 895 $upload_error_strings = array( 896 false, 897 sprintf( 898 /* translators: 1: upload_max_filesize, 2: php.ini */ 899 __( 'The uploaded file exceeds the %1$s directive in %2$s.' ), 900 'upload_max_filesize', 901 'php.ini' 902 ), 903 sprintf( 904 /* translators: %s: MAX_FILE_SIZE */ 905 __( 'The uploaded file exceeds the %s directive that was specified in the HTML form.' ), 906 'MAX_FILE_SIZE' 907 ), 908 __( 'The uploaded file was only partially uploaded.' ), 909 __( 'No file was uploaded.' ), 910 '', 911 __( 'Missing a temporary folder.' ), 912 __( 'Failed to write file to disk.' ), 913 __( 'File upload stopped by extension.' ), 914 ); 915 } 916 917 // All tests are on by default. Most can be turned off by $overrides[{test_name}] = false; 918 $test_form = $overrides['test_form'] ?? true; 919 $test_size = $overrides['test_size'] ?? true; 920 921 // If you override this, you must provide $ext and $type!! 922 $test_type = $overrides['test_type'] ?? true; 923 $mimes = $overrides['mimes'] ?? null; 924 925 // A correct form post will pass this test. 926 if ( $test_form && ( ! isset( $_POST['action'] ) || $_POST['action'] !== $action ) ) { 927 return call_user_func_array( $upload_error_handler, array( &$file, __( 'Invalid form submission.' ) ) ); 928 } 929 930 // A successful upload will pass this test. It makes no sense to override this one. 931 if ( isset( $file['error'] ) && $file['error'] > 0 ) { 932 return call_user_func_array( $upload_error_handler, array( &$file, $upload_error_strings[ $file['error'] ] ) ); 933 } 934 935 // A properly uploaded file will pass this test. There should be no reason to override this one. 936 $test_uploaded_file = 'wp_handle_upload' === $action ? is_uploaded_file( $file['tmp_name'] ) : @is_readable( $file['tmp_name'] ); 937 if ( ! $test_uploaded_file ) { 938 return call_user_func_array( $upload_error_handler, array( &$file, __( 'Specified file failed upload test.' ) ) ); 939 } 940 941 $test_file_size = 'wp_handle_upload' === $action ? $file['size'] : filesize( $file['tmp_name'] ); 942 // A non-empty file will pass this test. 943 if ( $test_size && ! ( $test_file_size > 0 ) ) { 944 if ( is_multisite() ) { 945 $error_msg = __( 'File is empty. Please upload something more substantial.' ); 946 } else { 947 $error_msg = sprintf( 948 /* translators: 1: php.ini, 2: post_max_size, 3: upload_max_filesize */ 949 __( 'File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your %1$s file or by %2$s being defined as smaller than %3$s in %1$s.' ), 950 'php.ini', 951 'post_max_size', 952 'upload_max_filesize' 953 ); 954 } 955 956 return call_user_func_array( $upload_error_handler, array( &$file, $error_msg ) ); 957 } 958 959 // A correct MIME type will pass this test. Override $mimes or use the upload_mimes filter. 960 if ( $test_type ) { 961 $wp_filetype = wp_check_filetype_and_ext( $file['tmp_name'], $file['name'], $mimes ); 962 $ext = empty( $wp_filetype['ext'] ) ? '' : $wp_filetype['ext']; 963 $type = empty( $wp_filetype['type'] ) ? '' : $wp_filetype['type']; 964 $proper_filename = empty( $wp_filetype['proper_filename'] ) ? '' : $wp_filetype['proper_filename']; 965 966 // Check to see if wp_check_filetype_and_ext() determined the filename was incorrect. 967 if ( $proper_filename ) { 968 $file['name'] = $proper_filename; 969 } 970 971 if ( ( ! $type || ! $ext ) && ! current_user_can( 'unfiltered_upload' ) ) { 972 return call_user_func_array( $upload_error_handler, array( &$file, __( 'Sorry, you are not allowed to upload this file type.' ) ) ); 973 } 974 975 if ( ! $type ) { 976 $type = $file['type']; 977 } 978 } else { 979 $type = ''; 980 } 981 982 /* 983 * A writable uploads dir will pass this test. Again, there's no point 984 * overriding this one. 985 */ 986 $uploads = wp_upload_dir( $time ); 987 if ( ! ( $uploads && false === $uploads['error'] ) ) { 988 return call_user_func_array( $upload_error_handler, array( &$file, $uploads['error'] ) ); 989 } 990 991 $filename = wp_unique_filename( $uploads['path'], $file['name'], $unique_filename_callback ); 992 993 // Move the file to the uploads dir. 994 $new_file = $uploads['path'] . "/$filename"; 995 996 /** 997 * Filters whether to short-circuit moving the uploaded file after passing all checks. 998 * 999 * If a non-null value is returned from the filter, moving the file and any related 1000 * error reporting will be completely skipped. 1001 * 1002 * @since 4.9.0 1003 * 1004 * @param mixed $move_new_file If null (default) move the file after the upload. 1005 * @param array $file { 1006 * Reference to a single element from `$_FILES`. 1007 * 1008 * @type string $name The original name of the file on the client machine. 1009 * @type string $type The mime type of the file, if the browser provided this information. 1010 * @type string $tmp_name The temporary filename of the file in which the uploaded file was stored on the server. 1011 * @type int $size The size, in bytes, of the uploaded file. 1012 * @type int $error The error code associated with this file upload. 1013 * } 1014 * @param string $new_file Filename of the newly-uploaded file. 1015 * @param string $type Mime type of the newly-uploaded file. 1016 */ 1017 $move_new_file = apply_filters( 'pre_move_uploaded_file', null, $file, $new_file, $type ); 1018 1019 if ( null === $move_new_file ) { 1020 if ( 'wp_handle_upload' === $action ) { 1021 $move_new_file = @move_uploaded_file( $file['tmp_name'], $new_file ); 1022 } else { 1023 // Use copy and unlink because rename breaks streams. 1024 // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged 1025 $move_new_file = @copy( $file['tmp_name'], $new_file ); 1026 unlink( $file['tmp_name'] ); 1027 } 1028 1029 if ( false === $move_new_file ) { 1030 if ( str_starts_with( $uploads['basedir'], ABSPATH ) ) { 1031 $error_path = str_replace( ABSPATH, '', $uploads['basedir'] ) . $uploads['subdir']; 1032 } else { 1033 $error_path = basename( $uploads['basedir'] ) . $uploads['subdir']; 1034 } 1035 1036 return $upload_error_handler( 1037 $file, 1038 sprintf( 1039 /* translators: %s: Destination file path. */ 1040 __( 'The uploaded file could not be moved to %s.' ), 1041 $error_path 1042 ) 1043 ); 1044 } 1045 } 1046 1047 // Set correct file permissions. 1048 $stat = stat( dirname( $new_file ) ); 1049 $perms = $stat['mode'] & 0000666; 1050 chmod( $new_file, $perms ); 1051 1052 // Compute the URL. 1053 $url = $uploads['url'] . "/$filename"; 1054 1055 if ( is_multisite() ) { 1056 clean_dirsize_cache( $new_file ); 1057 } 1058 1059 /** 1060 * Filters the data array for the uploaded file. 1061 * 1062 * @since 2.1.0 1063 * 1064 * @param array $upload { 1065 * Array of upload data. 1066 * 1067 * @type string $file Filename of the newly-uploaded file. 1068 * @type string $url URL of the newly-uploaded file. 1069 * @type string $type Mime type of the newly-uploaded file. 1070 * } 1071 * @param string $context The type of upload action. Values include 'upload' or 'sideload'. 1072 */ 1073 return apply_filters( 1074 'wp_handle_upload', 1075 array( 1076 'file' => $new_file, 1077 'url' => $url, 1078 'type' => $type, 1079 ), 1080 'wp_handle_sideload' === $action ? 'sideload' : 'upload' 1081 ); 1082 } 1083 1084 /** 1085 * Wrapper for _wp_handle_upload(). 1086 * 1087 * Passes the {@see 'wp_handle_upload'} action. 1088 * 1089 * @since 2.0.0 1090 * 1091 * @see _wp_handle_upload() 1092 * 1093 * @param array $file Reference to a single element of `$_FILES`. 1094 * Call the function once for each uploaded file. 1095 * See _wp_handle_upload() for accepted values. 1096 * @param array|false $overrides Optional. An associative array of names => values 1097 * to override default variables. Default false. 1098 * See _wp_handle_upload() for accepted values. 1099 * @param string|null $time Optional. Time formatted in 'yyyy/mm'. Default null. 1100 * @return array See _wp_handle_upload() for return value. 1101 * 1102 * @phpstan-return array{ file: non-empty-string, url: non-empty-string, type: non-empty-string } 1103 * |array{ error: non-empty-string } 1104 */ 1105 function wp_handle_upload( &$file, $overrides = false, $time = null ) { 1106 /* 1107 * $_POST['action'] must be set and its value must equal $overrides['action'] 1108 * or this: 1109 */ 1110 $action = $overrides['action'] ?? 'wp_handle_upload'; 1111 return _wp_handle_upload( $file, $overrides, $time, $action ); 1112 } 1113 1114 /** 1115 * Wrapper for _wp_handle_upload(). 1116 * 1117 * Passes the {@see 'wp_handle_sideload'} action. 1118 * 1119 * @since 2.6.0 1120 * 1121 * @see _wp_handle_upload() 1122 * 1123 * @param array $file Reference to a single element of `$_FILES`. 1124 * Call the function once for each uploaded file. 1125 * See _wp_handle_upload() for accepted values. 1126 * @param array|false $overrides Optional. An associative array of names => values 1127 * to override default variables. Default false. 1128 * See _wp_handle_upload() for accepted values. 1129 * @param string|null $time Optional. Time formatted in 'yyyy/mm'. Default null. 1130 * @return array See _wp_handle_upload() for return value. 1131 * 1132 * @phpstan-return array{ file: non-empty-string, url: non-empty-string, type: non-empty-string } 1133 * |array{ error: non-empty-string } 1134 */ 1135 function wp_handle_sideload( &$file, $overrides = false, $time = null ) { 1136 /* 1137 * $_POST['action'] must be set and its value must equal $overrides['action'] 1138 * or this: 1139 */ 1140 $action = $overrides['action'] ?? 'wp_handle_sideload'; 1141 return _wp_handle_upload( $file, $overrides, $time, $action ); 1142 } 1143 1144 /** 1145 * Downloads a URL to a local temporary file using the WordPress HTTP API. 1146 * 1147 * Please note that the calling function must delete or move the file. 1148 * 1149 * @since 2.5.0 1150 * @since 5.2.0 Signature Verification with SoftFail was added. 1151 * @since 5.9.0 Support for Content-Disposition filename was added. 1152 * 1153 * @param string $url The URL of the file to download. 1154 * @param int $timeout The timeout for the request to download the file. 1155 * Default 300 seconds. 1156 * @param bool $signature_verification Whether to perform Signature Verification. 1157 * Default false. 1158 * @return string|WP_Error Filename on success, WP_Error on failure. 1159 */ 1160 function download_url( $url, $timeout = 300, $signature_verification = false ) { 1161 // WARNING: The file is not automatically deleted, the script must delete or move the file. 1162 if ( ! $url ) { 1163 return new WP_Error( 'http_no_url', __( 'No URL Provided.' ) ); 1164 } 1165 1166 $url_path = parse_url( $url, PHP_URL_PATH ); 1167 $url_filename = ''; 1168 if ( is_string( $url_path ) && '' !== $url_path ) { 1169 $url_filename = basename( $url_path ); 1170 } 1171 1172 $tmpfname = wp_tempnam( $url_filename ); 1173 if ( ! $tmpfname ) { 1174 return new WP_Error( 'http_no_file', __( 'Could not create temporary file.' ) ); 1175 } 1176 1177 $response = wp_safe_remote_get( 1178 $url, 1179 array( 1180 'timeout' => $timeout, 1181 'stream' => true, 1182 'filename' => $tmpfname, 1183 ) 1184 ); 1185 1186 if ( is_wp_error( $response ) ) { 1187 unlink( $tmpfname ); 1188 return $response; 1189 } 1190 1191 $response_code = wp_remote_retrieve_response_code( $response ); 1192 1193 if ( 200 !== $response_code ) { 1194 $data = array( 1195 'code' => $response_code, 1196 ); 1197 1198 // Retrieve a sample of the response body for debugging purposes. 1199 $tmpf = fopen( $tmpfname, 'rb' ); 1200 1201 if ( $tmpf ) { 1202 /** 1203 * Filters the maximum error response body size in `download_url()`. 1204 * 1205 * @since 5.1.0 1206 * 1207 * @see download_url() 1208 * 1209 * @param int $size The maximum error response body size. Default 1 KB. 1210 */ 1211 $response_size = apply_filters( 'download_url_error_max_body_size', KB_IN_BYTES ); 1212 1213 $data['body'] = fread( $tmpf, $response_size ); 1214 fclose( $tmpf ); 1215 } 1216 1217 unlink( $tmpfname ); 1218 1219 return new WP_Error( 'http_404', trim( wp_remote_retrieve_response_message( $response ) ), $data ); 1220 } 1221 1222 $content_disposition = wp_remote_retrieve_header( $response, 'Content-Disposition' ); 1223 1224 if ( $content_disposition ) { 1225 $content_disposition = strtolower( $content_disposition ); 1226 1227 if ( str_starts_with( $content_disposition, 'attachment; filename=' ) ) { 1228 $tmpfname_disposition = sanitize_file_name( substr( $content_disposition, 21 ) ); 1229 } else { 1230 $tmpfname_disposition = ''; 1231 } 1232 1233 // Potential file name must be valid string. 1234 if ( $tmpfname_disposition && is_string( $tmpfname_disposition ) 1235 && ( 0 === validate_file( $tmpfname_disposition ) ) 1236 ) { 1237 $tmpfname_disposition = dirname( $tmpfname ) . '/' . $tmpfname_disposition; 1238 1239 if ( rename( $tmpfname, $tmpfname_disposition ) ) { 1240 $tmpfname = $tmpfname_disposition; 1241 } 1242 1243 if ( ( $tmpfname !== $tmpfname_disposition ) && file_exists( $tmpfname_disposition ) ) { 1244 unlink( $tmpfname_disposition ); 1245 } 1246 } 1247 } 1248 1249 $mime_type = wp_remote_retrieve_header( $response, 'content-type' ); 1250 if ( $mime_type && 'tmp' === pathinfo( $tmpfname, PATHINFO_EXTENSION ) ) { 1251 $valid_mime_types = array_flip( get_allowed_mime_types() ); 1252 if ( ! empty( $valid_mime_types[ $mime_type ] ) ) { 1253 $extensions = explode( '|', $valid_mime_types[ $mime_type ] ); 1254 $new_image_name = substr( $tmpfname, 0, -4 ) . ".{$extensions[0]}"; 1255 if ( 0 === validate_file( $new_image_name ) ) { 1256 if ( rename( $tmpfname, $new_image_name ) ) { 1257 $tmpfname = $new_image_name; 1258 } 1259 1260 if ( ( $tmpfname !== $new_image_name ) && file_exists( $new_image_name ) ) { 1261 unlink( $new_image_name ); 1262 } 1263 } 1264 } 1265 } 1266 1267 $content_md5 = wp_remote_retrieve_header( $response, 'Content-MD5' ); 1268 1269 if ( $content_md5 ) { 1270 $md5_check = verify_file_md5( $tmpfname, $content_md5 ); 1271 1272 if ( is_wp_error( $md5_check ) ) { 1273 unlink( $tmpfname ); 1274 return $md5_check; 1275 } 1276 } 1277 1278 // If the caller expects signature verification to occur, check to see if this URL supports it. 1279 if ( $signature_verification ) { 1280 /** 1281 * Filters the list of hosts which should have Signature Verification attempted on. 1282 * 1283 * @since 5.2.0 1284 * 1285 * @param string[] $hostnames List of hostnames. 1286 */ 1287 $signed_hostnames = apply_filters( 'wp_signature_hosts', array( 'wordpress.org', 'downloads.wordpress.org', 's.w.org' ) ); 1288 1289 $signature_verification = in_array( parse_url( $url, PHP_URL_HOST ), $signed_hostnames, true ); 1290 } 1291 1292 // Perform signature validation if supported. 1293 if ( $signature_verification ) { 1294 $signature = wp_remote_retrieve_header( $response, 'X-Content-Signature' ); 1295 1296 if ( ! $signature ) { 1297 /* 1298 * Retrieve signatures from a file if the header wasn't included. 1299 * WordPress.org stores signatures at $package_url.sig. 1300 */ 1301 1302 $signature_url = false; 1303 1304 if ( is_string( $url_path ) && ( str_ends_with( $url_path, '.zip' ) || str_ends_with( $url_path, '.tar.gz' ) ) ) { 1305 $signature_url = str_replace( $url_path, $url_path . '.sig', $url ); 1306 } 1307 1308 /** 1309 * Filters the URL where the signature for a file is located. 1310 * 1311 * @since 5.2.0 1312 * 1313 * @param false|string $signature_url The URL where signatures can be found for a file, or false if none are known. 1314 * @param string $url The URL being verified. 1315 */ 1316 $signature_url = apply_filters( 'wp_signature_url', $signature_url, $url ); 1317 1318 if ( $signature_url ) { 1319 $signature_request = wp_safe_remote_get( 1320 $signature_url, 1321 array( 1322 'limit_response_size' => 10 * KB_IN_BYTES, // 10KB should be large enough for quite a few signatures. 1323 ) 1324 ); 1325 1326 if ( ! is_wp_error( $signature_request ) && 200 === wp_remote_retrieve_response_code( $signature_request ) ) { 1327 $signature = explode( "\n", wp_remote_retrieve_body( $signature_request ) ); 1328 } 1329 } 1330 } 1331 1332 // Perform the checks. 1333 $signature_verification = verify_file_signature( $tmpfname, $signature, $url_filename ); 1334 } 1335 1336 if ( is_wp_error( $signature_verification ) ) { 1337 if ( 1338 /** 1339 * Filters whether Signature Verification failures should be allowed to soft fail. 1340 * 1341 * WARNING: This may be removed from a future release. 1342 * 1343 * @since 5.2.0 1344 * 1345 * @param bool $signature_softfail If a softfail is allowed. 1346 * @param string $url The url being accessed. 1347 */ 1348 apply_filters( 'wp_signature_softfail', true, $url ) 1349 ) { 1350 $signature_verification->add_data( $tmpfname, 'softfail-filename' ); 1351 } else { 1352 // Hard-fail. 1353 unlink( $tmpfname ); 1354 } 1355 1356 return $signature_verification; 1357 } 1358 1359 return $tmpfname; 1360 } 1361 1362 /** 1363 * Calculates and compares the MD5 of a file to its expected value. 1364 * 1365 * @since 3.7.0 1366 * 1367 * @param string $filename The filename to check the MD5 of. 1368 * @param string $expected_md5 The expected MD5 of the file, either a base64-encoded raw md5, 1369 * or a hex-encoded md5. 1370 * @return bool|WP_Error True on success, false when the MD5 format is unknown/unexpected, 1371 * WP_Error on failure. 1372 */ 1373 function verify_file_md5( $filename, $expected_md5 ) { 1374 if ( 32 === strlen( $expected_md5 ) ) { 1375 $expected_raw_md5 = pack( 'H*', $expected_md5 ); 1376 } elseif ( 24 === strlen( $expected_md5 ) ) { 1377 $expected_raw_md5 = base64_decode( $expected_md5 ); 1378 } else { 1379 return false; // Unknown format. 1380 } 1381 1382 $file_md5 = md5_file( $filename, true ); 1383 1384 if ( $file_md5 === $expected_raw_md5 ) { 1385 return true; 1386 } 1387 1388 return new WP_Error( 1389 'md5_mismatch', 1390 sprintf( 1391 /* translators: 1: File checksum, 2: Expected checksum value. */ 1392 __( 'The checksum of the file (%1$s) does not match the expected checksum value (%2$s).' ), 1393 bin2hex( $file_md5 ), 1394 bin2hex( $expected_raw_md5 ) 1395 ) 1396 ); 1397 } 1398 1399 /** 1400 * Verifies the contents of a file against its ED25519 signature. 1401 * 1402 * @since 5.2.0 1403 * 1404 * @param string $filename The file to validate. 1405 * @param string|array $signatures A Signature provided for the file. 1406 * @param string|false $filename_for_errors Optional. A friendly filename for errors. 1407 * @return bool|WP_Error True on success, false if verification not attempted, 1408 * or WP_Error describing an error condition. 1409 */ 1410 function verify_file_signature( $filename, $signatures, $filename_for_errors = false ) { 1411 if ( ! $filename_for_errors ) { 1412 $filename_for_errors = wp_basename( $filename ); 1413 } 1414 1415 // Check we can process signatures. 1416 if ( ! function_exists( 'sodium_crypto_sign_verify_detached' ) || ! in_array( 'sha384', array_map( 'strtolower', hash_algos() ), true ) ) { 1417 return new WP_Error( 1418 'signature_verification_unsupported', 1419 sprintf( 1420 /* translators: %s: The filename of the package. */ 1421 __( 'The authenticity of %s could not be verified as signature verification is unavailable on this system.' ), 1422 '<span class="code">' . esc_html( $filename_for_errors ) . '</span>' 1423 ), 1424 ( ! function_exists( 'sodium_crypto_sign_verify_detached' ) ? 'sodium_crypto_sign_verify_detached' : 'sha384' ) 1425 ); 1426 } 1427 1428 // Verify runtime speed of Sodium_Compat is acceptable. 1429 if ( ! extension_loaded( 'sodium' ) && ! ParagonIE_Sodium_Compat::polyfill_is_fast() ) { 1430 $sodium_compat_is_fast = false; 1431 1432 // Allow for an old version of Sodium_Compat being loaded before the bundled WordPress one. 1433 if ( method_exists( 'ParagonIE_Sodium_Compat', 'runtime_speed_test' ) ) { 1434 /* 1435 * Run `ParagonIE_Sodium_Compat::runtime_speed_test()` in optimized integer mode, 1436 * as that's what WordPress utilizes during signing verifications. 1437 */ 1438 // phpcs:disable WordPress.NamingConventions.ValidVariableName 1439 $old_fastMult = ParagonIE_Sodium_Compat::$fastMult; 1440 ParagonIE_Sodium_Compat::$fastMult = true; 1441 $sodium_compat_is_fast = ParagonIE_Sodium_Compat::runtime_speed_test( 100, 10 ); 1442 ParagonIE_Sodium_Compat::$fastMult = $old_fastMult; 1443 // phpcs:enable 1444 } 1445 1446 /* 1447 * This cannot be performed in a reasonable amount of time. 1448 * https://github.com/paragonie/sodium_compat#help-sodium_compat-is-slow-how-can-i-make-it-fast 1449 */ 1450 if ( ! $sodium_compat_is_fast ) { 1451 return new WP_Error( 1452 'signature_verification_unsupported', 1453 sprintf( 1454 /* translators: %s: The filename of the package. */ 1455 __( 'The authenticity of %s could not be verified as signature verification is unavailable on this system.' ), 1456 '<span class="code">' . esc_html( $filename_for_errors ) . '</span>' 1457 ), 1458 array( 1459 'php' => PHP_VERSION, 1460 'sodium' => defined( 'SODIUM_LIBRARY_VERSION' ) ? SODIUM_LIBRARY_VERSION : ( defined( 'ParagonIE_Sodium_Compat::VERSION_STRING' ) ? ParagonIE_Sodium_Compat::VERSION_STRING : false ), 1461 'polyfill_is_fast' => false, 1462 'max_execution_time' => ini_get( 'max_execution_time' ), 1463 ) 1464 ); 1465 } 1466 } 1467 1468 if ( ! $signatures ) { 1469 return new WP_Error( 1470 'signature_verification_no_signature', 1471 sprintf( 1472 /* translators: %s: The filename of the package. */ 1473 __( 'The authenticity of %s could not be verified as no signature was found.' ), 1474 '<span class="code">' . esc_html( $filename_for_errors ) . '</span>' 1475 ), 1476 array( 1477 'filename' => $filename_for_errors, 1478 ) 1479 ); 1480 } 1481 1482 $trusted_keys = wp_trusted_keys(); 1483 $file_hash = hash_file( 'sha384', $filename, true ); 1484 1485 mbstring_binary_safe_encoding(); 1486 1487 $skipped_key = 0; 1488 $skipped_signature = 0; 1489 1490 foreach ( (array) $signatures as $signature ) { 1491 $signature_raw = base64_decode( $signature ); 1492 1493 // Ensure only valid-length signatures are considered. 1494 if ( SODIUM_CRYPTO_SIGN_BYTES !== strlen( $signature_raw ) ) { 1495 ++$skipped_signature; 1496 continue; 1497 } 1498 1499 foreach ( (array) $trusted_keys as $key ) { 1500 $key_raw = base64_decode( $key ); 1501 1502 // Only pass valid public keys through. 1503 if ( SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES !== strlen( $key_raw ) ) { 1504 ++$skipped_key; 1505 continue; 1506 } 1507 1508 if ( sodium_crypto_sign_verify_detached( $signature_raw, $file_hash, $key_raw ) ) { 1509 reset_mbstring_encoding(); 1510 return true; 1511 } 1512 } 1513 } 1514 1515 reset_mbstring_encoding(); 1516 1517 return new WP_Error( 1518 'signature_verification_failed', 1519 sprintf( 1520 /* translators: %s: The filename of the package. */ 1521 __( 'The authenticity of %s could not be verified.' ), 1522 '<span class="code">' . esc_html( $filename_for_errors ) . '</span>' 1523 ), 1524 // Error data helpful for debugging: 1525 array( 1526 'filename' => $filename_for_errors, 1527 'keys' => $trusted_keys, 1528 'signatures' => $signatures, 1529 'hash' => bin2hex( $file_hash ), 1530 'skipped_key' => $skipped_key, 1531 'skipped_sig' => $skipped_signature, 1532 'php' => PHP_VERSION, 1533 'sodium' => defined( 'SODIUM_LIBRARY_VERSION' ) ? SODIUM_LIBRARY_VERSION : ( defined( 'ParagonIE_Sodium_Compat::VERSION_STRING' ) ? ParagonIE_Sodium_Compat::VERSION_STRING : false ), 1534 ) 1535 ); 1536 } 1537 1538 /** 1539 * Retrieves the list of signing keys trusted by WordPress. 1540 * 1541 * @since 5.2.0 1542 * 1543 * @return string[] Array of base64-encoded signing keys. 1544 */ 1545 function wp_trusted_keys() { 1546 $trusted_keys = array(); 1547 1548 if ( time() < 1617235200 ) { 1549 // WordPress.org Key #1 - This key is only valid before April 1st, 2021. 1550 $trusted_keys[] = 'fRPyrxb/MvVLbdsYi+OOEv4xc+Eqpsj+kkAS6gNOkI0='; 1551 } 1552 1553 // TODO: Add key #2 with longer expiration. 1554 1555 /** 1556 * Filters the valid signing keys used to verify the contents of files. 1557 * 1558 * @since 5.2.0 1559 * 1560 * @param string[] $trusted_keys The trusted keys that may sign packages. 1561 */ 1562 return apply_filters( 'wp_trusted_keys', $trusted_keys ); 1563 } 1564 1565 /** 1566 * Determines whether the given file is a valid ZIP file. 1567 * 1568 * This function does not test to ensure that a file exists. Non-existent files 1569 * are not valid ZIPs, so those will also return false. 1570 * 1571 * @since 6.4.4 1572 * 1573 * @param string $file Full path to the ZIP file. 1574 * @return bool Whether the file is a valid ZIP file. 1575 */ 1576 function wp_zip_file_is_valid( $file ) { 1577 /** This filter is documented in wp-admin/includes/file.php */ 1578 if ( class_exists( 'ZipArchive', false ) && apply_filters( 'unzip_file_use_ziparchive', true ) ) { 1579 $archive = new ZipArchive(); 1580 $archive_is_valid = $archive->open( $file, ZipArchive::CHECKCONS ); 1581 if ( true === $archive_is_valid ) { 1582 $archive->close(); 1583 return true; 1584 } 1585 } 1586 1587 // Fall through to PclZip if ZipArchive is not available, or encountered an error opening the file. 1588 require_once ABSPATH . 'wp-admin/includes/class-pclzip.php'; 1589 1590 $archive = new PclZip( $file ); 1591 $archive_is_valid = is_array( $archive->properties() ); 1592 1593 return $archive_is_valid; 1594 } 1595 1596 /** 1597 * Unzips a specified ZIP file to a location on the filesystem via the WordPress 1598 * Filesystem Abstraction. 1599 * 1600 * Assumes that WP_Filesystem() has already been called and set up. Does not extract 1601 * a root-level __MACOSX directory, if present. 1602 * 1603 * Attempts to increase the PHP memory limit to 256M before uncompressing. However, 1604 * the most memory required shouldn't be much larger than the archive itself. 1605 * 1606 * @since 2.5.0 1607 * 1608 * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. 1609 * 1610 * @param string $file Full path and filename of ZIP archive. 1611 * @param string $to Full path on the filesystem to extract archive to. 1612 * @return true|WP_Error True on success, WP_Error on failure. 1613 */ 1614 function unzip_file( $file, $to ) { 1615 global $wp_filesystem; 1616 1617 if ( ! $wp_filesystem || ! is_object( $wp_filesystem ) ) { 1618 return new WP_Error( 'fs_unavailable', __( 'Could not access filesystem.' ) ); 1619 } 1620 1621 // Unzip can use a lot of memory, but not this much hopefully. 1622 wp_raise_memory_limit( 'admin' ); 1623 1624 $needed_dirs = array(); 1625 $to = trailingslashit( $to ); 1626 1627 // Determine any parent directories needed (of the upgrade directory). 1628 if ( ! $wp_filesystem->is_dir( $to ) ) { // Only do parents if no children exist. 1629 $path = preg_split( '![/\\\]!', untrailingslashit( $to ) ); 1630 for ( $i = count( $path ); $i >= 0; $i-- ) { 1631 if ( empty( $path[ $i ] ) ) { 1632 continue; 1633 } 1634 1635 $dir = implode( '/', array_slice( $path, 0, $i + 1 ) ); 1636 if ( preg_match( '!^[a-z]:$!i', $dir ) ) { // Skip it if it looks like a Windows Drive letter. 1637 continue; 1638 } 1639 1640 if ( ! $wp_filesystem->is_dir( $dir ) ) { 1641 $needed_dirs[] = $dir; 1642 } else { 1643 break; // A folder exists, therefore we don't need to check the levels below this. 1644 } 1645 } 1646 } 1647 1648 /** 1649 * Filters whether to use ZipArchive to unzip archives. 1650 * 1651 * @since 3.0.0 1652 * 1653 * @param bool $ziparchive Whether to use ZipArchive. Default true. 1654 */ 1655 if ( class_exists( 'ZipArchive', false ) && apply_filters( 'unzip_file_use_ziparchive', true ) ) { 1656 $result = _unzip_file_ziparchive( $file, $to, $needed_dirs ); 1657 if ( true === $result ) { 1658 return $result; 1659 } elseif ( is_wp_error( $result ) ) { 1660 if ( 'incompatible_archive' !== $result->get_error_code() ) { 1661 return $result; 1662 } 1663 } 1664 } 1665 // Fall through to PclZip if ZipArchive is not available, or encountered an error opening the file. 1666 return _unzip_file_pclzip( $file, $to, $needed_dirs ); 1667 } 1668 1669 /** 1670 * Attempts to unzip an archive using the ZipArchive class. 1671 * 1672 * This function should not be called directly, use `unzip_file()` instead. 1673 * 1674 * Assumes that WP_Filesystem() has already been called and set up. 1675 * 1676 * @since 3.0.0 1677 * @access private 1678 * 1679 * @see unzip_file() 1680 * 1681 * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. 1682 * 1683 * @param string $file Full path and filename of ZIP archive. 1684 * @param string $to Full path on the filesystem to extract archive to. 1685 * @param string[] $needed_dirs A partial list of required folders needed to be created. 1686 * @return true|WP_Error True on success, WP_Error on failure. 1687 */ 1688 function _unzip_file_ziparchive( $file, $to, $needed_dirs = array() ) { 1689 global $wp_filesystem; 1690 1691 $z = new ZipArchive(); 1692 1693 $zopen = $z->open( $file, ZIPARCHIVE::CHECKCONS ); 1694 1695 if ( true !== $zopen ) { 1696 return new WP_Error( 'incompatible_archive', __( 'Incompatible Archive.' ), array( 'ziparchive_error' => $zopen ) ); 1697 } 1698 1699 $uncompressed_size = 0; 1700 1701 for ( $i = 0; $i < $z->numFiles; $i++ ) { 1702 $info = $z->statIndex( $i ); 1703 1704 if ( ! $info ) { 1705 $z->close(); 1706 return new WP_Error( 'stat_failed_ziparchive', __( 'Could not retrieve file from archive.' ) ); 1707 } 1708 1709 if ( str_starts_with( $info['name'], '__MACOSX/' ) ) { // Skip the OS X-created __MACOSX directory. 1710 continue; 1711 } 1712 1713 // Don't extract invalid files: 1714 if ( 0 !== validate_file( $info['name'] ) ) { 1715 continue; 1716 } 1717 1718 $uncompressed_size += $info['size']; 1719 1720 $dirname = dirname( $info['name'] ); 1721 1722 if ( str_ends_with( $info['name'], '/' ) ) { 1723 // Directory. 1724 $needed_dirs[] = $to . untrailingslashit( $info['name'] ); 1725 } elseif ( '.' !== $dirname ) { 1726 // Path to a file. 1727 $needed_dirs[] = $to . untrailingslashit( $dirname ); 1728 } 1729 } 1730 1731 // Enough space to unzip the file and copy its contents, with a 10% buffer. 1732 $required_space = $uncompressed_size * 2.1; 1733 1734 /* 1735 * disk_free_space() could return false. Assume that any falsey value is an error. 1736 * A disk that has zero free bytes has bigger problems. 1737 * Require we have enough space to unzip the file and copy its contents, with a 10% buffer. 1738 */ 1739 if ( wp_doing_cron() ) { 1740 $available_space = function_exists( 'disk_free_space' ) ? @disk_free_space( WP_CONTENT_DIR ) : false; 1741 1742 if ( $available_space && ( $required_space > $available_space ) ) { 1743 $z->close(); 1744 return new WP_Error( 1745 'disk_full_unzip_file', 1746 __( 'Could not copy files. You may have run out of disk space.' ), 1747 compact( 'uncompressed_size', 'available_space' ) 1748 ); 1749 } 1750 } 1751 1752 $needed_dirs = array_unique( $needed_dirs ); 1753 1754 foreach ( $needed_dirs as $dir ) { 1755 // Check the parent folders of the folders all exist within the creation array. 1756 if ( untrailingslashit( $to ) === $dir ) { // Skip over the working directory, we know this exists (or will exist). 1757 continue; 1758 } 1759 1760 if ( ! str_contains( $dir, $to ) ) { // If the directory is not within the working directory, skip it. 1761 continue; 1762 } 1763 1764 $parent_folder = dirname( $dir ); 1765 1766 while ( ! empty( $parent_folder ) 1767 && untrailingslashit( $to ) !== $parent_folder 1768 && ! in_array( $parent_folder, $needed_dirs, true ) 1769 ) { 1770 $needed_dirs[] = $parent_folder; 1771 $parent_folder = dirname( $parent_folder ); 1772 } 1773 } 1774 1775 asort( $needed_dirs ); 1776 1777 // Create those directories if need be: 1778 foreach ( $needed_dirs as $_dir ) { 1779 // Only check to see if the Dir exists upon creation failure. Less I/O this way. 1780 if ( ! $wp_filesystem->mkdir( $_dir, FS_CHMOD_DIR ) && ! $wp_filesystem->is_dir( $_dir ) ) { 1781 $z->close(); 1782 return new WP_Error( 'mkdir_failed_ziparchive', __( 'Could not create directory.' ), $_dir ); 1783 } 1784 } 1785 1786 /** 1787 * Filters archive unzipping to override with a custom process. 1788 * 1789 * @since 6.4.0 1790 * 1791 * @param null|true|WP_Error $result The result of the override. True on success, otherwise WP Error. Default null. 1792 * @param string $file Full path and filename of ZIP archive. 1793 * @param string $to Full path on the filesystem to extract archive to. 1794 * @param string[] $needed_dirs A full list of required folders that need to be created. 1795 * @param float $required_space The space required to unzip the file and copy its contents, with a 10% buffer. 1796 */ 1797 $pre = apply_filters( 'pre_unzip_file', null, $file, $to, $needed_dirs, $required_space ); 1798 1799 if ( null !== $pre ) { 1800 // Ensure the ZIP file archive has been closed. 1801 $z->close(); 1802 1803 return $pre; 1804 } 1805 1806 for ( $i = 0; $i < $z->numFiles; $i++ ) { 1807 $info = $z->statIndex( $i ); 1808 1809 if ( ! $info ) { 1810 $z->close(); 1811 return new WP_Error( 'stat_failed_ziparchive', __( 'Could not retrieve file from archive.' ) ); 1812 } 1813 1814 if ( str_ends_with( $info['name'], '/' ) ) { // Directory. 1815 continue; 1816 } 1817 1818 if ( str_starts_with( $info['name'], '__MACOSX/' ) ) { // Don't extract the OS X-created __MACOSX directory files. 1819 continue; 1820 } 1821 1822 // Don't extract invalid files: 1823 if ( 0 !== validate_file( $info['name'] ) ) { 1824 continue; 1825 } 1826 1827 $contents = $z->getFromIndex( $i ); 1828 1829 if ( false === $contents ) { 1830 $z->close(); 1831 return new WP_Error( 'extract_failed_ziparchive', __( 'Could not extract file from archive.' ), $info['name'] ); 1832 } 1833 1834 if ( ! $wp_filesystem->put_contents( $to . $info['name'], $contents, FS_CHMOD_FILE ) ) { 1835 $z->close(); 1836 return new WP_Error( 'copy_failed_ziparchive', __( 'Could not copy file.' ), $info['name'] ); 1837 } 1838 } 1839 1840 $z->close(); 1841 1842 /** 1843 * Filters the result of unzipping an archive. 1844 * 1845 * @since 6.4.0 1846 * 1847 * @param true|WP_Error $result The result of unzipping the archive. True on success, otherwise WP_Error. Default true. 1848 * @param string $file Full path and filename of ZIP archive. 1849 * @param string $to Full path on the filesystem the archive was extracted to. 1850 * @param string[] $needed_dirs A full list of required folders that were created. 1851 * @param float $required_space The space required to unzip the file and copy its contents, with a 10% buffer. 1852 */ 1853 $result = apply_filters( 'unzip_file', true, $file, $to, $needed_dirs, $required_space ); 1854 1855 unset( $needed_dirs ); 1856 1857 return $result; 1858 } 1859 1860 /** 1861 * Attempts to unzip an archive using the PclZip library. 1862 * 1863 * This function should not be called directly, use `unzip_file()` instead. 1864 * 1865 * Assumes that WP_Filesystem() has already been called and set up. 1866 * 1867 * @since 3.0.0 1868 * @access private 1869 * 1870 * @see unzip_file() 1871 * 1872 * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. 1873 * 1874 * @param string $file Full path and filename of ZIP archive. 1875 * @param string $to Full path on the filesystem to extract archive to. 1876 * @param string[] $needed_dirs A partial list of required folders needed to be created. 1877 * @return true|WP_Error True on success, WP_Error on failure. 1878 */ 1879 function _unzip_file_pclzip( $file, $to, $needed_dirs = array() ) { 1880 global $wp_filesystem; 1881 1882 mbstring_binary_safe_encoding(); 1883 1884 require_once ABSPATH . 'wp-admin/includes/class-pclzip.php'; 1885 1886 $archive = new PclZip( $file ); 1887 1888 $archive_files = $archive->extract( PCLZIP_OPT_EXTRACT_AS_STRING ); 1889 1890 reset_mbstring_encoding(); 1891 1892 // Is the archive valid? 1893 if ( ! is_array( $archive_files ) ) { 1894 return new WP_Error( 'incompatible_archive', __( 'Incompatible Archive.' ), $archive->errorInfo( true ) ); 1895 } 1896 1897 if ( 0 === count( $archive_files ) ) { 1898 return new WP_Error( 'empty_archive_pclzip', __( 'Empty archive.' ) ); 1899 } 1900 1901 $uncompressed_size = 0; 1902 1903 // Determine any children directories needed (From within the archive). 1904 foreach ( $archive_files as $archive_file ) { 1905 if ( str_starts_with( $archive_file['filename'], '__MACOSX/' ) ) { // Skip the OS X-created __MACOSX directory. 1906 continue; 1907 } 1908 1909 // Don't extract invalid files: 1910 if ( 0 !== validate_file( $archive_file['filename'] ) ) { 1911 continue; 1912 } 1913 1914 $uncompressed_size += $archive_file['size']; 1915 1916 $needed_dirs[] = $to . untrailingslashit( $archive_file['folder'] ? $archive_file['filename'] : dirname( $archive_file['filename'] ) ); 1917 } 1918 1919 // Enough space to unzip the file and copy its contents, with a 10% buffer. 1920 $required_space = $uncompressed_size * 2.1; 1921 1922 /* 1923 * disk_free_space() could return false. Assume that any falsey value is an error. 1924 * A disk that has zero free bytes has bigger problems. 1925 * Require we have enough space to unzip the file and copy its contents, with a 10% buffer. 1926 */ 1927 if ( wp_doing_cron() ) { 1928 $available_space = function_exists( 'disk_free_space' ) ? @disk_free_space( WP_CONTENT_DIR ) : false; 1929 1930 if ( $available_space && ( $required_space > $available_space ) ) { 1931 return new WP_Error( 1932 'disk_full_unzip_file', 1933 __( 'Could not copy files. You may have run out of disk space.' ), 1934 compact( 'uncompressed_size', 'available_space' ) 1935 ); 1936 } 1937 } 1938 1939 $needed_dirs = array_unique( $needed_dirs ); 1940 1941 foreach ( $needed_dirs as $dir ) { 1942 // Check the parent folders of the folders all exist within the creation array. 1943 if ( untrailingslashit( $to ) === $dir ) { // Skip over the working directory, we know this exists (or will exist). 1944 continue; 1945 } 1946 1947 if ( ! str_contains( $dir, $to ) ) { // If the directory is not within the working directory, skip it. 1948 continue; 1949 } 1950 1951 $parent_folder = dirname( $dir ); 1952 1953 while ( ! empty( $parent_folder ) 1954 && untrailingslashit( $to ) !== $parent_folder 1955 && ! in_array( $parent_folder, $needed_dirs, true ) 1956 ) { 1957 $needed_dirs[] = $parent_folder; 1958 $parent_folder = dirname( $parent_folder ); 1959 } 1960 } 1961 1962 asort( $needed_dirs ); 1963 1964 // Create those directories if need be: 1965 foreach ( $needed_dirs as $_dir ) { 1966 // Only check to see if the dir exists upon creation failure. Less I/O this way. 1967 if ( ! $wp_filesystem->mkdir( $_dir, FS_CHMOD_DIR ) && ! $wp_filesystem->is_dir( $_dir ) ) { 1968 return new WP_Error( 'mkdir_failed_pclzip', __( 'Could not create directory.' ), $_dir ); 1969 } 1970 } 1971 1972 /** This filter is documented in wp-admin/includes/file.php */ 1973 $pre = apply_filters( 'pre_unzip_file', null, $file, $to, $needed_dirs, $required_space ); 1974 1975 if ( null !== $pre ) { 1976 return $pre; 1977 } 1978 1979 // Extract the files from the zip. 1980 foreach ( $archive_files as $archive_file ) { 1981 if ( $archive_file['folder'] ) { 1982 continue; 1983 } 1984 1985 if ( str_starts_with( $archive_file['filename'], '__MACOSX/' ) ) { // Don't extract the OS X-created __MACOSX directory files. 1986 continue; 1987 } 1988 1989 // Don't extract invalid files: 1990 if ( 0 !== validate_file( $archive_file['filename'] ) ) { 1991 continue; 1992 } 1993 1994 if ( ! $wp_filesystem->put_contents( $to . $archive_file['filename'], $archive_file['content'], FS_CHMOD_FILE ) ) { 1995 return new WP_Error( 'copy_failed_pclzip', __( 'Could not copy file.' ), $archive_file['filename'] ); 1996 } 1997 } 1998 1999 /** This filter is documented in wp-admin/includes/file.php */ 2000 $result = apply_filters( 'unzip_file', true, $file, $to, $needed_dirs, $required_space ); 2001 2002 unset( $needed_dirs ); 2003 2004 return $result; 2005 } 2006 2007 /** 2008 * Copies a directory from one location to another via the WordPress Filesystem 2009 * Abstraction. 2010 * 2011 * Assumes that WP_Filesystem() has already been called and setup. 2012 * 2013 * @since 2.5.0 2014 * 2015 * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. 2016 * 2017 * @param string $from Source directory. 2018 * @param string $to Destination directory. 2019 * @param string[] $skip_list An array of files/folders to skip copying. 2020 * @return true|WP_Error True on success, WP_Error on failure. 2021 */ 2022 function copy_dir( $from, $to, $skip_list = array() ) { 2023 global $wp_filesystem; 2024 2025 $dirlist = $wp_filesystem->dirlist( $from ); 2026 2027 if ( false === $dirlist ) { 2028 return new WP_Error( 'dirlist_failed_copy_dir', __( 'Directory listing failed.' ), basename( $from ) ); 2029 } 2030 2031 $from = trailingslashit( $from ); 2032 $to = trailingslashit( $to ); 2033 2034 if ( ! $wp_filesystem->exists( $to ) && ! $wp_filesystem->mkdir( $to ) ) { 2035 return new WP_Error( 2036 'mkdir_destination_failed_copy_dir', 2037 __( 'Could not create the destination directory.' ), 2038 basename( $to ) 2039 ); 2040 } 2041 2042 foreach ( (array) $dirlist as $filename => $fileinfo ) { 2043 if ( in_array( $filename, $skip_list, true ) ) { 2044 continue; 2045 } 2046 2047 if ( 'f' === $fileinfo['type'] ) { 2048 if ( ! $wp_filesystem->copy( $from . $filename, $to . $filename, true, FS_CHMOD_FILE ) ) { 2049 // If copy failed, chmod file to 0644 and try again. 2050 $wp_filesystem->chmod( $to . $filename, FS_CHMOD_FILE ); 2051 2052 if ( ! $wp_filesystem->copy( $from . $filename, $to . $filename, true, FS_CHMOD_FILE ) ) { 2053 return new WP_Error( 'copy_failed_copy_dir', __( 'Could not copy file.' ), $to . $filename ); 2054 } 2055 } 2056 2057 wp_opcache_invalidate( $to . $filename ); 2058 } elseif ( 'd' === $fileinfo['type'] ) { 2059 if ( ! $wp_filesystem->is_dir( $to . $filename ) ) { 2060 if ( ! $wp_filesystem->mkdir( $to . $filename, FS_CHMOD_DIR ) ) { 2061 return new WP_Error( 'mkdir_failed_copy_dir', __( 'Could not create directory.' ), $to . $filename ); 2062 } 2063 } 2064 2065 // Generate the $sub_skip_list for the subdirectory as a sub-set of the existing $skip_list. 2066 $sub_skip_list = array(); 2067 2068 foreach ( $skip_list as $skip_item ) { 2069 if ( str_starts_with( $skip_item, $filename . '/' ) ) { 2070 $sub_skip_list[] = preg_replace( '!^' . preg_quote( $filename, '!' ) . '/!i', '', $skip_item ); 2071 } 2072 } 2073 2074 $result = copy_dir( $from . $filename, $to . $filename, $sub_skip_list ); 2075 2076 if ( is_wp_error( $result ) ) { 2077 return $result; 2078 } 2079 } 2080 } 2081 2082 return true; 2083 } 2084 2085 /** 2086 * Moves a directory from one location to another. 2087 * 2088 * Recursively invalidates OPcache on success. 2089 * 2090 * If the renaming failed, falls back to copy_dir(). 2091 * 2092 * Assumes that WP_Filesystem() has already been called and setup. 2093 * 2094 * This function is not designed to merge directories, copy_dir() should be used instead. 2095 * 2096 * @since 6.2.0 2097 * 2098 * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. 2099 * 2100 * @param string $from Source directory. 2101 * @param string $to Destination directory. 2102 * @param bool $overwrite Optional. Whether to overwrite the destination directory if it exists. 2103 * Default false. 2104 * @return true|WP_Error True on success, WP_Error on failure. 2105 */ 2106 function move_dir( $from, $to, $overwrite = false ) { 2107 global $wp_filesystem; 2108 2109 if ( trailingslashit( strtolower( $from ) ) === trailingslashit( strtolower( $to ) ) ) { 2110 return new WP_Error( 'source_destination_same_move_dir', __( 'The source and destination are the same.' ) ); 2111 } 2112 2113 if ( $wp_filesystem->exists( $to ) ) { 2114 if ( ! $overwrite ) { 2115 return new WP_Error( 'destination_already_exists_move_dir', __( 'The destination folder already exists.' ), $to ); 2116 } elseif ( ! $wp_filesystem->delete( $to, true ) ) { 2117 // Can't overwrite if the destination couldn't be deleted. 2118 return new WP_Error( 'destination_not_deleted_move_dir', __( 'The destination directory already exists and could not be removed.' ) ); 2119 } 2120 } 2121 2122 if ( $wp_filesystem->move( $from, $to ) ) { 2123 /* 2124 * When using an environment with shared folders, 2125 * there is a delay in updating the filesystem's cache. 2126 * 2127 * This is a known issue in environments with a VirtualBox provider. 2128 * 2129 * A 200ms delay gives time for the filesystem to update its cache, 2130 * prevents "Operation not permitted", and "No such file or directory" warnings. 2131 * 2132 * This delay is used in other projects, including Composer. 2133 * @link https://github.com/composer/composer/blob/2.5.1/src/Composer/Util/Platform.php#L228-L233 2134 */ 2135 usleep( 200000 ); 2136 wp_opcache_invalidate_directory( $to ); 2137 2138 return true; 2139 } 2140 2141 // Fall back to a recursive copy. 2142 if ( ! $wp_filesystem->is_dir( $to ) ) { 2143 if ( ! $wp_filesystem->mkdir( $to, FS_CHMOD_DIR ) ) { 2144 return new WP_Error( 'mkdir_failed_move_dir', __( 'Could not create directory.' ), $to ); 2145 } 2146 } 2147 2148 $result = copy_dir( $from, $to, array( basename( $to ) ) ); 2149 2150 // Clear the source directory. 2151 if ( true === $result ) { 2152 $wp_filesystem->delete( $from, true ); 2153 } 2154 2155 return $result; 2156 } 2157 2158 /** 2159 * Initializes and connects the WordPress Filesystem Abstraction classes. 2160 * 2161 * This function will include the chosen transport and attempt connecting. 2162 * 2163 * Plugins may add extra transports, And force WordPress to use them by returning 2164 * the filename via the {@see 'filesystem_method_file'} filter. 2165 * 2166 * @since 2.5.0 2167 * 2168 * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. 2169 * 2170 * @param array|false $args Optional. Connection args, These are passed 2171 * directly to the `WP_Filesystem_*()` classes. 2172 * Default false. 2173 * @param string|false $context Optional. Context for get_filesystem_method(). 2174 * Default false. 2175 * @param bool $allow_relaxed_file_ownership Optional. Whether to allow Group/World writable. 2176 * Default false. 2177 * @return bool|null True on success, false on failure, 2178 * null if the filesystem method class file does not exist. 2179 */ 2180 function WP_Filesystem( $args = false, $context = false, $allow_relaxed_file_ownership = false ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid 2181 global $wp_filesystem; 2182 2183 require_once ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php'; 2184 2185 $method = get_filesystem_method( $args, $context, $allow_relaxed_file_ownership ); 2186 2187 if ( ! $method ) { 2188 return false; 2189 } 2190 2191 if ( ! class_exists( "WP_Filesystem_$method" ) ) { 2192 2193 /** 2194 * Filters the path for a specific filesystem method class file. 2195 * 2196 * @since 2.6.0 2197 * 2198 * @see get_filesystem_method() 2199 * 2200 * @param string $path Path to the specific filesystem method class file. 2201 * @param string $method The filesystem method to use. 2202 */ 2203 $abstraction_file = apply_filters( 'filesystem_method_file', ABSPATH . 'wp-admin/includes/class-wp-filesystem-' . $method . '.php', $method ); 2204 2205 if ( ! file_exists( $abstraction_file ) ) { 2206 return null; 2207 } 2208 2209 require_once $abstraction_file; 2210 } 2211 $method = "WP_Filesystem_$method"; 2212 2213 $wp_filesystem = new $method( $args ); 2214 2215 /* 2216 * Define the timeouts for the connections. Only available after the constructor is called 2217 * to allow for per-transport overriding of the default. 2218 */ 2219 if ( ! defined( 'FS_CONNECT_TIMEOUT' ) ) { 2220 define( 'FS_CONNECT_TIMEOUT', 30 ); // 30 seconds. 2221 } 2222 if ( ! defined( 'FS_TIMEOUT' ) ) { 2223 define( 'FS_TIMEOUT', 30 ); // 30 seconds. 2224 } 2225 2226 if ( is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) { 2227 return false; 2228 } 2229 2230 if ( ! $wp_filesystem->connect() ) { 2231 return false; // There was an error connecting to the server. 2232 } 2233 2234 // Set the permission constants if not already set. 2235 if ( ! defined( 'FS_CHMOD_DIR' ) ) { 2236 define( 'FS_CHMOD_DIR', ( fileperms( ABSPATH ) & 0777 | 0755 ) ); 2237 } 2238 if ( ! defined( 'FS_CHMOD_FILE' ) ) { 2239 define( 'FS_CHMOD_FILE', ( fileperms( ABSPATH . 'index.php' ) & 0777 | 0644 ) ); 2240 } 2241 2242 return true; 2243 } 2244 2245 /** 2246 * Determines which method to use for reading, writing, modifying, or deleting 2247 * files on the filesystem. 2248 * 2249 * The priority of the transports are: Direct, SSH2, FTP PHP Extension, FTP Sockets 2250 * (Via Sockets class, or `fsockopen()`). Valid values for these are: 'direct', 'ssh2', 2251 * 'ftpext' or 'ftpsockets'. 2252 * 2253 * The return value can be overridden by defining the `FS_METHOD` constant in `wp-config.php`, 2254 * or filtering via {@see 'filesystem_method'}. 2255 * 2256 * @link https://developer.wordpress.org/advanced-administration/wordpress/wp-config/#wordpress-upgrade-constants 2257 * 2258 * Plugins may define a custom transport handler, See WP_Filesystem(). 2259 * 2260 * @since 2.5.0 2261 * 2262 * @global callable $_wp_filesystem_direct_method 2263 * 2264 * @param array $args Optional. Connection details. Default empty array. 2265 * @param string $context Optional. Full path to the directory that is tested 2266 * for being writable. Default empty. 2267 * @param bool $allow_relaxed_file_ownership Optional. Whether to allow Group/World writable. 2268 * Default false. 2269 * @return string The transport to use, see description for valid return values. 2270 */ 2271 function get_filesystem_method( $args = array(), $context = '', $allow_relaxed_file_ownership = false ) { 2272 // Please ensure that this is either 'direct', 'ssh2', 'ftpext', or 'ftpsockets'. 2273 $method = defined( 'FS_METHOD' ) ? FS_METHOD : false; 2274 2275 if ( ! $context ) { 2276 $context = WP_CONTENT_DIR; 2277 } 2278 2279 // If the directory doesn't exist (wp-content/languages) then use the parent directory as we'll create it. 2280 if ( WP_LANG_DIR === $context && ! is_dir( $context ) ) { 2281 $context = dirname( $context ); 2282 } 2283 2284 $context = trailingslashit( $context ); 2285 2286 if ( ! $method ) { 2287 2288 $temp_file_name = $context . 'temp-write-test-' . str_replace( '.', '-', uniqid( '', true ) ); 2289 $temp_handle = @fopen( $temp_file_name, 'w' ); 2290 if ( $temp_handle ) { 2291 2292 // Attempt to determine the file owner of the WordPress files, and that of newly created files. 2293 $wp_file_owner = false; 2294 $temp_file_owner = false; 2295 if ( function_exists( 'fileowner' ) ) { 2296 $wp_file_owner = @fileowner( __FILE__ ); 2297 $temp_file_owner = @fileowner( $temp_file_name ); 2298 } 2299 2300 if ( false !== $wp_file_owner && $wp_file_owner === $temp_file_owner ) { 2301 /* 2302 * WordPress is creating files as the same owner as the WordPress files, 2303 * this means it's safe to modify & create new files via PHP. 2304 */ 2305 $method = 'direct'; 2306 $GLOBALS['_wp_filesystem_direct_method'] = 'file_owner'; 2307 } elseif ( $allow_relaxed_file_ownership ) { 2308 /* 2309 * The $context directory is writable, and $allow_relaxed_file_ownership is set, 2310 * this means we can modify files safely in this directory. 2311 * This mode doesn't create new files, only alter existing ones. 2312 */ 2313 $method = 'direct'; 2314 $GLOBALS['_wp_filesystem_direct_method'] = 'relaxed_ownership'; 2315 } 2316 2317 fclose( $temp_handle ); 2318 @unlink( $temp_file_name ); 2319 } 2320 } 2321 2322 if ( ! $method && isset( $args['connection_type'] ) && 'ssh' === $args['connection_type'] && extension_loaded( 'ssh2' ) ) { 2323 $method = 'ssh2'; 2324 } 2325 if ( ! $method && extension_loaded( 'ftp' ) ) { 2326 $method = 'ftpext'; 2327 } 2328 if ( ! $method && ( extension_loaded( 'sockets' ) || function_exists( 'fsockopen' ) ) ) { 2329 $method = 'ftpsockets'; // Sockets: Socket extension; PHP Mode: FSockopen / fwrite / fread. 2330 } 2331 2332 /** 2333 * Filters the filesystem method to use. 2334 * 2335 * @since 2.6.0 2336 * 2337 * @param string $method Filesystem method to return. 2338 * @param array $args An array of connection details for the method. 2339 * @param string $context Full path to the directory that is tested for being writable. 2340 * @param bool $allow_relaxed_file_ownership Whether to allow Group/World writable. 2341 */ 2342 return apply_filters( 'filesystem_method', $method, $args, $context, $allow_relaxed_file_ownership ); 2343 } 2344 2345 /** 2346 * Displays a form to the user to request for their FTP/SSH details in order 2347 * to connect to the filesystem. 2348 * 2349 * All chosen/entered details are saved, excluding the password. 2350 * 2351 * Hostnames may be in the form of hostname:portnumber (eg: wordpress.org:2467) 2352 * to specify an alternate FTP/SSH port. 2353 * 2354 * Plugins may override this form by returning true|false via the {@see 'request_filesystem_credentials'} filter. 2355 * 2356 * @since 2.5.0 2357 * @since 4.6.0 The `$context` parameter default changed from `false` to an empty string. 2358 * 2359 * @global string $pagenow The filename of the current screen. 2360 * 2361 * @param string $form_post The URL to post the form to. 2362 * @param string $type Optional. Chosen type of filesystem. Default empty. 2363 * @param bool|WP_Error $error Optional. Whether the current request has failed 2364 * to connect, or an error object. Default false. 2365 * @param string $context Optional. Full path to the directory that is tested 2366 * for being writable. Default empty. 2367 * @param array $extra_fields Optional. Extra `POST` fields to be checked 2368 * for inclusion in the post. Default null. 2369 * @param bool $allow_relaxed_file_ownership Optional. Whether to allow Group/World writable. 2370 * Default false. 2371 * @return bool|array True if no filesystem credentials are required, 2372 * false if they are required but have not been provided, 2373 * array of credentials if they are required and have been provided. 2374 */ 2375 function request_filesystem_credentials( $form_post, $type = '', $error = false, $context = '', $extra_fields = null, $allow_relaxed_file_ownership = false ) { 2376 global $pagenow; 2377 2378 /** 2379 * Filters the filesystem credentials. 2380 * 2381 * Returning anything other than an empty string will effectively short-circuit 2382 * output of the filesystem credentials form, returning that value instead. 2383 * 2384 * A filter should return true if no filesystem credentials are required, false if they are required but have not been 2385 * provided, or an array of credentials if they are required and have been provided. 2386 * 2387 * @since 2.5.0 2388 * @since 4.6.0 The `$context` parameter default changed from `false` to an empty string. 2389 * 2390 * @param mixed $credentials Credentials to return instead. Default empty string. 2391 * @param string $form_post The URL to post the form to. 2392 * @param string $type Chosen type of filesystem. 2393 * @param bool|WP_Error $error Whether the current request has failed to connect, 2394 * or an error object. 2395 * @param string $context Full path to the directory that is tested for 2396 * being writable. 2397 * @param array $extra_fields Extra POST fields. 2398 * @param bool $allow_relaxed_file_ownership Whether to allow Group/World writable. 2399 */ 2400 $req_cred = apply_filters( 'request_filesystem_credentials', '', $form_post, $type, $error, $context, $extra_fields, $allow_relaxed_file_ownership ); 2401 2402 if ( '' !== $req_cred ) { 2403 return $req_cred; 2404 } 2405 2406 if ( empty( $type ) ) { 2407 $type = get_filesystem_method( array(), $context, $allow_relaxed_file_ownership ); 2408 } 2409 2410 if ( 'direct' === $type ) { 2411 return true; 2412 } 2413 2414 if ( is_null( $extra_fields ) ) { 2415 $extra_fields = array( 'version', 'locale' ); 2416 } 2417 2418 $credentials = get_option( 2419 'ftp_credentials', 2420 array( 2421 'hostname' => '', 2422 'username' => '', 2423 ) 2424 ); 2425 2426 $submitted_form = wp_unslash( $_POST ); 2427 2428 // Verify nonce, or unset submitted form field values on failure. 2429 if ( ! isset( $_POST['_fs_nonce'] ) || ! wp_verify_nonce( $_POST['_fs_nonce'], 'filesystem-credentials' ) ) { 2430 unset( 2431 $submitted_form['hostname'], 2432 $submitted_form['username'], 2433 $submitted_form['password'], 2434 $submitted_form['public_key'], 2435 $submitted_form['private_key'], 2436 $submitted_form['connection_type'] 2437 ); 2438 } 2439 2440 $ftp_constants = array( 2441 'hostname' => 'FTP_HOST', 2442 'username' => 'FTP_USER', 2443 'password' => 'FTP_PASS', 2444 'public_key' => 'FTP_PUBKEY', 2445 'private_key' => 'FTP_PRIKEY', 2446 ); 2447 2448 /* 2449 * If defined, set it to that. Else, if POST'd, set it to that. If not, set it to an empty string. 2450 * Otherwise, keep it as it previously was (saved details in option). 2451 */ 2452 foreach ( $ftp_constants as $key => $constant ) { 2453 if ( defined( $constant ) ) { 2454 $credentials[ $key ] = constant( $constant ); 2455 } elseif ( ! empty( $submitted_form[ $key ] ) ) { 2456 $credentials[ $key ] = $submitted_form[ $key ]; 2457 } elseif ( ! isset( $credentials[ $key ] ) ) { 2458 $credentials[ $key ] = ''; 2459 } 2460 } 2461 2462 // Sanitize the hostname, some people might pass in odd data. 2463 $credentials['hostname'] = preg_replace( '|\w+://|', '', $credentials['hostname'] ); // Strip any schemes off. 2464 2465 if ( strpos( $credentials['hostname'], ':' ) ) { 2466 list( $credentials['hostname'], $credentials['port'] ) = explode( ':', $credentials['hostname'], 2 ); 2467 if ( ! is_numeric( $credentials['port'] ) ) { 2468 unset( $credentials['port'] ); 2469 } 2470 } else { 2471 unset( $credentials['port'] ); 2472 } 2473 2474 if ( ( defined( 'FTP_SSH' ) && FTP_SSH ) || ( defined( 'FS_METHOD' ) && 'ssh2' === FS_METHOD ) ) { 2475 $credentials['connection_type'] = 'ssh'; 2476 } elseif ( ( defined( 'FTP_SSL' ) && FTP_SSL ) && 'ftpext' === $type ) { // Only the FTP Extension understands SSL. 2477 $credentials['connection_type'] = 'ftps'; 2478 } elseif ( ! empty( $submitted_form['connection_type'] ) ) { 2479 $credentials['connection_type'] = $submitted_form['connection_type']; 2480 } elseif ( ! isset( $credentials['connection_type'] ) ) { // All else fails (and it's not defaulted to something else saved), default to FTP. 2481 $credentials['connection_type'] = 'ftp'; 2482 } 2483 2484 if ( ! $error 2485 && ( ! empty( $credentials['hostname'] ) && ! empty( $credentials['username'] ) && ! empty( $credentials['password'] ) 2486 || 'ssh' === $credentials['connection_type'] && ! empty( $credentials['public_key'] ) && ! empty( $credentials['private_key'] ) 2487 ) 2488 ) { 2489 $stored_credentials = $credentials; 2490 2491 if ( ! empty( $stored_credentials['port'] ) ) { // Save port as part of hostname to simplify above code. 2492 $stored_credentials['hostname'] .= ':' . $stored_credentials['port']; 2493 } 2494 2495 unset( 2496 $stored_credentials['password'], 2497 $stored_credentials['port'], 2498 $stored_credentials['private_key'], 2499 $stored_credentials['public_key'] 2500 ); 2501 2502 if ( ! wp_installing() ) { 2503 update_option( 'ftp_credentials', $stored_credentials, false ); 2504 } 2505 2506 return $credentials; 2507 } 2508 2509 $hostname = $credentials['hostname'] ?? ''; 2510 $username = $credentials['username'] ?? ''; 2511 $public_key = $credentials['public_key'] ?? ''; 2512 $private_key = $credentials['private_key'] ?? ''; 2513 $port = $credentials['port'] ?? ''; 2514 $connection_type = $credentials['connection_type'] ?? ''; 2515 2516 if ( $error ) { 2517 $error_string = __( '<strong>Error:</strong> Could not connect to the server. Please verify the settings are correct.' ); 2518 if ( is_wp_error( $error ) ) { 2519 $error_string = esc_html( $error->get_error_message() ); 2520 } 2521 wp_admin_notice( 2522 $error_string, 2523 array( 2524 'id' => 'message', 2525 'additional_classes' => array( 'error' ), 2526 ) 2527 ); 2528 } 2529 2530 $types = array(); 2531 if ( extension_loaded( 'ftp' ) || extension_loaded( 'sockets' ) || function_exists( 'fsockopen' ) ) { 2532 $types['ftp'] = __( 'FTP' ); 2533 } 2534 if ( extension_loaded( 'ftp' ) ) { // Only this supports FTPS. 2535 $types['ftps'] = __( 'FTPS (SSL)' ); 2536 } 2537 if ( extension_loaded( 'ssh2' ) ) { 2538 $types['ssh'] = __( 'SSH2' ); 2539 } 2540 2541 /** 2542 * Filters the connection types to output to the filesystem credentials form. 2543 * 2544 * @since 2.9.0 2545 * @since 4.6.0 The `$context` parameter default changed from `false` to an empty string. 2546 * 2547 * @param string[] $types Types of connections. 2548 * @param array $credentials Credentials to connect with. 2549 * @param string $type Chosen filesystem method. 2550 * @param bool|WP_Error $error Whether the current request has failed to connect, 2551 * or an error object. 2552 * @param string $context Full path to the directory that is tested for being writable. 2553 */ 2554 $types = apply_filters( 'fs_ftp_connection_types', $types, $credentials, $type, $error, $context ); 2555 ?> 2556 <form action="<?php echo esc_url( $form_post ); ?>" method="post"> 2557 <div id="request-filesystem-credentials-form" class="request-filesystem-credentials-form"> 2558 <?php 2559 // Print a H1 heading in the FTP credentials modal dialog, default is a H2. 2560 $heading_tag = 'h2'; 2561 if ( 'plugins.php' === $pagenow || 'plugin-install.php' === $pagenow ) { 2562 $heading_tag = 'h1'; 2563 } 2564 echo "<$heading_tag id='request-filesystem-credentials-title'>" . __( 'Connection Information' ) . "</$heading_tag>"; 2565 ?> 2566 <p id="request-filesystem-credentials-desc"> 2567 <?php 2568 $label_user = __( 'Username' ); 2569 $label_pass = __( 'Password' ); 2570 _e( 'To perform the requested action, WordPress needs to access your web server.' ); 2571 echo ' '; 2572 if ( ( isset( $types['ftp'] ) || isset( $types['ftps'] ) ) ) { 2573 if ( isset( $types['ssh'] ) ) { 2574 _e( 'Please enter your FTP or SSH credentials to proceed.' ); 2575 $label_user = __( 'FTP/SSH Username' ); 2576 $label_pass = __( 'FTP/SSH Password' ); 2577 } else { 2578 _e( 'Please enter your FTP credentials to proceed.' ); 2579 $label_user = __( 'FTP Username' ); 2580 $label_pass = __( 'FTP Password' ); 2581 } 2582 echo ' '; 2583 } 2584 _e( 'If you do not remember your credentials, you should contact your web host.' ); 2585 2586 $hostname_value = esc_attr( $hostname ); 2587 if ( ! empty( $port ) ) { 2588 $hostname_value .= ":$port"; 2589 } 2590 2591 $password_value = ''; 2592 if ( defined( 'FTP_PASS' ) ) { 2593 $password_value = '*****'; 2594 } 2595 ?> 2596 </p> 2597 <label for="hostname"> 2598 <span class="field-title"><?php _e( 'Hostname' ); ?></span> 2599 <input name="hostname" type="text" id="hostname" aria-describedby="request-filesystem-credentials-desc" class="code" placeholder="<?php esc_attr_e( 'example: www.wordpress.org' ); ?>" value="<?php echo $hostname_value; ?>"<?php disabled( defined( 'FTP_HOST' ) ); ?> /> 2600 </label> 2601 <div class="ftp-username"> 2602 <label for="username"> 2603 <span class="field-title"><?php echo $label_user; ?></span> 2604 <input name="username" type="text" id="username" value="<?php echo esc_attr( $username ); ?>"<?php disabled( defined( 'FTP_USER' ) ); ?> /> 2605 </label> 2606 </div> 2607 <div class="ftp-password"> 2608 <label for="password"> 2609 <span class="field-title"><?php echo $label_pass; ?></span> 2610 <input name="password" type="password" id="password" value="<?php echo $password_value; ?>"<?php disabled( defined( 'FTP_PASS' ) ); ?> spellcheck="false" /> 2611 <?php 2612 if ( ! defined( 'FTP_PASS' ) ) { 2613 _e( 'This password will not be stored on the server.' ); 2614 } 2615 ?> 2616 </label> 2617 </div> 2618 <fieldset> 2619 <legend><?php _e( 'Connection Type' ); ?></legend> 2620 <?php 2621 $disabled = disabled( ( defined( 'FTP_SSL' ) && FTP_SSL ) || ( defined( 'FTP_SSH' ) && FTP_SSH ), true, false ); 2622 foreach ( $types as $name => $text ) : 2623 ?> 2624 <label for="<?php echo esc_attr( $name ); ?>"> 2625 <input type="radio" name="connection_type" id="<?php echo esc_attr( $name ); ?>" value="<?php echo esc_attr( $name ); ?>" <?php checked( $name, $connection_type ); ?> <?php echo $disabled; ?> /> 2626 <?php echo $text; ?> 2627 </label> 2628 <?php 2629 endforeach; 2630 ?> 2631 </fieldset> 2632 <?php 2633 if ( isset( $types['ssh'] ) ) { 2634 $hidden_class = ''; 2635 if ( 'ssh' !== $connection_type ) { 2636 $hidden_class = ' class="hidden"'; 2637 } 2638 ?> 2639 <fieldset id="ssh-keys"<?php echo $hidden_class; ?>> 2640 <legend><?php _e( 'Authentication Keys' ); ?></legend> 2641 <label for="public_key"> 2642 <span class="field-title"><?php _e( 'Public Key:' ); ?></span> 2643 <input name="public_key" type="text" id="public_key" aria-describedby="auth-keys-desc" value="<?php echo esc_attr( $public_key ); ?>"<?php disabled( defined( 'FTP_PUBKEY' ) ); ?> /> 2644 </label> 2645 <label for="private_key"> 2646 <span class="field-title"><?php _e( 'Private Key:' ); ?></span> 2647 <input name="private_key" type="text" id="private_key" value="<?php echo esc_attr( $private_key ); ?>"<?php disabled( defined( 'FTP_PRIKEY' ) ); ?> /> 2648 </label> 2649 <p id="auth-keys-desc"><?php _e( 'Enter the location on the server where the public and private keys are located. If a passphrase is needed, enter that in the password field above.' ); ?></p> 2650 </fieldset> 2651 <?php 2652 } 2653 2654 foreach ( (array) $extra_fields as $field ) { 2655 if ( isset( $submitted_form[ $field ] ) ) { 2656 echo '<input type="hidden" name="' . esc_attr( $field ) . '" value="' . esc_attr( $submitted_form[ $field ] ) . '" />'; 2657 } 2658 } 2659 2660 /* 2661 * Make sure the `submit_button()` function is available during the REST API call 2662 * from WP_Site_Health_Auto_Updates::test_check_wp_filesystem_method(). 2663 */ 2664 if ( ! function_exists( 'submit_button' ) ) { 2665 require_once ABSPATH . 'wp-admin/includes/template.php'; 2666 } 2667 ?> 2668 <p class="request-filesystem-credentials-action-buttons"> 2669 <?php wp_nonce_field( 'filesystem-credentials', '_fs_nonce', false, true ); ?> 2670 <button class="button cancel-button" data-js-action="close" type="button"><?php _e( 'Cancel' ); ?></button> 2671 <?php submit_button( __( 'Proceed' ), 'primary', 'upgrade', false ); ?> 2672 </p> 2673 </div> 2674 </form> 2675 <?php 2676 return false; 2677 } 2678 2679 /** 2680 * Prints the filesystem credentials modal when needed. 2681 * 2682 * @since 4.2.0 2683 */ 2684 function wp_print_request_filesystem_credentials_modal() { 2685 $filesystem_method = get_filesystem_method(); 2686 2687 ob_start(); 2688 $filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() ); 2689 ob_end_clean(); 2690 2691 $request_filesystem_credentials = ( 'direct' !== $filesystem_method && ! $filesystem_credentials_are_stored ); 2692 if ( ! $request_filesystem_credentials ) { 2693 return; 2694 } 2695 ?> 2696 <div id="request-filesystem-credentials-dialog" class="notification-dialog-wrap request-filesystem-credentials-dialog"> 2697 <div class="notification-dialog-background"></div> 2698 <div class="notification-dialog" role="dialog" aria-labelledby="request-filesystem-credentials-title" tabindex="0"> 2699 <div class="request-filesystem-credentials-dialog-content"> 2700 <?php request_filesystem_credentials( site_url() ); ?> 2701 </div> 2702 </div> 2703 </div> 2704 <?php 2705 } 2706 2707 /** 2708 * Attempts to clear the opcode cache for an individual PHP file. 2709 * 2710 * This function can be called safely without having to check the file extension 2711 * or availability of the OPcache extension. 2712 * 2713 * Whether or not invalidation is possible is cached to improve performance. 2714 * 2715 * @since 5.5.0 2716 * 2717 * @link https://www.php.net/manual/en/function.opcache-invalidate.php 2718 * 2719 * @param string $filepath Path to the file, including extension, for which the opcode cache is to be cleared. 2720 * @param bool $force Invalidate even if the modification time is not newer than the file in cache. 2721 * Default false. 2722 * @return bool True if opcache was invalidated for `$filepath`, or there was nothing to invalidate. 2723 * False if opcache invalidation is not available, or is disabled via filter. 2724 */ 2725 function wp_opcache_invalidate( $filepath, $force = false ) { 2726 static $can_invalidate = null; 2727 2728 /* 2729 * Check to see if WordPress is able to run `opcache_invalidate()` or not, and cache the value. 2730 * 2731 * First, check to see if the function is available to call, then if the host has restricted 2732 * the ability to run the function to avoid a PHP warning. 2733 * 2734 * `opcache.restrict_api` can specify the path for files allowed to call `opcache_invalidate()`. 2735 * 2736 * If the host has this set, check whether the path in `opcache.restrict_api` matches 2737 * the beginning of the path of the origin file. 2738 * 2739 * `$_SERVER['SCRIPT_FILENAME']` approximates the origin file's path, but `realpath()` 2740 * is necessary because `SCRIPT_FILENAME` can be a relative path when run from CLI. 2741 * 2742 * For more details, see: 2743 * - https://www.php.net/manual/en/opcache.configuration.php 2744 * - https://www.php.net/manual/en/reserved.variables.server.php 2745 * - https://core.trac.wordpress.org/ticket/36455 2746 */ 2747 if ( null === $can_invalidate 2748 && function_exists( 'opcache_invalidate' ) 2749 && ( ! ini_get( 'opcache.restrict_api' ) 2750 || stripos( realpath( $_SERVER['SCRIPT_FILENAME'] ), ini_get( 'opcache.restrict_api' ) ) === 0 ) 2751 ) { 2752 $can_invalidate = true; 2753 } 2754 2755 // If invalidation is not available, return early. 2756 if ( ! $can_invalidate ) { 2757 return false; 2758 } 2759 2760 // Verify that file to be invalidated has a PHP extension. 2761 if ( '.php' !== strtolower( substr( $filepath, -4 ) ) ) { 2762 return false; 2763 } 2764 2765 /** 2766 * Filters whether to invalidate a file from the opcode cache. 2767 * 2768 * @since 5.5.0 2769 * 2770 * @param bool $will_invalidate Whether WordPress will invalidate `$filepath`. Default true. 2771 * @param string $filepath The path to the PHP file to invalidate. 2772 */ 2773 if ( apply_filters( 'wp_opcache_invalidate_file', true, $filepath ) ) { 2774 return opcache_invalidate( $filepath, $force ); 2775 } 2776 2777 return false; 2778 } 2779 2780 /** 2781 * Attempts to clear the opcode cache for a directory of files. 2782 * 2783 * @since 6.2.0 2784 * 2785 * @see wp_opcache_invalidate() 2786 * @link https://www.php.net/manual/en/function.opcache-invalidate.php 2787 * 2788 * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass. 2789 * 2790 * @param string $dir The path to the directory for which the opcode cache is to be cleared. 2791 */ 2792 function wp_opcache_invalidate_directory( $dir ) { 2793 global $wp_filesystem; 2794 2795 if ( ! is_string( $dir ) || '' === trim( $dir ) ) { 2796 if ( WP_DEBUG ) { 2797 $error_message = sprintf( 2798 /* translators: %s: The function name. */ 2799 __( '%s expects a non-empty string.' ), 2800 '<code>wp_opcache_invalidate_directory()</code>' 2801 ); 2802 wp_trigger_error( '', $error_message ); 2803 } 2804 return; 2805 } 2806 2807 $dirlist = $wp_filesystem->dirlist( $dir, false, true ); 2808 2809 if ( empty( $dirlist ) ) { 2810 return; 2811 } 2812 2813 /* 2814 * Recursively invalidate opcache of files in a directory. 2815 * 2816 * WP_Filesystem_*::dirlist() returns an array of file and directory information. 2817 * 2818 * This does not include a path to the file or directory. 2819 * To invalidate files within sub-directories, recursion is needed 2820 * to prepend an absolute path containing the sub-directory's name. 2821 * 2822 * @param array $dirlist Array of file/directory information from WP_Filesystem_Base::dirlist(), 2823 * with sub-directories represented as nested arrays. 2824 * @param string $path Absolute path to the directory. 2825 */ 2826 $invalidate_directory = static function ( $dirlist, $path ) use ( &$invalidate_directory ) { 2827 $path = trailingslashit( $path ); 2828 2829 foreach ( $dirlist as $name => $details ) { 2830 if ( 'f' === $details['type'] ) { 2831 wp_opcache_invalidate( $path . $name, true ); 2832 } elseif ( is_array( $details['files'] ) && ! empty( $details['files'] ) ) { 2833 $invalidate_directory( $details['files'], $path . $name ); 2834 } 2835 } 2836 }; 2837 2838 $invalidate_directory( $dirlist, $dir ); 2839 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
| Generated : Thu Aug 6 08:20:21 2026 | Cross-referenced by PHPXref |