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


Generated: Tue Jan 28 01:00:03 2020 Cross-referenced by PHPXref 0.7.1