[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

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


Generated: Sun Oct 17 01:00:03 2021 Cross-referenced by PHPXref 0.7.1