[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

   1  <?php
   2  /**
   3   * Filesystem API: Top-level functionality
   4   *
   5   * Functions for reading, writing, modifying, and deleting files on the file system.
   6   * Includes functionality for theme-specific files as well as operations for uploading,
   7   * archiving, and rendering output when necessary.
   8   *
   9   * @package WordPress
  10   * @subpackage Filesystem
  11   * @since 2.3.0
  12   */
  13  
  14  /** The descriptions for theme files. */
  15  $wp_file_descriptions = array(
  16      'functions.php'         => __( 'Theme Functions' ),
  17      'header.php'            => __( 'Theme Header' ),
  18      'footer.php'            => __( 'Theme Footer' ),
  19      'sidebar.php'           => __( 'Sidebar' ),
  20      'comments.php'          => __( 'Comments' ),
  21      'searchform.php'        => __( 'Search Form' ),
  22      '404.php'               => __( '404 Template' ),
  23      'link.php'              => __( 'Links Template' ),
  24      // Archives
  25      'index.php'             => __( 'Main Index Template' ),
  26      'archive.php'           => __( 'Archives' ),
  27      'author.php'            => __( 'Author Template' ),
  28      'taxonomy.php'          => __( 'Taxonomy Template' ),
  29      'category.php'          => __( 'Category Template' ),
  30      'tag.php'               => __( 'Tag Template' ),
  31      'home.php'              => __( 'Posts Page' ),
  32      'search.php'            => __( 'Search Results' ),
  33      'date.php'              => __( 'Date Template' ),
  34      // Content
  35      'singular.php'          => __( 'Singular Template' ),
  36      'single.php'            => __( 'Single Post' ),
  37      'page.php'              => __( 'Single Page' ),
  38      'front-page.php'        => __( 'Homepage' ),
  39      'privacy-policy.php'    => __( 'Privacy Policy Page' ),
  40      // Attachments
  41      'attachment.php'        => __( 'Attachment Template' ),
  42      'image.php'             => __( 'Image Attachment Template' ),
  43      'video.php'             => __( 'Video Attachment Template' ),
  44      'audio.php'             => __( 'Audio Attachment Template' ),
  45      'application.php'       => __( 'Application Attachment Template' ),
  46      // Embeds
  47      'embed.php'             => __( 'Embed Template' ),
  48      'embed-404.php'         => __( 'Embed 404 Template' ),
  49      'embed-content.php'     => __( 'Embed Content Template' ),
  50      'header-embed.php'      => __( 'Embed Header Template' ),
  51      'footer-embed.php'      => __( 'Embed Footer Template' ),
  52      // Stylesheets
  53      'style.css'             => __( 'Stylesheet' ),
  54      'editor-style.css'      => __( 'Visual Editor Stylesheet' ),
  55      'editor-style-rtl.css'  => __( 'Visual Editor RTL Stylesheet' ),
  56      'rtl.css'               => __( 'RTL Stylesheet' ),
  57      // Other
  58      'my-hacks.php'          => __( 'my-hacks.php (legacy hacks support)' ),
  59      '.htaccess'             => __( '.htaccess (for rewrite rules )' ),
  60      // Deprecated files
  61      'wp-layout.css'         => __( 'Stylesheet' ),
  62      'wp-comments.php'       => __( 'Comments Template' ),
  63      'wp-comments-popup.php' => __( 'Popup Comments Template' ),
  64      'comments-popup.php'    => __( 'Popup Comments' ),
  65  );
  66  
  67  /**
  68   * 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          set_transient( $transient, $scrape_nonce, 60 ); // It shouldn't take more than 60 seconds to make the two loopback requests.
 511  
 512          $cookies       = wp_unslash( $_COOKIE );
 513          $scrape_params = array(
 514              'wp_scrape_key'   => $scrape_key,
 515              'wp_scrape_nonce' => $scrape_nonce,
 516          );
 517          $headers       = array(
 518              'Cache-Control' => 'no-cache',
 519          );
 520  
 521          // Include Basic auth in loopback requests.
 522          if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) {
 523              $headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) );
 524          }
 525  
 526          // Make sure PHP process doesn't die before loopback requests complete.
 527          set_time_limit( 300 );
 528  
 529          // Time to wait for loopback requests to finish.
 530          $timeout = 100;
 531  
 532          $needle_start = "###### wp_scraping_result_start:$scrape_key ######";
 533          $needle_end   = "###### wp_scraping_result_end:$scrape_key ######";
 534  
 535          // Attempt loopback request to editor to see if user just whitescreened themselves.
 536          if ( $plugin ) {
 537              $url = add_query_arg( compact( 'plugin', 'file' ), admin_url( 'plugin-editor.php' ) );
 538          } elseif ( isset( $stylesheet ) ) {
 539              $url = add_query_arg(
 540                  array(
 541                      'theme' => $stylesheet,
 542                      'file'  => $file,
 543                  ),
 544                  admin_url( 'theme-editor.php' )
 545              );
 546          } else {
 547              $url = admin_url();
 548          }
 549          $url                    = add_query_arg( $scrape_params, $url );
 550          $r                      = wp_remote_get( $url, compact( 'cookies', 'headers', 'timeout' ) );
 551          $body                   = wp_remote_retrieve_body( $r );
 552          $scrape_result_position = strpos( $body, $needle_start );
 553  
 554          $loopback_request_failure = array(
 555              'code'    => 'loopback_request_failed',
 556              '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.' ),
 557          );
 558          $json_parse_failure       = array(
 559              'code' => 'json_parse_error',
 560          );
 561  
 562          $result = null;
 563          if ( false === $scrape_result_position ) {
 564              $result = $loopback_request_failure;
 565          } else {
 566              $error_output = substr( $body, $scrape_result_position + strlen( $needle_start ) );
 567              $error_output = substr( $error_output, 0, strpos( $error_output, $needle_end ) );
 568              $result       = json_decode( trim( $error_output ), true );
 569              if ( empty( $result ) ) {
 570                  $result = $json_parse_failure;
 571              }
 572          }
 573  
 574          // Try making request to homepage as well to see if visitors have been whitescreened.
 575          if ( true === $result ) {
 576              $url                    = home_url( '/' );
 577              $url                    = add_query_arg( $scrape_params, $url );
 578              $r                      = wp_remote_get( $url, compact( 'cookies', 'headers', 'timeout' ) );
 579              $body                   = wp_remote_retrieve_body( $r );
 580              $scrape_result_position = strpos( $body, $needle_start );
 581  
 582              if ( false === $scrape_result_position ) {
 583                  $result = $loopback_request_failure;
 584              } else {
 585                  $error_output = substr( $body, $scrape_result_position + strlen( $needle_start ) );
 586                  $error_output = substr( $error_output, 0, strpos( $error_output, $needle_end ) );
 587                  $result       = json_decode( trim( $error_output ), true );
 588                  if ( empty( $result ) ) {
 589                      $result = $json_parse_failure;
 590                  }
 591              }
 592          }
 593  
 594          delete_transient( $transient );
 595  
 596          if ( true !== $result ) {
 597  
 598              // Roll-back file change.
 599              file_put_contents( $real_file, $previous_content );
 600              if ( function_exists( 'opcache_invalidate' ) ) {
 601                  opcache_invalidate( $real_file, true );
 602              }
 603  
 604              if ( ! isset( $result['message'] ) ) {
 605                  $message = __( 'Something went wrong.' );
 606              } else {
 607                  $message = $result['message'];
 608                  unset( $result['message'] );
 609              }
 610              return new WP_Error( 'php_error', $message, $result );
 611          }
 612      }
 613  
 614      if ( $theme instanceof WP_Theme ) {
 615          $theme->cache_delete();
 616      }
 617  
 618      return true;
 619  }
 620  
 621  
 622  /**
 623   * Returns a filename of a Temporary unique file.
 624   * Please note that the calling function must unlink() this itself.
 625   *
 626   * The filename is based off the passed parameter or defaults to the current unix timestamp,
 627   * while the directory can either be passed as well, or by leaving it blank, default to a writable temporary directory.
 628   *
 629   * @since 2.6.0
 630   *
 631   * @param string $filename Optional. Filename to base the Unique file off. Default empty.
 632   * @param string $dir      Optional. Directory to store the file in. Default empty.
 633   * @return string a writable filename
 634   */
 635  function wp_tempnam( $filename = '', $dir = '' ) {
 636      if ( empty( $dir ) ) {
 637          $dir = get_temp_dir();
 638      }
 639  
 640      if ( empty( $filename ) || '.' == $filename || '/' == $filename || '\\' == $filename ) {
 641          $filename = uniqid();
 642      }
 643  
 644      // Use the basename of the given file without the extension as the name for the temporary directory
 645      $temp_filename = basename( $filename );
 646      $temp_filename = preg_replace( '|\.[^.]*$|', '', $temp_filename );
 647  
 648      // If the folder is falsey, use its parent directory name instead.
 649      if ( ! $temp_filename ) {
 650          return wp_tempnam( dirname( $filename ), $dir );
 651      }
 652  
 653      // Suffix some random data to avoid filename conflicts
 654      $temp_filename .= '-' . wp_generate_password( 6, false );
 655      $temp_filename .= '.tmp';
 656      $temp_filename  = $dir . wp_unique_filename( $dir, $temp_filename );
 657  
 658      $fp = @fopen( $temp_filename, 'x' );
 659      if ( ! $fp && is_writable( $dir ) && file_exists( $temp_filename ) ) {
 660          return wp_tempnam( $filename, $dir );
 661      }
 662      if ( $fp ) {
 663          fclose( $fp );
 664      }
 665  
 666      return $temp_filename;
 667  }
 668  
 669  /**
 670   * Makes sure that the file that was requested to be edited is allowed to be edited.
 671   *
 672   * Function will die if you are not allowed to edit the file.
 673   *
 674   * @since 1.5.0
 675   *
 676   * @param string   $file          File the user is attempting to edit.
 677   * @param string[] $allowed_files Optional. Array of allowed files to edit. `$file` must match an entry exactly.
 678   * @return string|void Returns the file name on success, dies on failure.
 679   */
 680  function validate_file_to_edit( $file, $allowed_files = array() ) {
 681      $code = validate_file( $file, $allowed_files );
 682  
 683      if ( ! $code ) {
 684          return $file;
 685      }
 686  
 687      switch ( $code ) {
 688          case 1:
 689              wp_die( __( 'Sorry, that file cannot be edited.' ) );
 690  
 691              // case 2 :
 692              // wp_die( __('Sorry, can&#8217;t call files with their real path.' ));
 693  
 694          case 3:
 695              wp_die( __( 'Sorry, that file cannot be edited.' ) );
 696      }
 697  }
 698  
 699  /**
 700   * Handle PHP uploads in WordPress, sanitizing file names, checking extensions for mime type,
 701   * and moving the file to the appropriate directory within the uploads directory.
 702   *
 703   * @access private
 704   * @since 4.0.0
 705   *
 706   * @see wp_handle_upload_error
 707   *
 708   * @param string[]       $file      Reference to a single element of `$_FILES`. Call the function once for each uploaded file.
 709   * @param string[]|false $overrides An associative array of names => values to override default variables. Default false.
 710   * @param string         $time      Time formatted in 'yyyy/mm'.
 711   * @param string         $action    Expected value for `$_POST['action']`.
 712   * @return string[] On success, returns an associative array of file attributes. On failure, returns
 713   *               `$overrides['upload_error_handler'](&$file, $message )` or `array( 'error'=>$message )`.
 714   */
 715  function _wp_handle_upload( &$file, $overrides, $time, $action ) {
 716      // The default error handler.
 717      if ( ! function_exists( 'wp_handle_upload_error' ) ) {
 718  		function wp_handle_upload_error( &$file, $message ) {
 719              return array( 'error' => $message );
 720          }
 721      }
 722  
 723      /**
 724       * Filters the data for a file before it is uploaded to WordPress.
 725       *
 726       * The dynamic portion of the hook name, `$action`, refers to the post action.
 727       *
 728       * @since 2.9.0 as 'wp_handle_upload_prefilter'.
 729       * @since 4.0.0 Converted to a dynamic hook with `$action`.
 730       *
 731       * @param string[] $file An array of data for a single file.
 732       */
 733      $file = apply_filters( "{$action}_prefilter", $file );
 734  
 735      // You may define your own function and pass the name in $overrides['upload_error_handler']
 736      $upload_error_handler = 'wp_handle_upload_error';
 737      if ( isset( $overrides['upload_error_handler'] ) ) {
 738          $upload_error_handler = $overrides['upload_error_handler'];
 739      }
 740  
 741      // You may have had one or more 'wp_handle_upload_prefilter' functions error out the file. Handle that gracefully.
 742      if ( isset( $file['error'] ) && ! is_numeric( $file['error'] ) && $file['error'] ) {
 743          return call_user_func_array( $upload_error_handler, array( &$file, $file['error'] ) );
 744      }
 745  
 746      // Install user overrides. Did we mention that this voids your warranty?
 747  
 748      // You may define your own function and pass the name in $overrides['unique_filename_callback']
 749      $unique_filename_callback = null;
 750      if ( isset( $overrides['unique_filename_callback'] ) ) {
 751          $unique_filename_callback = $overrides['unique_filename_callback'];
 752      }
 753  
 754      /*
 755       * This may not have originally been intended to be overridable,
 756       * but historically has been.
 757       */
 758      if ( isset( $overrides['upload_error_strings'] ) ) {
 759          $upload_error_strings = $overrides['upload_error_strings'];
 760      } else {
 761          // Courtesy of php.net, the strings that describe the error indicated in $_FILES[{form field}]['error'].
 762          $upload_error_strings = array(
 763              false,
 764              __( 'The uploaded file exceeds the upload_max_filesize directive in php.ini.' ),
 765              __( 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.' ),
 766              __( 'The uploaded file was only partially uploaded.' ),
 767              __( 'No file was uploaded.' ),
 768              '',
 769              __( 'Missing a temporary folder.' ),
 770              __( 'Failed to write file to disk.' ),
 771              __( 'File upload stopped by extension.' ),
 772          );
 773      }
 774  
 775      // All tests are on by default. Most can be turned off by $overrides[{test_name}] = false;
 776      $test_form = isset( $overrides['test_form'] ) ? $overrides['test_form'] : true;
 777      $test_size = isset( $overrides['test_size'] ) ? $overrides['test_size'] : true;
 778  
 779      // If you override this, you must provide $ext and $type!!
 780      $test_type = isset( $overrides['test_type'] ) ? $overrides['test_type'] : true;
 781      $mimes     = isset( $overrides['mimes'] ) ? $overrides['mimes'] : false;
 782  
 783      // A correct form post will pass this test.
 784      if ( $test_form && ( ! isset( $_POST['action'] ) || ( $_POST['action'] != $action ) ) ) {
 785          return call_user_func_array( $upload_error_handler, array( &$file, __( 'Invalid form submission.' ) ) );
 786      }
 787      // A successful upload will pass this test. It makes no sense to override this one.
 788      if ( isset( $file['error'] ) && $file['error'] > 0 ) {
 789          return call_user_func_array( $upload_error_handler, array( &$file, $upload_error_strings[ $file['error'] ] ) );
 790      }
 791  
 792      // A properly uploaded file will pass this test. There should be no reason to override this one.
 793      $test_uploaded_file = 'wp_handle_upload' === $action ? is_uploaded_file( $file['tmp_name'] ) : @is_readable( $file['tmp_name'] );
 794      if ( ! $test_uploaded_file ) {
 795          return call_user_func_array( $upload_error_handler, array( &$file, __( 'Specified file failed upload test.' ) ) );
 796      }
 797  
 798      $test_file_size = 'wp_handle_upload' === $action ? $file['size'] : filesize( $file['tmp_name'] );
 799      // A non-empty file will pass this test.
 800      if ( $test_size && ! ( $test_file_size > 0 ) ) {
 801          if ( is_multisite() ) {
 802              $error_msg = __( 'File is empty. Please upload something more substantial.' );
 803          } else {
 804              $error_msg = __( 'File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your php.ini or by post_max_size being defined as smaller than upload_max_filesize in php.ini.' );
 805          }
 806          return call_user_func_array( $upload_error_handler, array( &$file, $error_msg ) );
 807      }
 808  
 809      // A correct MIME type will pass this test. Override $mimes or use the upload_mimes filter.
 810      if ( $test_type ) {
 811          $wp_filetype     = wp_check_filetype_and_ext( $file['tmp_name'], $file['name'], $mimes );
 812          $ext             = empty( $wp_filetype['ext'] ) ? '' : $wp_filetype['ext'];
 813          $type            = empty( $wp_filetype['type'] ) ? '' : $wp_filetype['type'];
 814          $proper_filename = empty( $wp_filetype['proper_filename'] ) ? '' : $wp_filetype['proper_filename'];
 815  
 816          // Check to see if wp_check_filetype_and_ext() determined the filename was incorrect
 817          if ( $proper_filename ) {
 818              $file['name'] = $proper_filename;
 819          }
 820          if ( ( ! $type || ! $ext ) && ! current_user_can( 'unfiltered_upload' ) ) {
 821              return call_user_func_array( $upload_error_handler, array( &$file, __( 'Sorry, this file type is not permitted for security reasons.' ) ) );
 822          }
 823          if ( ! $type ) {
 824              $type = $file['type'];
 825          }
 826      } else {
 827          $type = '';
 828      }
 829  
 830      /*
 831       * A writable uploads dir will pass this test. Again, there's no point
 832       * overriding this one.
 833       */
 834      $uploads = wp_upload_dir( $time );
 835      if ( ! ( $uploads && false === $uploads['error'] ) ) {
 836          return call_user_func_array( $upload_error_handler, array( &$file, $uploads['error'] ) );
 837      }
 838  
 839      $filename = wp_unique_filename( $uploads['path'], $file['name'], $unique_filename_callback );
 840  
 841      // Move the file to the uploads dir.
 842      $new_file = $uploads['path'] . "/$filename";
 843  
 844      /**
 845       * Filters whether to short-circuit moving the uploaded file after passing all checks.
 846       *
 847       * If a non-null value is passed to the filter, moving the file and any related error
 848       * reporting will be completely skipped.
 849       *
 850       * @since 4.9.0
 851       *
 852       * @param string $move_new_file If null (default) move the file after the upload.
 853       * @param string $file          An array of data for a single file.
 854       * @param string $new_file      Filename of the newly-uploaded file.
 855       * @param string $type          File type.
 856       */
 857      $move_new_file = apply_filters( 'pre_move_uploaded_file', null, $file, $new_file, $type );
 858  
 859      if ( null === $move_new_file ) {
 860          if ( 'wp_handle_upload' === $action ) {
 861              $move_new_file = @move_uploaded_file( $file['tmp_name'], $new_file );
 862          } else {
 863              // use copy and unlink because rename breaks streams.
 864              // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
 865              $move_new_file = @copy( $file['tmp_name'], $new_file );
 866              unlink( $file['tmp_name'] );
 867          }
 868  
 869          if ( false === $move_new_file ) {
 870              if ( 0 === strpos( $uploads['basedir'], ABSPATH ) ) {
 871                  $error_path = str_replace( ABSPATH, '', $uploads['basedir'] ) . $uploads['subdir'];
 872              } else {
 873                  $error_path = basename( $uploads['basedir'] ) . $uploads['subdir'];
 874              }
 875              return $upload_error_handler(
 876                  $file,
 877                  sprintf(
 878                      /* translators: %s: Destination file path. */
 879                      __( 'The uploaded file could not be moved to %s.' ),
 880                      $error_path
 881                  )
 882              );
 883          }
 884      }
 885  
 886      // Set correct file permissions.
 887      $stat  = stat( dirname( $new_file ) );
 888      $perms = $stat['mode'] & 0000666;
 889      chmod( $new_file, $perms );
 890  
 891      // Compute the URL.
 892      $url = $uploads['url'] . "/$filename";
 893  
 894      if ( is_multisite() ) {
 895          delete_transient( 'dirsize_cache' );
 896      }
 897  
 898      /**
 899       * Filters the data array for the uploaded file.
 900       *
 901       * @since 2.1.0
 902       *
 903       * @param array  $upload {
 904       *     Array of upload data.
 905       *
 906       *     @type string $file Filename of the newly-uploaded file.
 907       *     @type string $url  URL of the uploaded file.
 908       *     @type string $type File type.
 909       * }
 910       * @param string $context The type of upload action. Values include 'upload' or 'sideload'.
 911       */
 912      return apply_filters(
 913          'wp_handle_upload',
 914          array(
 915              'file' => $new_file,
 916              'url'  => $url,
 917              'type' => $type,
 918          ),
 919          'wp_handle_sideload' === $action ? 'sideload' : 'upload'
 920      );
 921  }
 922  
 923  /**
 924   * Wrapper for _wp_handle_upload().
 925   *
 926   * Passes the {@see 'wp_handle_upload'} action.
 927   *
 928   * @since 2.0.0
 929   *
 930   * @see _wp_handle_upload()
 931   *
 932   * @param array      $file      Reference to a single element of `$_FILES`. Call the function once for
 933   *                              each uploaded file.
 934   * @param array|bool $overrides Optional. An associative array of names=>values to override default
 935   *                              variables. Default false.
 936   * @param string     $time      Optional. Time formatted in 'yyyy/mm'. Default null.
 937   * @return array On success, returns an associative array of file attributes. On failure, returns
 938   *               $overrides['upload_error_handler'](&$file, $message ) or array( 'error'=>$message ).
 939   */
 940  function wp_handle_upload( &$file, $overrides = false, $time = null ) {
 941      /*
 942       *  $_POST['action'] must be set and its value must equal $overrides['action']
 943       *  or this:
 944       */
 945      $action = 'wp_handle_upload';
 946      if ( isset( $overrides['action'] ) ) {
 947          $action = $overrides['action'];
 948      }
 949  
 950      return _wp_handle_upload( $file, $overrides, $time, $action );
 951  }
 952  
 953  /**
 954   * Wrapper for _wp_handle_upload().
 955   *
 956   * Passes the {@see 'wp_handle_sideload'} action.
 957   *
 958   * @since 2.6.0
 959   *
 960   * @see _wp_handle_upload()
 961   *
 962   * @param array      $file      An array similar to that of a PHP `$_FILES` POST array
 963   * @param array|bool $overrides Optional. An associative array of names=>values to override default
 964   *                              variables. Default false.
 965   * @param string     $time      Optional. Time formatted in 'yyyy/mm'. Default null.
 966   * @return array On success, returns an associative array of file attributes. On failure, returns
 967   *               $overrides['upload_error_handler'](&$file, $message ) or array( 'error'=>$message ).
 968   */
 969  function wp_handle_sideload( &$file, $overrides = false, $time = null ) {
 970      /*
 971       *  $_POST['action'] must be set and its value must equal $overrides['action']
 972       *  or this:
 973       */
 974      $action = 'wp_handle_sideload';
 975      if ( isset( $overrides['action'] ) ) {
 976          $action = $overrides['action'];
 977      }
 978      return _wp_handle_upload( $file, $overrides, $time, $action );
 979  }
 980  
 981  
 982  /**
 983   * Downloads a URL to a local temporary file using the WordPress HTTP API.
 984   *
 985   * Please note that the calling function must unlink() the file.
 986   *
 987   * @since 2.5.0
 988   * @since 5.2.0 Signature Verification with SoftFail was added.
 989   *
 990   * @param string $url                    The URL of the file to download.
 991   * @param int    $timeout                The timeout for the request to download the file. Default 300 seconds.
 992   * @param bool   $signature_verification Whether to perform Signature Verification. Default false.
 993   * @return string|WP_Error Filename on success, WP_Error on failure.
 994   */
 995  function download_url( $url, $timeout = 300, $signature_verification = false ) {
 996      //WARNING: The file is not automatically deleted, The script must unlink() the file.
 997      if ( ! $url ) {
 998          return new WP_Error( 'http_no_url', __( 'Invalid URL Provided.' ) );
 999      }
1000  
1001      $url_filename = basename( parse_url( $url, PHP_URL_PATH ) );
1002  
1003      $tmpfname = wp_tempnam( $url_filename );
1004      if ( ! $tmpfname ) {
1005          return new WP_Error( 'http_no_file', __( 'Could not create Temporary file.' ) );
1006      }
1007  
1008      $response = wp_safe_remote_get(
1009          $url,
1010          array(
1011              'timeout'  => $timeout,
1012              'stream'   => true,
1013              'filename' => $tmpfname,
1014          )
1015      );
1016  
1017      if ( is_wp_error( $response ) ) {
1018          unlink( $tmpfname );
1019          return $response;
1020      }
1021  
1022      $response_code = wp_remote_retrieve_response_code( $response );
1023  
1024      if ( 200 != $response_code ) {
1025          $data = array(
1026              'code' => $response_code,
1027          );
1028  
1029          // Retrieve a sample of the response body for debugging purposes.
1030          $tmpf = fopen( $tmpfname, 'rb' );
1031          if ( $tmpf ) {
1032              /**
1033               * Filters the maximum error response body size in `download_url()`.
1034               *
1035               * @since 5.1.0
1036               *
1037               * @see download_url()
1038               *
1039               * @param int $size The maximum error response body size. Default 1 KB.
1040               */
1041              $response_size = apply_filters( 'download_url_error_max_body_size', KB_IN_BYTES );
1042              $data['body']  = fread( $tmpf, $response_size );
1043              fclose( $tmpf );
1044          }
1045  
1046          unlink( $tmpfname );
1047          return new WP_Error( 'http_404', trim( wp_remote_retrieve_response_message( $response ) ), $data );
1048      }
1049  
1050      $content_md5 = wp_remote_retrieve_header( $response, 'content-md5' );
1051      if ( $content_md5 ) {
1052          $md5_check = verify_file_md5( $tmpfname, $content_md5 );
1053          if ( is_wp_error( $md5_check ) ) {
1054              unlink( $tmpfname );
1055              return $md5_check;
1056          }
1057      }
1058  
1059      // If the caller expects signature verification to occur, check to see if this URL supports it.
1060      if ( $signature_verification ) {
1061          /**
1062           * Filters the list of hosts which should have Signature Verification attempteds on.
1063           *
1064           * @since 5.2.0
1065           *
1066           * @param array List of hostnames.
1067           */
1068          $signed_hostnames       = apply_filters( 'wp_signature_hosts', array( 'wordpress.org', 'downloads.wordpress.org', 's.w.org' ) );
1069          $signature_verification = in_array( parse_url( $url, PHP_URL_HOST ), $signed_hostnames, true );
1070      }
1071  
1072      // Perform signature valiation if supported.
1073      if ( $signature_verification ) {
1074          $signature = wp_remote_retrieve_header( $response, 'x-content-signature' );
1075          if ( ! $signature ) {
1076              // Retrieve signatures from a file if the header wasn't included.
1077              // WordPress.org stores signatures at $package_url.sig
1078  
1079              $signature_url = false;
1080              $url_path      = parse_url( $url, PHP_URL_PATH );
1081              if ( substr( $url_path, -4 ) == '.zip' || substr( $url_path, -7 ) == '.tar.gz' ) {
1082                  $signature_url = str_replace( $url_path, $url_path . '.sig', $url );
1083              }
1084  
1085              /**
1086               * Filter the URL where the signature for a file is located.
1087               *
1088               * @since 5.2.0
1089               *
1090               * @param false|string $signature_url The URL where signatures can be found for a file, or false if none are known.
1091               * @param string $url                 The URL being verified.
1092               */
1093              $signature_url = apply_filters( 'wp_signature_url', $signature_url, $url );
1094  
1095              if ( $signature_url ) {
1096                  $signature_request = wp_safe_remote_get(
1097                      $signature_url,
1098                      array(
1099                          'limit_response_size' => 10 * 1024, // 10KB should be large enough for quite a few signatures.
1100                      )
1101                  );
1102  
1103                  if ( ! is_wp_error( $signature_request ) && 200 === wp_remote_retrieve_response_code( $signature_request ) ) {
1104                      $signature = explode( "\n", wp_remote_retrieve_body( $signature_request ) );
1105                  }
1106              }
1107          }
1108  
1109          // Perform the checks.
1110          $signature_verification = verify_file_signature( $tmpfname, $signature, basename( parse_url( $url, PHP_URL_PATH ) ) );
1111      }
1112  
1113      if ( is_wp_error( $signature_verification ) ) {
1114          if (
1115              /**
1116               * Filters whether Signature Verification failures should be allowed to soft fail.
1117               *
1118               * WARNING: This may be removed from a future release.
1119               *
1120               * @since 5.2.0
1121               *
1122               * @param bool   $signature_softfail If a softfail is allowed.
1123               * @param string $url                The url being accessed.
1124               */
1125              apply_filters( 'wp_signature_softfail', true, $url )
1126          ) {
1127              $signature_verification->add_data( $tmpfname, 'softfail-filename' );
1128          } else {
1129              // Hard-fail.
1130              unlink( $tmpfname );
1131          }
1132  
1133          return $signature_verification;
1134      }
1135  
1136      return $tmpfname;
1137  }
1138  
1139  /**
1140   * Calculates and compares the MD5 of a file to its expected value.
1141   *
1142   * @since 3.7.0
1143   *
1144   * @param string $filename     The filename to check the MD5 of.
1145   * @param string $expected_md5 The expected MD5 of the file, either a base64-encoded raw md5,
1146   *                             or a hex-encoded md5.
1147   * @return bool|WP_Error True on success, false when the MD5 format is unknown/unexpected,
1148   *                       WP_Error on failure.
1149   */
1150  function verify_file_md5( $filename, $expected_md5 ) {
1151      if ( 32 == strlen( $expected_md5 ) ) {
1152          $expected_raw_md5 = pack( 'H*', $expected_md5 );
1153      } elseif ( 24 == strlen( $expected_md5 ) ) {
1154          $expected_raw_md5 = base64_decode( $expected_md5 );
1155      } else {
1156          return false; // unknown format
1157      }
1158  
1159      $file_md5 = md5_file( $filename, true );
1160  
1161      if ( $file_md5 === $expected_raw_md5 ) {
1162          return true;
1163      }
1164  
1165      return new WP_Error(
1166          'md5_mismatch',
1167          sprintf(
1168              /* translators: 1: File checksum, 2: Expected checksum value. */
1169              __( 'The checksum of the file (%1$s) does not match the expected checksum value (%2$s).' ),
1170              bin2hex( $file_md5 ),
1171              bin2hex( $expected_raw_md5 )
1172          )
1173      );
1174  }
1175  
1176  /**
1177   * Verifies the contents of a file against its ED25519 signature.
1178   *
1179   * @since 5.2.0
1180   *
1181   * @param string       $filename            The file to validate.
1182   * @param string|array $signatures          A Signature provided for the file.
1183   * @param string       $filename_for_errors A friendly filename for errors. Optional.
1184   *
1185   * @return bool|WP_Error true on success, false if verification not attempted, or WP_Error describing an error condition.
1186   */
1187  function verify_file_signature( $filename, $signatures, $filename_for_errors = false ) {
1188      if ( ! $filename_for_errors ) {
1189          $filename_for_errors = wp_basename( $filename );
1190      }
1191  
1192      // Check we can process signatures.
1193      if ( ! function_exists( 'sodium_crypto_sign_verify_detached' ) || ! in_array( 'sha384', array_map( 'strtolower', hash_algos() ) ) ) {
1194          return new WP_Error(
1195              'signature_verification_unsupported',
1196              sprintf(
1197                  /* translators: %s: The filename of the package. */
1198                  __( 'The authenticity of %s could not be verified as signature verification is unavailable on this system.' ),
1199                  '<span class="code">' . esc_html( $filename_for_errors ) . '</span>'
1200              ),
1201              ( ! function_exists( 'sodium_crypto_sign_verify_detached' ) ? 'sodium_crypto_sign_verify_detached' : 'sha384' )
1202          );
1203      }
1204  
1205      // Check for a edge-case affecting PHP Maths abilities
1206      if (
1207          ! extension_loaded( 'sodium' ) &&
1208          in_array( PHP_VERSION_ID, [ 70200, 70201, 70202 ], true ) &&
1209          extension_loaded( 'opcache' )
1210      ) {
1211          // 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.
1212          // https://bugs.php.net/bug.php?id=75938
1213  
1214          return new WP_Error(
1215              'signature_verification_unsupported',
1216              sprintf(
1217                  /* translators: %s: The filename of the package. */
1218                  __( 'The authenticity of %s could not be verified as signature verification is unavailable on this system.' ),
1219                  '<span class="code">' . esc_html( $filename_for_errors ) . '</span>'
1220              ),
1221              array(
1222                  'php'    => phpversion(),
1223                  'sodium' => defined( 'SODIUM_LIBRARY_VERSION' ) ? SODIUM_LIBRARY_VERSION : ( defined( 'ParagonIE_Sodium_Compat::VERSION_STRING' ) ? ParagonIE_Sodium_Compat::VERSION_STRING : false ),
1224              )
1225          );
1226  
1227      }
1228  
1229      // Verify runtime speed of Sodium_Compat is acceptable.
1230      if ( ! extension_loaded( 'sodium' ) && ! ParagonIE_Sodium_Compat::polyfill_is_fast() ) {
1231          $sodium_compat_is_fast = false;
1232  
1233          // Allow for an old version of Sodium_Compat being loaded before the bundled WordPress one.
1234          if ( method_exists( 'ParagonIE_Sodium_Compat', 'runtime_speed_test' ) ) {
1235              // Run `ParagonIE_Sodium_Compat::runtime_speed_test()` in optimized integer mode, as that's what WordPress utilises during signing verifications.
1236              // phpcs:disable WordPress.NamingConventions.ValidVariableName
1237              $old_fastMult                      = ParagonIE_Sodium_Compat::$fastMult;
1238              ParagonIE_Sodium_Compat::$fastMult = true;
1239              $sodium_compat_is_fast             = ParagonIE_Sodium_Compat::runtime_speed_test( 100, 10 );
1240              ParagonIE_Sodium_Compat::$fastMult = $old_fastMult;
1241              // phpcs:enable
1242          }
1243  
1244          // This cannot be performed in a reasonable amount of time
1245          // https://github.com/paragonie/sodium_compat#help-sodium_compat-is-slow-how-can-i-make-it-fast
1246          if ( ! $sodium_compat_is_fast ) {
1247              return new WP_Error(
1248                  'signature_verification_unsupported',
1249                  sprintf(
1250                      /* translators: %s: The filename of the package. */
1251                      __( 'The authenticity of %s could not be verified as signature verification is unavailable on this system.' ),
1252                      '<span class="code">' . esc_html( $filename_for_errors ) . '</span>'
1253                  ),
1254                  array(
1255                      'php'                => phpversion(),
1256                      'sodium'             => defined( 'SODIUM_LIBRARY_VERSION' ) ? SODIUM_LIBRARY_VERSION : ( defined( 'ParagonIE_Sodium_Compat::VERSION_STRING' ) ? ParagonIE_Sodium_Compat::VERSION_STRING : false ),
1257                      'polyfill_is_fast'   => false,
1258                      'max_execution_time' => ini_get( 'max_execution_time' ),
1259                  )
1260              );
1261          }
1262      }
1263  
1264      if ( ! $signatures ) {
1265          return new WP_Error(
1266              'signature_verification_no_signature',
1267              sprintf(
1268                  /* translators: %s: The filename of the package. */
1269                  __( 'The authenticity of %s could not be verified as no signature was found.' ),
1270                  '<span class="code">' . esc_html( $filename_for_errors ) . '</span>'
1271              ),
1272              array(
1273                  'filename' => $filename_for_errors,
1274              )
1275          );
1276      }
1277  
1278      $trusted_keys = wp_trusted_keys();
1279      $file_hash    = hash_file( 'sha384', $filename, true );
1280  
1281      mbstring_binary_safe_encoding();
1282  
1283      $skipped_key       = 0;
1284      $skipped_signature = 0;
1285  
1286      foreach ( (array) $signatures as $signature ) {
1287          $signature_raw = base64_decode( $signature );
1288  
1289          // Ensure only valid-length signatures are considered.
1290          if ( SODIUM_CRYPTO_SIGN_BYTES !== strlen( $signature_raw ) ) {
1291              $skipped_signature++;
1292              continue;
1293          }
1294  
1295          foreach ( (array) $trusted_keys as $key ) {
1296              $key_raw = base64_decode( $key );
1297  
1298              // Only pass valid public keys through.
1299              if ( SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES !== strlen( $key_raw ) ) {
1300                  $skipped_key++;
1301                  continue;
1302              }
1303  
1304              if ( sodium_crypto_sign_verify_detached( $signature_raw, $file_hash, $key_raw ) ) {
1305                  reset_mbstring_encoding();
1306                  return true;
1307              }
1308          }
1309      }
1310  
1311      reset_mbstring_encoding();
1312  
1313      return new WP_Error(
1314          'signature_verification_failed',
1315          sprintf(
1316              /* translators: %s: The filename of the package. */
1317              __( 'The authenticity of %s could not be verified.' ),
1318              '<span class="code">' . esc_html( $filename_for_errors ) . '</span>'
1319          ),
1320          // Error data helpful for debugging:
1321          array(
1322              'filename'    => $filename_for_errors,
1323              'keys'        => $trusted_keys,
1324              'signatures'  => $signatures,
1325              'hash'        => bin2hex( $file_hash ),
1326              'skipped_key' => $skipped_key,
1327              'skipped_sig' => $skipped_signature,
1328              'php'         => phpversion(),
1329              'sodium'      => defined( 'SODIUM_LIBRARY_VERSION' ) ? SODIUM_LIBRARY_VERSION : ( defined( 'ParagonIE_Sodium_Compat::VERSION_STRING' ) ? ParagonIE_Sodium_Compat::VERSION_STRING : false ),
1330          )
1331      );
1332  }
1333  
1334  /**
1335   * Retrieve the list of signing keys trusted by WordPress.
1336   *
1337   * @since 5.2.0
1338   *
1339   * @return array List of base64-encoded Signing keys.
1340   */
1341  function wp_trusted_keys() {
1342      $trusted_keys = array();
1343  
1344      if ( time() < 1617235200 ) {
1345          // WordPress.org Key #1 - This key is only valid before April 1st, 2021.
1346          $trusted_keys[] = 'fRPyrxb/MvVLbdsYi+OOEv4xc+Eqpsj+kkAS6gNOkI0=';
1347      }
1348  
1349      // TODO: Add key #2 with longer expiration.
1350  
1351      /**
1352       * Filter the valid Signing keys used to verify the contents of files.
1353       *
1354       * @since 5.2.0
1355       *
1356       * @param array $trusted_keys The trusted keys that may sign packages.
1357       */
1358      return apply_filters( 'wp_trusted_keys', $trusted_keys );
1359  }
1360  
1361  /**
1362   * Unzips a specified ZIP file to a location on the filesystem via the WordPress
1363   * Filesystem Abstraction.
1364   *
1365   * Assumes that WP_Filesystem() has already been called and set up. Does not extract
1366   * a root-level __MACOSX directory, if present.
1367   *
1368   * Attempts to increase the PHP memory limit to 256M before uncompressing. However,
1369   * the most memory required shouldn't be much larger than the archive itself.
1370   *
1371   * @since 2.5.0
1372   *
1373   * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
1374   *
1375   * @param string $file Full path and filename of ZIP archive.
1376   * @param string $to   Full path on the filesystem to extract archive to.
1377   * @return true|WP_Error True on success, WP_Error on failure.
1378   */
1379  function unzip_file( $file, $to ) {
1380      global $wp_filesystem;
1381  
1382      if ( ! $wp_filesystem || ! is_object( $wp_filesystem ) ) {
1383          return new WP_Error( 'fs_unavailable', __( 'Could not access filesystem.' ) );
1384      }
1385  
1386      // Unzip can use a lot of memory, but not this much hopefully.
1387      wp_raise_memory_limit( 'admin' );
1388  
1389      $needed_dirs = array();
1390      $to          = trailingslashit( $to );
1391  
1392      // Determine any parent directories needed (of the upgrade directory).
1393      if ( ! $wp_filesystem->is_dir( $to ) ) { // Only do parents if no children exist.
1394          $path = preg_split( '![/\\\]!', untrailingslashit( $to ) );
1395          for ( $i = count( $path ); $i >= 0; $i-- ) {
1396              if ( empty( $path[ $i ] ) ) {
1397                  continue;
1398              }
1399  
1400              $dir = implode( '/', array_slice( $path, 0, $i + 1 ) );
1401              if ( preg_match( '!^[a-z]:$!i', $dir ) ) { // Skip it if it looks like a Windows Drive letter.
1402                  continue;
1403              }
1404  
1405              if ( ! $wp_filesystem->is_dir( $dir ) ) {
1406                  $needed_dirs[] = $dir;
1407              } else {
1408                  break; // A folder exists, therefore we don't need to check the levels below this.
1409              }
1410          }
1411      }
1412  
1413      /**
1414       * Filters whether to use ZipArchive to unzip archives.
1415       *
1416       * @since 3.0.0
1417       *
1418       * @param bool $ziparchive Whether to use ZipArchive. Default true.
1419       */
1420      if ( class_exists( 'ZipArchive', false ) && apply_filters( 'unzip_file_use_ziparchive', true ) ) {
1421          $result = _unzip_file_ziparchive( $file, $to, $needed_dirs );
1422          if ( true === $result ) {
1423              return $result;
1424          } elseif ( is_wp_error( $result ) ) {
1425              if ( 'incompatible_archive' != $result->get_error_code() ) {
1426                  return $result;
1427              }
1428          }
1429      }
1430      // Fall through to PclZip if ZipArchive is not available, or encountered an error opening the file.
1431      return _unzip_file_pclzip( $file, $to, $needed_dirs );
1432  }
1433  
1434  /**
1435   * Attempts to unzip an archive using the ZipArchive class.
1436   *
1437   * This function should not be called directly, use `unzip_file()` instead.
1438   *
1439   * Assumes that WP_Filesystem() has already been called and set up.
1440   *
1441   * @since 3.0.0
1442   * @see unzip_file()
1443   * @access private
1444   *
1445   * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
1446   *
1447   * @param string $file       Full path and filename of ZIP archive.
1448   * @param string $to         Full path on the filesystem to extract archive to.
1449   * @param array $needed_dirs A partial list of required folders needed to be created.
1450   * @return true|WP_Error True on success, WP_Error on failure.
1451   */
1452  function _unzip_file_ziparchive( $file, $to, $needed_dirs = array() ) {
1453      global $wp_filesystem;
1454  
1455      $z = new ZipArchive();
1456  
1457      $zopen = $z->open( $file, ZIPARCHIVE::CHECKCONS );
1458      if ( true !== $zopen ) {
1459          return new WP_Error( 'incompatible_archive', __( 'Incompatible Archive.' ), array( 'ziparchive_error' => $zopen ) );
1460      }
1461  
1462      $uncompressed_size = 0;
1463  
1464      for ( $i = 0; $i < $z->numFiles; $i++ ) {
1465          $info = $z->statIndex( $i );
1466          if ( ! $info ) {
1467              return new WP_Error( 'stat_failed_ziparchive', __( 'Could not retrieve file from archive.' ) );
1468          }
1469  
1470          if ( '__MACOSX/' === substr( $info['name'], 0, 9 ) ) { // Skip the OS X-created __MACOSX directory
1471              continue;
1472          }
1473  
1474          // Don't extract invalid files:
1475          if ( 0 !== validate_file( $info['name'] ) ) {
1476              continue;
1477          }
1478  
1479          $uncompressed_size += $info['size'];
1480  
1481          $dirname = dirname( $info['name'] );
1482  
1483          if ( '/' === substr( $info['name'], -1 ) ) {
1484              // Directory.
1485              $needed_dirs[] = $to . untrailingslashit( $info['name'] );
1486          } elseif ( '.' !== $dirname ) {
1487              // Path to a file.
1488              $needed_dirs[] = $to . untrailingslashit( $dirname );
1489          }
1490      }
1491  
1492      /*
1493       * disk_free_space() could return false. Assume that any falsey value is an error.
1494       * A disk that has zero free bytes has bigger problems.
1495       * Require we have enough space to unzip the file and copy its contents, with a 10% buffer.
1496       */
1497      if ( wp_doing_cron() ) {
1498          $available_space = @disk_free_space( WP_CONTENT_DIR );
1499          if ( $available_space && ( $uncompressed_size * 2.1 ) > $available_space ) {
1500              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' ) );
1501          }
1502      }
1503  
1504      $needed_dirs = array_unique( $needed_dirs );
1505      foreach ( $needed_dirs as $dir ) {
1506          // Check the parent folders of the folders all exist within the creation array.
1507          if ( untrailingslashit( $to ) == $dir ) { // Skip over the working directory, We know this exists (or will exist)
1508              continue;
1509          }
1510          if ( strpos( $dir, $to ) === false ) { // If the directory is not within the working directory, Skip it
1511              continue;
1512          }
1513  
1514          $parent_folder = dirname( $dir );
1515          while ( ! empty( $parent_folder ) && untrailingslashit( $to ) != $parent_folder && ! in_array( $parent_folder, $needed_dirs ) ) {
1516              $needed_dirs[] = $parent_folder;
1517              $parent_folder = dirname( $parent_folder );
1518          }
1519      }
1520      asort( $needed_dirs );
1521  
1522      // Create those directories if need be:
1523      foreach ( $needed_dirs as $_dir ) {
1524          // Only check to see if the Dir exists upon creation failure. Less I/O this way.
1525          if ( ! $wp_filesystem->mkdir( $_dir, FS_CHMOD_DIR ) && ! $wp_filesystem->is_dir( $_dir ) ) {
1526              return new WP_Error( 'mkdir_failed_ziparchive', __( 'Could not create directory.' ), substr( $_dir, strlen( $to ) ) );
1527          }
1528      }
1529      unset( $needed_dirs );
1530  
1531      for ( $i = 0; $i < $z->numFiles; $i++ ) {
1532          $info = $z->statIndex( $i );
1533          if ( ! $info ) {
1534              return new WP_Error( 'stat_failed_ziparchive', __( 'Could not retrieve file from archive.' ) );
1535          }
1536  
1537          if ( '/' == substr( $info['name'], -1 ) ) { // directory
1538              continue;
1539          }
1540  
1541          if ( '__MACOSX/' === substr( $info['name'], 0, 9 ) ) { // Don't extract the OS X-created __MACOSX directory files
1542              continue;
1543          }
1544  
1545          // Don't extract invalid files:
1546          if ( 0 !== validate_file( $info['name'] ) ) {
1547              continue;
1548          }
1549  
1550          $contents = $z->getFromIndex( $i );
1551          if ( false === $contents ) {
1552              return new WP_Error( 'extract_failed_ziparchive', __( 'Could not extract file from archive.' ), $info['name'] );
1553          }
1554  
1555          if ( ! $wp_filesystem->put_contents( $to . $info['name'], $contents, FS_CHMOD_FILE ) ) {
1556              return new WP_Error( 'copy_failed_ziparchive', __( 'Could not copy file.' ), $info['name'] );
1557          }
1558      }
1559  
1560      $z->close();
1561  
1562      return true;
1563  }
1564  
1565  /**
1566   * Attempts to unzip an archive using the PclZip library.
1567   *
1568   * This function should not be called directly, use `unzip_file()` instead.
1569   *
1570   * Assumes that WP_Filesystem() has already been called and set up.
1571   *
1572   * @since 3.0.0
1573   * @see unzip_file()
1574   * @access private
1575   *
1576   * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
1577   *
1578   * @param string $file       Full path and filename of ZIP archive.
1579   * @param string $to         Full path on the filesystem to extract archive to.
1580   * @param array $needed_dirs A partial list of required folders needed to be created.
1581   * @return true|WP_Error True on success, WP_Error on failure.
1582   */
1583  function _unzip_file_pclzip( $file, $to, $needed_dirs = array() ) {
1584      global $wp_filesystem;
1585  
1586      mbstring_binary_safe_encoding();
1587  
1588      require_once( ABSPATH . 'wp-admin/includes/class-pclzip.php' );
1589  
1590      $archive = new PclZip( $file );
1591  
1592      $archive_files = $archive->extract( PCLZIP_OPT_EXTRACT_AS_STRING );
1593  
1594      reset_mbstring_encoding();
1595  
1596      // Is the archive valid?
1597      if ( ! is_array( $archive_files ) ) {
1598          return new WP_Error( 'incompatible_archive', __( 'Incompatible Archive.' ), $archive->errorInfo( true ) );
1599      }
1600  
1601      if ( 0 == count( $archive_files ) ) {
1602          return new WP_Error( 'empty_archive_pclzip', __( 'Empty archive.' ) );
1603      }
1604  
1605      $uncompressed_size = 0;
1606  
1607      // Determine any children directories needed (From within the archive)
1608      foreach ( $archive_files as $file ) {
1609          if ( '__MACOSX/' === substr( $file['filename'], 0, 9 ) ) { // Skip the OS X-created __MACOSX directory
1610              continue;
1611          }
1612  
1613          $uncompressed_size += $file['size'];
1614  
1615          $needed_dirs[] = $to . untrailingslashit( $file['folder'] ? $file['filename'] : dirname( $file['filename'] ) );
1616      }
1617  
1618      /*
1619       * disk_free_space() could return false. Assume that any falsey value is an error.
1620       * A disk that has zero free bytes has bigger problems.
1621       * Require we have enough space to unzip the file and copy its contents, with a 10% buffer.
1622       */
1623      if ( wp_doing_cron() ) {
1624          $available_space = @disk_free_space( WP_CONTENT_DIR );
1625          if ( $available_space && ( $uncompressed_size * 2.1 ) > $available_space ) {
1626              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' ) );
1627          }
1628      }
1629  
1630      $needed_dirs = array_unique( $needed_dirs );
1631      foreach ( $needed_dirs as $dir ) {
1632          // Check the parent folders of the folders all exist within the creation array.
1633          if ( untrailingslashit( $to ) == $dir ) { // Skip over the working directory, We know this exists (or will exist)
1634              continue;
1635          }
1636          if ( strpos( $dir, $to ) === false ) { // If the directory is not within the working directory, Skip it
1637              continue;
1638          }
1639  
1640          $parent_folder = dirname( $dir );
1641          while ( ! empty( $parent_folder ) && untrailingslashit( $to ) != $parent_folder && ! in_array( $parent_folder, $needed_dirs ) ) {
1642              $needed_dirs[] = $parent_folder;
1643              $parent_folder = dirname( $parent_folder );
1644          }
1645      }
1646      asort( $needed_dirs );
1647  
1648      // Create those directories if need be:
1649      foreach ( $needed_dirs as $_dir ) {
1650          // Only check to see if the dir exists upon creation failure. Less I/O this way.
1651          if ( ! $wp_filesystem->mkdir( $_dir, FS_CHMOD_DIR ) && ! $wp_filesystem->is_dir( $_dir ) ) {
1652              return new WP_Error( 'mkdir_failed_pclzip', __( 'Could not create directory.' ), substr( $_dir, strlen( $to ) ) );
1653          }
1654      }
1655      unset( $needed_dirs );
1656  
1657      // Extract the files from the zip
1658      foreach ( $archive_files as $file ) {
1659          if ( $file['folder'] ) {
1660              continue;
1661          }
1662  
1663          if ( '__MACOSX/' === substr( $file['filename'], 0, 9 ) ) { // Don't extract the OS X-created __MACOSX directory files
1664              continue;
1665          }
1666  
1667          // Don't extract invalid files:
1668          if ( 0 !== validate_file( $file['filename'] ) ) {
1669              continue;
1670          }
1671  
1672          if ( ! $wp_filesystem->put_contents( $to . $file['filename'], $file['content'], FS_CHMOD_FILE ) ) {
1673              return new WP_Error( 'copy_failed_pclzip', __( 'Could not copy file.' ), $file['filename'] );
1674          }
1675      }
1676      return true;
1677  }
1678  
1679  /**
1680   * Copies a directory from one location to another via the WordPress Filesystem
1681   * Abstraction.
1682   *
1683   * Assumes that WP_Filesystem() has already been called and setup.
1684   *
1685   * @since 2.5.0
1686   *
1687   * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
1688   *
1689   * @param string $from     Source directory.
1690   * @param string $to       Destination directory.
1691   * @param array $skip_list A list of files/folders to skip copying.
1692   * @return true|WP_Error True on success, WP_Error on failure.
1693   */
1694  function copy_dir( $from, $to, $skip_list = array() ) {
1695      global $wp_filesystem;
1696  
1697      $dirlist = $wp_filesystem->dirlist( $from );
1698  
1699      $from = trailingslashit( $from );
1700      $to   = trailingslashit( $to );
1701  
1702      foreach ( (array) $dirlist as $filename => $fileinfo ) {
1703          if ( in_array( $filename, $skip_list ) ) {
1704              continue;
1705          }
1706  
1707          if ( 'f' == $fileinfo['type'] ) {
1708              if ( ! $wp_filesystem->copy( $from . $filename, $to . $filename, true, FS_CHMOD_FILE ) ) {
1709                  // If copy failed, chmod file to 0644 and try again.
1710                  $wp_filesystem->chmod( $to . $filename, FS_CHMOD_FILE );
1711                  if ( ! $wp_filesystem->copy( $from . $filename, $to . $filename, true, FS_CHMOD_FILE ) ) {
1712                      return new WP_Error( 'copy_failed_copy_dir', __( 'Could not copy file.' ), $to . $filename );
1713                  }
1714              }
1715          } elseif ( 'd' == $fileinfo['type'] ) {
1716              if ( ! $wp_filesystem->is_dir( $to . $filename ) ) {
1717                  if ( ! $wp_filesystem->mkdir( $to . $filename, FS_CHMOD_DIR ) ) {
1718                      return new WP_Error( 'mkdir_failed_copy_dir', __( 'Could not create directory.' ), $to . $filename );
1719                  }
1720              }
1721  
1722              // generate the $sub_skip_list for the subdirectory as a sub-set of the existing $skip_list
1723              $sub_skip_list = array();
1724              foreach ( $skip_list as $skip_item ) {
1725                  if ( 0 === strpos( $skip_item, $filename . '/' ) ) {
1726                      $sub_skip_list[] = preg_replace( '!^' . preg_quote( $filename, '!' ) . '/!i', '', $skip_item );
1727                  }
1728              }
1729  
1730              $result = copy_dir( $from . $filename, $to . $filename, $sub_skip_list );
1731              if ( is_wp_error( $result ) ) {
1732                  return $result;
1733              }
1734          }
1735      }
1736      return true;
1737  }
1738  
1739  /**
1740   * Initialises and connects the WordPress Filesystem Abstraction classes.
1741   *
1742   * This function will include the chosen transport and attempt connecting.
1743   *
1744   * Plugins may add extra transports, And force WordPress to use them by returning
1745   * the filename via the {@see 'filesystem_method_file'} filter.
1746   *
1747   * @since 2.5.0
1748   *
1749   * @global WP_Filesystem_Base $wp_filesystem WordPress filesystem subclass.
1750   *
1751   * @param array|false  $args                         Optional. Connection args, These are passed directly to
1752   *                                                   the `WP_Filesystem_*()` classes. Default false.
1753   * @param string|false $context                      Optional. Context for get_filesystem_method(). Default false.
1754   * @param bool         $allow_relaxed_file_ownership Optional. Whether to allow Group/World writable. Default false.
1755   * @return bool|null True on success, false on failure, null if the filesystem method class file does not exist.
1756   */
1757  function WP_Filesystem( $args = false, $context = false, $allow_relaxed_file_ownership = false ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.FunctionNameInvalid
1758      global $wp_filesystem;
1759  
1760      require_once( ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php' );
1761  
1762      $method = get_filesystem_method( $args, $context, $allow_relaxed_file_ownership );
1763  
1764      if ( ! $method ) {
1765          return false;
1766      }
1767  
1768      if ( ! class_exists( "WP_Filesystem_$method" ) ) {
1769  
1770          /**
1771           * Filters the path for a specific filesystem method class file.
1772           *
1773           * @since 2.6.0
1774           *
1775           * @see get_filesystem_method()
1776           *
1777           * @param string $path   Path to the specific filesystem method class file.
1778           * @param string $method The filesystem method to use.
1779           */
1780          $abstraction_file = apply_filters( 'filesystem_method_file', ABSPATH . 'wp-admin/includes/class-wp-filesystem-' . $method . '.php', $method );
1781  
1782          if ( ! file_exists( $abstraction_file ) ) {
1783              return;
1784          }
1785  
1786          require_once( $abstraction_file );
1787      }
1788      $method = "WP_Filesystem_$method";
1789  
1790      $wp_filesystem = new $method( $args );
1791  
1792      //Define the timeouts for the connections. Only available after the construct is called to allow for per-transport overriding of the default.
1793      if ( ! defined( 'FS_CONNECT_TIMEOUT' ) ) {
1794          define( 'FS_CONNECT_TIMEOUT', 30 );
1795      }
1796      if ( ! defined( 'FS_TIMEOUT' ) ) {
1797          define( 'FS_TIMEOUT', 30 );
1798      }
1799  
1800      if ( is_wp_error( $wp_filesystem->errors ) && $wp_filesystem->errors->has_errors() ) {
1801          return false;
1802      }
1803  
1804      if ( ! $wp_filesystem->connect() ) {
1805          return false; //There was an error connecting to the server.
1806      }
1807  
1808      // Set the permission constants if not already set.
1809      if ( ! defined( 'FS_CHMOD_DIR' ) ) {
1810          define( 'FS_CHMOD_DIR', ( fileperms( ABSPATH ) & 0777 | 0755 ) );
1811      }
1812      if ( ! defined( 'FS_CHMOD_FILE' ) ) {
1813          define( 'FS_CHMOD_FILE', ( fileperms( ABSPATH . 'index.php' ) & 0777 | 0644 ) );
1814      }
1815  
1816      return true;
1817  }
1818  
1819  /**
1820   * Determines which method to use for reading, writing, modifying, or deleting
1821   * files on the filesystem.
1822   *
1823   * The priority of the transports are: Direct, SSH2, FTP PHP Extension, FTP Sockets
1824   * (Via Sockets class, or `fsockopen()`). Valid values for these are: 'direct', 'ssh2',
1825   * 'ftpext' or 'ftpsockets'.
1826   *
1827   * The return value can be overridden by defining the `FS_METHOD` constant in `wp-config.php`,
1828   * or filtering via {@see 'filesystem_method'}.
1829   *
1830   * @link https://wordpress.org/support/article/editing-wp-config-php/#wordpress-upgrade-constants
1831   *
1832   * Plugins may define a custom transport handler, See WP_Filesystem().
1833   *
1834   * @since 2.5.0
1835   *
1836   * @global callable $_wp_filesystem_direct_method
1837   *
1838   * @param array  $args                         Optional. Connection details. Default empty array.
1839   * @param string $context                      Optional. Full path to the directory that is tested
1840   *                                             for being writable. Default empty.
1841   * @param bool   $allow_relaxed_file_ownership Optional. Whether to allow Group/World writable.
1842   *                                             Default false.
1843   * @return string The transport to use, see description for valid return values.
1844   */
1845  function get_filesystem_method( $args = array(), $context = '', $allow_relaxed_file_ownership = false ) {
1846      $method = defined( 'FS_METHOD' ) ? FS_METHOD : false; // Please ensure that this is either 'direct', 'ssh2', 'ftpext' or 'ftpsockets'
1847  
1848      if ( ! $context ) {
1849          $context = WP_CONTENT_DIR;
1850      }
1851  
1852      // If the directory doesn't exist (wp-content/languages) then use the parent directory as we'll create it.
1853      if ( WP_LANG_DIR == $context && ! is_dir( $context ) ) {
1854          $context = dirname( $context );
1855      }
1856  
1857      $context = trailingslashit( $context );
1858  
1859      if ( ! $method ) {
1860  
1861          $temp_file_name = $context . 'temp-write-test-' . str_replace( '.', '-', uniqid( '', true ) );
1862          $temp_handle    = @fopen( $temp_file_name, 'w' );
1863          if ( $temp_handle ) {
1864  
1865              // Attempt to determine the file owner of the WordPress files, and that of newly created files
1866              $wp_file_owner   = false;
1867              $temp_file_owner = false;
1868              if ( function_exists( 'fileowner' ) ) {
1869                  $wp_file_owner   = @fileowner( __FILE__ );
1870                  $temp_file_owner = @fileowner( $temp_file_name );
1871              }
1872  
1873              if ( $wp_file_owner !== false && $wp_file_owner === $temp_file_owner ) {
1874                  // WordPress is creating files as the same owner as the WordPress files,
1875                  // this means it's safe to modify & create new files via PHP.
1876                  $method                                  = 'direct';
1877                  $GLOBALS['_wp_filesystem_direct_method'] = 'file_owner';
1878              } elseif ( $allow_relaxed_file_ownership ) {
1879                  // The $context directory is writable, and $allow_relaxed_file_ownership is set, this means we can modify files
1880                  // safely in this directory. This mode doesn't create new files, only alter existing ones.
1881                  $method                                  = 'direct';
1882                  $GLOBALS['_wp_filesystem_direct_method'] = 'relaxed_ownership';
1883              }
1884  
1885              fclose( $temp_handle );
1886              @unlink( $temp_file_name );
1887          }
1888      }
1889  
1890      if ( ! $method && isset( $args['connection_type'] ) && 'ssh' == $args['connection_type'] && extension_loaded( 'ssh2' ) && function_exists( 'stream_get_contents' ) ) {
1891          $method = 'ssh2';
1892      }
1893      if ( ! $method && extension_loaded( 'ftp' ) ) {
1894          $method = 'ftpext';
1895      }
1896      if ( ! $method && ( extension_loaded( 'sockets' ) || function_exists( 'fsockopen' ) ) ) {
1897          $method = 'ftpsockets'; //Sockets: Socket extension; PHP Mode: FSockopen / fwrite / fread
1898      }
1899  
1900      /**
1901       * Filters the filesystem method to use.
1902       *
1903       * @since 2.6.0
1904       *
1905       * @param string $method  Filesystem method to return.
1906       * @param array  $args    An array of connection details for the method.
1907       * @param string $context Full path to the directory that is tested for being writable.
1908       * @param bool   $allow_relaxed_file_ownership Whether to allow Group/World writable.
1909       */
1910      return apply_filters( 'filesystem_method', $method, $args, $context, $allow_relaxed_file_ownership );
1911  }
1912  
1913  /**
1914   * Displays a form to the user to request for their FTP/SSH details in order
1915   * to connect to the filesystem.
1916   *
1917   * All chosen/entered details are saved, excluding the password.
1918   *
1919   * Hostnames may be in the form of hostname:portnumber (eg: wordpress.org:2467)
1920   * to specify an alternate FTP/SSH port.
1921   *
1922   * Plugins may override this form by returning true|false via the {@see 'request_filesystem_credentials'} filter.
1923   *
1924   * @since 2.5.0
1925   * @since 4.6.0 The `$context` parameter default changed from `false` to an empty string.
1926   *
1927   * @global string $pagenow
1928   *
1929   * @param string $form_post                    The URL to post the form to.
1930   * @param string $type                         Optional. Chosen type of filesystem. Default empty.
1931   * @param bool   $error                        Optional. Whether the current request has failed to connect.
1932   *                                             Default false.
1933   * @param string $context                      Optional. Full path to the directory that is tested for being
1934   *                                             writable. Default empty.
1935   * @param array  $extra_fields                 Optional. Extra `POST` fields to be checked for inclusion in
1936   *                                             the post. Default null.
1937   * @param bool   $allow_relaxed_file_ownership Optional. Whether to allow Group/World writable. Default false.
1938   *
1939   * @return bool True on success, false on failure.
1940   */
1941  function request_filesystem_credentials( $form_post, $type = '', $error = false, $context = '', $extra_fields = null, $allow_relaxed_file_ownership = false ) {
1942      global $pagenow;
1943  
1944      /**
1945       * Filters the filesystem credentials form output.
1946       *
1947       * Returning anything other than an empty string will effectively short-circuit
1948       * output of the filesystem credentials form, returning that value instead.
1949       *
1950       * @since 2.5.0
1951       * @since 4.6.0 The `$context` parameter default changed from `false` to an empty string.
1952       *
1953       * @param mixed  $output                       Form output to return instead. Default empty.
1954       * @param string $form_post                    The URL to post the form to.
1955       * @param string $type                         Chosen type of filesystem.
1956       * @param bool   $error                        Whether the current request has failed to connect.
1957       *                                             Default false.
1958       * @param string $context                      Full path to the directory that is tested for
1959       *                                             being writable.
1960       * @param bool   $allow_relaxed_file_ownership Whether to allow Group/World writable.
1961       *                                             Default false.
1962       * @param array  $extra_fields                 Extra POST fields.
1963       */
1964      $req_cred = apply_filters( 'request_filesystem_credentials', '', $form_post, $type, $error, $context, $extra_fields, $allow_relaxed_file_ownership );
1965      if ( '' !== $req_cred ) {
1966          return $req_cred;
1967      }
1968  
1969      if ( empty( $type ) ) {
1970          $type = get_filesystem_method( array(), $context, $allow_relaxed_file_ownership );
1971      }
1972  
1973      if ( 'direct' == $type ) {
1974          return true;
1975      }
1976  
1977      if ( is_null( $extra_fields ) ) {
1978          $extra_fields = array( 'version', 'locale' );
1979      }
1980  
1981      $credentials = get_option(
1982          'ftp_credentials',
1983          array(
1984              'hostname' => '',
1985              'username' => '',
1986          )
1987      );
1988  
1989      $submitted_form = wp_unslash( $_POST );
1990  
1991      // Verify nonce, or unset submitted form field values on failure
1992      if ( ! isset( $_POST['_fs_nonce'] ) || ! wp_verify_nonce( $_POST['_fs_nonce'], 'filesystem-credentials' ) ) {
1993          unset(
1994              $submitted_form['hostname'],
1995              $submitted_form['username'],
1996              $submitted_form['password'],
1997              $submitted_form['public_key'],
1998              $submitted_form['private_key'],
1999              $submitted_form['connection_type']
2000          );
2001      }
2002  
2003      // 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)
2004      $credentials['hostname'] = defined( 'FTP_HOST' ) ? FTP_HOST : ( ! empty( $submitted_form['hostname'] ) ? $submitted_form['hostname'] : $credentials['hostname'] );
2005      $credentials['username'] = defined( 'FTP_USER' ) ? FTP_USER : ( ! empty( $submitted_form['username'] ) ? $submitted_form['username'] : $credentials['username'] );
2006      $credentials['password'] = defined( 'FTP_PASS' ) ? FTP_PASS : ( ! empty( $submitted_form['password'] ) ? $submitted_form['password'] : '' );
2007  
2008      // Check to see if we are setting the public/private keys for ssh
2009      $credentials['public_key']  = defined( 'FTP_PUBKEY' ) ? FTP_PUBKEY : ( ! empty( $submitted_form['public_key'] ) ? $submitted_form['public_key'] : '' );
2010      $credentials['private_key'] = defined( 'FTP_PRIKEY' ) ? FTP_PRIKEY : ( ! empty( $submitted_form['private_key'] ) ? $submitted_form['private_key'] : '' );
2011  
2012      // Sanitize the hostname, Some people might pass in odd-data:
2013      $credentials['hostname'] = preg_replace( '|\w+://|', '', $credentials['hostname'] ); //Strip any schemes off
2014  
2015      if ( strpos( $credentials['hostname'], ':' ) ) {
2016          list( $credentials['hostname'], $credentials['port'] ) = explode( ':', $credentials['hostname'], 2 );
2017          if ( ! is_numeric( $credentials['port'] ) ) {
2018              unset( $credentials['port'] );
2019          }
2020      } else {
2021          unset( $credentials['port'] );
2022      }
2023  
2024      if ( ( defined( 'FTP_SSH' ) && FTP_SSH ) || ( defined( 'FS_METHOD' ) && 'ssh2' == FS_METHOD ) ) {
2025          $credentials['connection_type'] = 'ssh';
2026      } elseif ( ( defined( 'FTP_SSL' ) && FTP_SSL ) && 'ftpext' == $type ) { //Only the FTP Extension understands SSL
2027          $credentials['connection_type'] = 'ftps';
2028      } elseif ( ! empty( $submitted_form['connection_type'] ) ) {
2029          $credentials['connection_type'] = $submitted_form['connection_type'];
2030      } elseif ( ! isset( $credentials['connection_type'] ) ) { //All else fails (And it's not defaulted to something else saved), Default to FTP
2031          $credentials['connection_type'] = 'ftp';
2032      }
2033      if ( ! $error &&
2034              (
2035                  ( ! empty( $credentials['password'] ) && ! empty( $credentials['username'] ) && ! empty( $credentials['hostname'] ) ) ||
2036                  ( 'ssh' == $credentials['connection_type'] && ! empty( $credentials['public_key'] ) && ! empty( $credentials['private_key'] ) )
2037              ) ) {
2038          $stored_credentials = $credentials;
2039          if ( ! empty( $stored_credentials['port'] ) ) { //save port as part of hostname to simplify above code.
2040              $stored_credentials['hostname'] .= ':' . $stored_credentials['port'];
2041          }
2042  
2043          unset( $stored_credentials['password'], $stored_credentials['port'], $stored_credentials['private_key'], $stored_credentials['public_key'] );
2044          if ( ! wp_installing() ) {
2045              update_option( 'ftp_credentials', $stored_credentials );
2046          }
2047          return $credentials;
2048      }
2049      $hostname        = isset( $credentials['hostname'] ) ? $credentials['hostname'] : '';
2050      $username        = isset( $credentials['username'] ) ? $credentials['username'] : '';
2051      $public_key      = isset( $credentials['public_key'] ) ? $credentials['public_key'] : '';
2052      $private_key     = isset( $credentials['private_key'] ) ? $credentials['private_key'] : '';
2053      $port            = isset( $credentials['port'] ) ? $credentials['port'] : '';
2054      $connection_type = isset( $credentials['connection_type'] ) ? $credentials['connection_type'] : '';
2055  
2056      if ( $error ) {
2057          $error_string = __( '<strong>ERROR:</strong> There was an error connecting to the server, Please verify the settings are correct.' );
2058          if ( is_wp_error( $error ) ) {
2059              $error_string = esc_html( $error->get_error_message() );
2060          }
2061          echo '<div id="message" class="error"><p>' . $error_string . '</p></div>';
2062      }
2063  
2064      $types = array();
2065      if ( extension_loaded( 'ftp' ) || extension_loaded( 'sockets' ) || function_exists( 'fsockopen' ) ) {
2066          $types['ftp'] = __( 'FTP' );
2067      }
2068      if ( extension_loaded( 'ftp' ) ) { //Only this supports FTPS
2069          $types['ftps'] = __( 'FTPS (SSL)' );
2070      }
2071      if ( extension_loaded( 'ssh2' ) && function_exists( 'stream_get_contents' ) ) {
2072          $types['ssh'] = __( 'SSH2' );
2073      }
2074  
2075      /**
2076       * Filters the connection types to output to the filesystem credentials form.
2077       *
2078       * @since 2.9.0
2079       * @since 4.6.0 The `$context` parameter default changed from `false` to an empty string.
2080       *
2081       * @param array  $types       Types of connections.
2082       * @param array  $credentials Credentials to connect with.
2083       * @param string $type        Chosen filesystem method.
2084       * @param object $error       Error object.
2085       * @param string $context     Full path to the directory that is tested
2086       *                            for being writable.
2087       */
2088      $types = apply_filters( 'fs_ftp_connection_types', $types, $credentials, $type, $error, $context );
2089  
2090      ?>
2091  <form action="<?php echo esc_url( $form_post ); ?>" method="post">
2092  <div id="request-filesystem-credentials-form" class="request-filesystem-credentials-form">
2093      <?php
2094      // Print a H1 heading in the FTP credentials modal dialog, default is a H2.
2095      $heading_tag = 'h2';
2096      if ( 'plugins.php' === $pagenow || 'plugin-install.php' === $pagenow ) {
2097          $heading_tag = 'h1';
2098      }
2099      echo "<$heading_tag id='request-filesystem-credentials-title'>" . __( 'Connection Information' ) . "</$heading_tag>";
2100      ?>
2101  <p id="request-filesystem-credentials-desc">
2102      <?php
2103      $label_user = __( 'Username' );
2104      $label_pass = __( 'Password' );
2105      _e( 'To perform the requested action, WordPress needs to access your web server.' );
2106      echo ' ';
2107      if ( ( isset( $types['ftp'] ) || isset( $types['ftps'] ) ) ) {
2108          if ( isset( $types['ssh'] ) ) {
2109              _e( 'Please enter your FTP or SSH credentials to proceed.' );
2110              $label_user = __( 'FTP/SSH Username' );
2111              $label_pass = __( 'FTP/SSH Password' );
2112          } else {
2113              _e( 'Please enter your FTP credentials to proceed.' );
2114              $label_user = __( 'FTP Username' );
2115              $label_pass = __( 'FTP Password' );
2116          }
2117          echo ' ';
2118      }
2119      _e( 'If you do not remember your credentials, you should contact your web host.' );
2120  
2121      $hostname_value = esc_attr( $hostname );
2122      if ( ! empty( $port ) ) {
2123          $hostname_value .= ":$port";
2124      }
2125  
2126      $password_value = '';
2127      if ( defined( 'FTP_PASS' ) ) {
2128          $password_value = '*****';
2129      }
2130      ?>
2131  </p>
2132  <label for="hostname">
2133      <span class="field-title"><?php _e( 'Hostname' ); ?></span>
2134      <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' ) ); ?> />
2135  </label>
2136  <div class="ftp-username">
2137      <label for="username">
2138          <span class="field-title"><?php echo $label_user; ?></span>
2139          <input name="username" type="text" id="username" value="<?php echo esc_attr( $username ); ?>"<?php disabled( defined( 'FTP_USER' ) ); ?> />
2140      </label>
2141  </div>
2142  <div class="ftp-password">
2143      <label for="password">
2144          <span class="field-title"><?php echo $label_pass; ?></span>
2145          <input name="password" type="password" id="password" value="<?php echo $password_value; ?>"<?php disabled( defined( 'FTP_PASS' ) ); ?> />
2146          <em>
2147          <?php
2148          if ( ! defined( 'FTP_PASS' ) ) {
2149              _e( 'This password will not be stored on the server.' );}
2150          ?>
2151  </em>
2152      </label>
2153  </div>
2154  <fieldset>
2155  <legend><?php _e( 'Connection Type' ); ?></legend>
2156      <?php
2157      $disabled = disabled( ( defined( 'FTP_SSL' ) && FTP_SSL ) || ( defined( 'FTP_SSH' ) && FTP_SSH ), true, false );
2158      foreach ( $types as $name => $text ) :
2159          ?>
2160      <label for="<?php echo esc_attr( $name ); ?>">
2161          <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; ?> />
2162          <?php echo $text; ?>
2163      </label>
2164          <?php
2165      endforeach;
2166      ?>
2167  </fieldset>
2168      <?php
2169      if ( isset( $types['ssh'] ) ) {
2170          $hidden_class = '';
2171          if ( 'ssh' != $connection_type || empty( $connection_type ) ) {
2172              $hidden_class = ' class="hidden"';
2173          }
2174          ?>
2175  <fieldset id="ssh-keys"<?php echo $hidden_class; ?>>
2176  <legend><?php _e( 'Authentication Keys' ); ?></legend>
2177  <label for="public_key">
2178      <span class="field-title"><?php _e( 'Public Key:' ); ?></span>
2179      <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' ) ); ?> />
2180  </label>
2181  <label for="private_key">
2182      <span class="field-title"><?php _e( 'Private Key:' ); ?></span>
2183      <input name="private_key" type="text" id="private_key" value="<?php echo esc_attr( $private_key ); ?>"<?php disabled( defined( 'FTP_PRIKEY' ) ); ?> />
2184  </label>
2185  <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>
2186  </fieldset>
2187          <?php
2188      }
2189  
2190      foreach ( (array) $extra_fields as $field ) {
2191          if ( isset( $submitted_form[ $field ] ) ) {
2192              echo '<input type="hidden" name="' . esc_attr( $field ) . '" value="' . esc_attr( $submitted_form[ $field ] ) . '" />';
2193          }
2194      }
2195      ?>
2196      <p class="request-filesystem-credentials-action-buttons">
2197          <?php wp_nonce_field( 'filesystem-credentials', '_fs_nonce', false, true ); ?>
2198          <button class="button cancel-button" data-js-action="close" type="button"><?php _e( 'Cancel' ); ?></button>
2199          <?php submit_button( __( 'Proceed' ), '', 'upgrade', false ); ?>
2200      </p>
2201  </div>
2202  </form>
2203      <?php
2204      return false;
2205  }
2206  
2207  /**
2208   * Print the filesystem credentials modal when needed.
2209   *
2210   * @since 4.2.0
2211   */
2212  function wp_print_request_filesystem_credentials_modal() {
2213      $filesystem_method = get_filesystem_method();
2214      ob_start();
2215      $filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
2216      ob_end_clean();
2217      $request_filesystem_credentials = ( $filesystem_method != 'direct' && ! $filesystem_credentials_are_stored );
2218      if ( ! $request_filesystem_credentials ) {
2219          return;
2220      }
2221      ?>
2222      <div id="request-filesystem-credentials-dialog" class="notification-dialog-wrap request-filesystem-credentials-dialog">
2223          <div class="notification-dialog-background"></div>
2224          <div class="notification-dialog" role="dialog" aria-labelledby="request-filesystem-credentials-title" tabindex="0">
2225              <div class="request-filesystem-credentials-dialog-content">
2226                  <?php request_filesystem_credentials( site_url() ); ?>
2227              </div>
2228          </div>
2229      </div>
2230      <?php
2231  }


Generated: Thu Sep 19 01:00:03 2019 Cross-referenced by PHPXref 0.7.1