[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

/wp-admin/includes/ -> file.php (source)

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


Generated: Thu Jul 16 01:00:03 2020 Cross-referenced by PHPXref 0.7.1