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