[ Index ]

WordPress 5.4.1

[ Index ]     [ Classes ]     [ Functions ]     [ Variables ]     [ Constants ]     [ Statistics ]    

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


Generated: Tue May 19 15:51:04 2020 Cross-referenced by PHPXref 0.7.1