]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-admin/includes/file.php
WordPress 4.5
[autoinstalls/wordpress.git] / wp-admin / includes / file.php
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'        => __( 'Static Front Page' ),
39         // Attachments
40         'attachment.php'        => __( 'Attachment Template' ),
41         'image.php'             => __( 'Image Attachment Template' ),
42         'video.php'             => __( 'Video Attachment Template' ),
43         'audio.php'             => __( 'Audio Attachment Template' ),
44         'application.php'       => __( 'Application Attachment Template' ),
45         // Stylesheets
46         'style.css'             => __( 'Stylesheet' ),
47         'editor-style.css'      => __( 'Visual Editor Stylesheet' ),
48         'editor-style-rtl.css'  => __( 'Visual Editor RTL Stylesheet' ),
49         'rtl.css'               => __( 'RTL Stylesheet' ),
50         // Other
51         'my-hacks.php'          => __( 'my-hacks.php (legacy hacks support)' ),
52         '.htaccess'             => __( '.htaccess (for rewrite rules )' ),
53         // Deprecated files
54         'wp-layout.css'         => __( 'Stylesheet' ),
55         'wp-comments.php'       => __( 'Comments Template' ),
56         'wp-comments-popup.php' => __( 'Popup Comments Template' ),
57         'comments-popup.php'    => __( 'Popup Comments' ),
58 );
59
60 /**
61  * Get the description for standard WordPress theme files and other various standard
62  * WordPress files
63  *
64  * @since 1.5.0
65  *
66  * @global array $wp_file_descriptions
67  * @param string $file Filesystem path or filename
68  * @return string Description of file from $wp_file_descriptions or basename of $file if description doesn't exist.
69  *                Appends 'Page Template' to basename of $file if the file is a page template
70  */
71 function get_file_description( $file ) {
72         global $wp_file_descriptions, $allowed_files;
73
74         $relative_pathinfo = pathinfo( $file );
75         $file_path = $allowed_files[ $file ];
76         if ( isset( $wp_file_descriptions[ basename( $file ) ] ) && '.' === $relative_pathinfo['dirname'] ) {
77                 return $wp_file_descriptions[ basename( $file ) ];
78         } elseif ( file_exists( $file_path ) && is_file( $file_path ) ) {
79                 $template_data = implode( '', file( $file_path ) );
80                 if ( preg_match( '|Template Name:(.*)$|mi', $template_data, $name ) ) {
81                         return sprintf( __( '%s Page Template' ), _cleanup_header_comment( $name[1] ) );
82                 }
83         }
84
85         return trim( basename( $file ) );
86 }
87
88 /**
89  * Get the absolute filesystem path to the root of the WordPress installation
90  *
91  * @since 1.5.0
92  *
93  * @return string Full filesystem path to the root of the WordPress installation
94  */
95 function get_home_path() {
96         $home    = set_url_scheme( get_option( 'home' ), 'http' );
97         $siteurl = set_url_scheme( get_option( 'siteurl' ), 'http' );
98         if ( ! empty( $home ) && 0 !== strcasecmp( $home, $siteurl ) ) {
99                 $wp_path_rel_to_home = str_ireplace( $home, '', $siteurl ); /* $siteurl - $home */
100                 $pos = strripos( str_replace( '\\', '/', $_SERVER['SCRIPT_FILENAME'] ), trailingslashit( $wp_path_rel_to_home ) );
101                 $home_path = substr( $_SERVER['SCRIPT_FILENAME'], 0, $pos );
102                 $home_path = trailingslashit( $home_path );
103         } else {
104                 $home_path = ABSPATH;
105         }
106
107         return str_replace( '\\', '/', $home_path );
108 }
109
110 /**
111  * Returns a listing of all files in the specified folder and all subdirectories up to 100 levels deep.
112  * The depth of the recursiveness can be controlled by the $levels param.
113  *
114  * @since 2.6.0
115  *
116  * @param string $folder Optional. Full path to folder. Default empty.
117  * @param int    $levels Optional. Levels of folders to follow, Default 100 (PHP Loop limit).
118  * @return bool|array False on failure, Else array of files
119  */
120 function list_files( $folder = '', $levels = 100 ) {
121         if ( empty($folder) )
122                 return false;
123
124         if ( ! $levels )
125                 return false;
126
127         $files = array();
128         if ( $dir = @opendir( $folder ) ) {
129                 while (($file = readdir( $dir ) ) !== false ) {
130                         if ( in_array($file, array('.', '..') ) )
131                                 continue;
132                         if ( is_dir( $folder . '/' . $file ) ) {
133                                 $files2 = list_files( $folder . '/' . $file, $levels - 1);
134                                 if ( $files2 )
135                                         $files = array_merge($files, $files2 );
136                                 else
137                                         $files[] = $folder . '/' . $file . '/';
138                         } else {
139                                 $files[] = $folder . '/' . $file;
140                         }
141                 }
142         }
143         @closedir( $dir );
144         return $files;
145 }
146
147 /**
148  * Returns a filename of a Temporary unique file.
149  * Please note that the calling function must unlink() this itself.
150  *
151  * The filename is based off the passed parameter or defaults to the current unix timestamp,
152  * while the directory can either be passed as well, or by leaving it blank, default to a writable temporary directory.
153  *
154  * @since 2.6.0
155  *
156  * @param string $filename Optional. Filename to base the Unique file off. Default empty.
157  * @param string $dir      Optional. Directory to store the file in. Default empty.
158  * @return string a writable filename
159  */
160 function wp_tempnam( $filename = '', $dir = '' ) {
161         if ( empty( $dir ) ) {
162                 $dir = get_temp_dir();
163         }
164
165         if ( empty( $filename ) || '.' == $filename || '/' == $filename ) {
166                 $filename = time();
167         }
168
169         // Use the basename of the given file without the extension as the name for the temporary directory
170         $temp_filename = basename( $filename );
171         $temp_filename = preg_replace( '|\.[^.]*$|', '', $temp_filename );
172
173         // If the folder is falsey, use its parent directory name instead.
174         if ( ! $temp_filename ) {
175                 return wp_tempnam( dirname( $filename ), $dir );
176         }
177
178         // Suffix some random data to avoid filename conflicts
179         $temp_filename .= '-' . wp_generate_password( 6, false );
180         $temp_filename .= '.tmp';
181         $temp_filename = $dir . wp_unique_filename( $dir, $temp_filename );
182
183         $fp = @fopen( $temp_filename, 'x' );
184         if ( ! $fp && is_writable( $dir ) && file_exists( $temp_filename ) ) {
185                 return wp_tempnam( $filename, $dir );
186         }
187         if ( $fp ) {
188                 fclose( $fp );
189         }
190
191         return $temp_filename;
192 }
193
194 /**
195  * Make sure that the file that was requested to edit, is allowed to be edited
196  *
197  * Function will die if you are not allowed to edit the file
198  *
199  * @since 1.5.0
200  *
201  * @param string $file file the users is attempting to edit
202  * @param array $allowed_files Array of allowed files to edit, $file must match an entry exactly
203  * @return string|null
204  */
205 function validate_file_to_edit( $file, $allowed_files = '' ) {
206         $code = validate_file( $file, $allowed_files );
207
208         if (!$code )
209                 return $file;
210
211         switch ( $code ) {
212                 case 1 :
213                         wp_die( __( 'Sorry, that file cannot be edited.' ) );
214
215                 // case 2 :
216                 // wp_die( __('Sorry, can&#8217;t call files with their real path.' ));
217
218                 case 3 :
219                         wp_die( __( 'Sorry, that file cannot be edited.' ) );
220         }
221 }
222
223 /**
224  * Handle PHP uploads in WordPress, sanitizing file names, checking extensions for mime type,
225  * and moving the file to the appropriate directory within the uploads directory.
226  *
227  * @access private
228  * @since 4.0.0
229  *
230  * @see wp_handle_upload_error
231  *
232  * @param array       $file      Reference to a single element of $_FILES. Call the function once for each uploaded file.
233  * @param array|false $overrides An associative array of names => values to override default variables. Default false.
234  * @param string      $time      Time formatted in 'yyyy/mm'.
235  * @param string      $action    Expected value for $_POST['action'].
236  * @return array On success, returns an associative array of file attributes. On failure, returns
237  *               $overrides['upload_error_handler'](&$file, $message ) or array( 'error'=>$message ).
238  */
239 function _wp_handle_upload( &$file, $overrides, $time, $action ) {
240         // The default error handler.
241         if ( ! function_exists( 'wp_handle_upload_error' ) ) {
242                 function wp_handle_upload_error( &$file, $message ) {
243                         return array( 'error' => $message );
244                 }
245         }
246
247         /**
248          * Filter the data for a file before it is uploaded to WordPress.
249          *
250          * The dynamic portion of the hook name, `$action`, refers to the post action.
251          *
252          * @since 2.9.0 as 'wp_handle_upload_prefilter'.
253          * @since 4.0.0 Converted to a dynamic hook with `$action`.
254          *
255          * @param array $file An array of data for a single file.
256          */
257         $file = apply_filters( "{$action}_prefilter", $file );
258
259         // You may define your own function and pass the name in $overrides['upload_error_handler']
260         $upload_error_handler = 'wp_handle_upload_error';
261         if ( isset( $overrides['upload_error_handler'] ) ) {
262                 $upload_error_handler = $overrides['upload_error_handler'];
263         }
264
265         // You may have had one or more 'wp_handle_upload_prefilter' functions error out the file. Handle that gracefully.
266         if ( isset( $file['error'] ) && ! is_numeric( $file['error'] ) && $file['error'] ) {
267                 return $upload_error_handler( $file, $file['error'] );
268         }
269
270         // Install user overrides. Did we mention that this voids your warranty?
271
272         // You may define your own function and pass the name in $overrides['unique_filename_callback']
273         $unique_filename_callback = null;
274         if ( isset( $overrides['unique_filename_callback'] ) ) {
275                 $unique_filename_callback = $overrides['unique_filename_callback'];
276         }
277
278         /*
279          * This may not have orignially been intended to be overrideable,
280          * but historically has been.
281          */
282         if ( isset( $overrides['upload_error_strings'] ) ) {
283                 $upload_error_strings = $overrides['upload_error_strings'];
284         } else {
285                 // Courtesy of php.net, the strings that describe the error indicated in $_FILES[{form field}]['error'].
286                 $upload_error_strings = array(
287                         false,
288                         __( 'The uploaded file exceeds the upload_max_filesize directive in php.ini.' ),
289                         __( 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.' ),
290                         __( 'The uploaded file was only partially uploaded.' ),
291                         __( 'No file was uploaded.' ),
292                         '',
293                         __( 'Missing a temporary folder.' ),
294                         __( 'Failed to write file to disk.' ),
295                         __( 'File upload stopped by extension.' )
296                 );
297         }
298
299         // All tests are on by default. Most can be turned off by $overrides[{test_name}] = false;
300         $test_form = isset( $overrides['test_form'] ) ? $overrides['test_form'] : true;
301         $test_size = isset( $overrides['test_size'] ) ? $overrides['test_size'] : true;
302
303         // If you override this, you must provide $ext and $type!!
304         $test_type = isset( $overrides['test_type'] ) ? $overrides['test_type'] : true;
305         $mimes = isset( $overrides['mimes'] ) ? $overrides['mimes'] : false;
306
307         // A correct form post will pass this test.
308         if ( $test_form && ( ! isset( $_POST['action'] ) || ( $_POST['action'] != $action ) ) ) {
309                 return call_user_func( $upload_error_handler, $file, __( 'Invalid form submission.' ) );
310         }
311         // A successful upload will pass this test. It makes no sense to override this one.
312         if ( isset( $file['error'] ) && $file['error'] > 0 ) {
313                 return call_user_func( $upload_error_handler, $file, $upload_error_strings[ $file['error'] ] );
314         }
315
316         $test_file_size = 'wp_handle_upload' === $action ? $file['size'] : filesize( $file['tmp_name'] );
317         // A non-empty file will pass this test.
318         if ( $test_size && ! ( $test_file_size > 0 ) ) {
319                 if ( is_multisite() ) {
320                         $error_msg = __( 'File is empty. Please upload something more substantial.' );
321                 } else {
322                         $error_msg = __( 'File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your php.ini or by post_max_size being defined as smaller than upload_max_filesize in php.ini.' );
323                 }
324                 return call_user_func( $upload_error_handler, $file, $error_msg );
325         }
326
327         // A properly uploaded file will pass this test. There should be no reason to override this one.
328         $test_uploaded_file = 'wp_handle_upload' === $action ? @ is_uploaded_file( $file['tmp_name'] ) : @ is_file( $file['tmp_name'] );
329         if ( ! $test_uploaded_file ) {
330                 return call_user_func( $upload_error_handler, $file, __( 'Specified file failed upload test.' ) );
331         }
332
333         // A correct MIME type will pass this test. Override $mimes or use the upload_mimes filter.
334         if ( $test_type ) {
335                 $wp_filetype = wp_check_filetype_and_ext( $file['tmp_name'], $file['name'], $mimes );
336                 $ext = empty( $wp_filetype['ext'] ) ? '' : $wp_filetype['ext'];
337                 $type = empty( $wp_filetype['type'] ) ? '' : $wp_filetype['type'];
338                 $proper_filename = empty( $wp_filetype['proper_filename'] ) ? '' : $wp_filetype['proper_filename'];
339
340                 // Check to see if wp_check_filetype_and_ext() determined the filename was incorrect
341                 if ( $proper_filename ) {
342                         $file['name'] = $proper_filename;
343                 }
344                 if ( ( ! $type || !$ext ) && ! current_user_can( 'unfiltered_upload' ) ) {
345                         return call_user_func( $upload_error_handler, $file, __( 'Sorry, this file type is not permitted for security reasons.' ) );
346                 }
347                 if ( ! $type ) {
348                         $type = $file['type'];
349                 }
350         } else {
351                 $type = '';
352         }
353
354         /*
355          * A writable uploads dir will pass this test. Again, there's no point
356          * overriding this one.
357          */
358         if ( ! ( ( $uploads = wp_upload_dir( $time ) ) && false === $uploads['error'] ) ) {
359                 return call_user_func( $upload_error_handler, $file, $uploads['error'] );
360         }
361
362         $filename = wp_unique_filename( $uploads['path'], $file['name'], $unique_filename_callback );
363
364         // Move the file to the uploads dir.
365         $new_file = $uploads['path'] . "/$filename";
366         if ( 'wp_handle_upload' === $action ) {
367                 $move_new_file = @ move_uploaded_file( $file['tmp_name'], $new_file );
368         } else {
369                 // use copy and unlink because rename breaks streams.
370                 $move_new_file = @ copy( $file['tmp_name'], $new_file );
371                 unlink( $file['tmp_name'] );
372         }
373
374         if ( false === $move_new_file ) {
375                 if ( 0 === strpos( $uploads['basedir'], ABSPATH ) ) {
376                         $error_path = str_replace( ABSPATH, '', $uploads['basedir'] ) . $uploads['subdir'];
377                 } else {
378                         $error_path = basename( $uploads['basedir'] ) . $uploads['subdir'];
379                 }
380                 return $upload_error_handler( $file, sprintf( __('The uploaded file could not be moved to %s.' ), $error_path ) );
381         }
382
383         // Set correct file permissions.
384         $stat = stat( dirname( $new_file ));
385         $perms = $stat['mode'] & 0000666;
386         @ chmod( $new_file, $perms );
387
388         // Compute the URL.
389         $url = $uploads['url'] . "/$filename";
390
391         if ( is_multisite() ) {
392                 delete_transient( 'dirsize_cache' );
393         }
394
395         /**
396          * Filter the data array for the uploaded file.
397          *
398          * @since 2.1.0
399          *
400          * @param array  $upload {
401          *     Array of upload data.
402          *
403          *     @type string $file Filename of the newly-uploaded file.
404          *     @type string $url  URL of the uploaded file.
405          *     @type string $type File type.
406          * }
407          * @param string $context The type of upload action. Values include 'upload' or 'sideload'.
408          */
409         return apply_filters( 'wp_handle_upload', array(
410                 'file' => $new_file,
411                 'url'  => $url,
412                 'type' => $type
413         ), 'wp_handle_sideload' === $action ? 'sideload' : 'upload' );
414 }
415
416 /**
417  * Wrapper for _wp_handle_upload(), passes 'wp_handle_upload' action.
418  *
419  * @since 2.0.0
420  *
421  * @see _wp_handle_upload()
422  *
423  * @param array      $file      Reference to a single element of $_FILES. Call the function once for
424  *                              each uploaded file.
425  * @param array|bool $overrides Optional. An associative array of names=>values to override default
426  *                              variables. Default false.
427  * @param string     $time      Optional. Time formatted in 'yyyy/mm'. Default null.
428  * @return array On success, returns an associative array of file attributes. On failure, returns
429  *               $overrides['upload_error_handler'](&$file, $message ) or array( 'error'=>$message ).
430  */
431 function wp_handle_upload( &$file, $overrides = false, $time = null ) {
432         /*
433          *  $_POST['action'] must be set and its value must equal $overrides['action']
434          *  or this:
435          */
436         $action = 'wp_handle_upload';
437         if ( isset( $overrides['action'] ) ) {
438                 $action = $overrides['action'];
439         }
440
441         return _wp_handle_upload( $file, $overrides, $time, $action );
442 }
443
444 /**
445  * Wrapper for _wp_handle_upload(), passes 'wp_handle_sideload' action
446  *
447  * @since 2.6.0
448  *
449  * @see _wp_handle_upload()
450  *
451  * @param array      $file      An array similar to that of a PHP $_FILES POST array
452  * @param array|bool $overrides Optional. An associative array of names=>values to override default
453  *                              variables. Default false.
454  * @param string     $time      Optional. Time formatted in 'yyyy/mm'. Default null.
455  * @return array On success, returns an associative array of file attributes. On failure, returns
456  *               $overrides['upload_error_handler'](&$file, $message ) or array( 'error'=>$message ).
457  */
458 function wp_handle_sideload( &$file, $overrides = false, $time = null ) {
459         /*
460          *  $_POST['action'] must be set and its value must equal $overrides['action']
461          *  or this:
462          */
463         $action = 'wp_handle_sideload';
464         if ( isset( $overrides['action'] ) ) {
465                 $action = $overrides['action'];
466         }
467         return _wp_handle_upload( $file, $overrides, $time, $action );
468 }
469
470
471 /**
472  * Downloads a URL to a local temporary file using the WordPress HTTP Class.
473  * Please note, That the calling function must unlink() the file.
474  *
475  * @since 2.5.0
476  *
477  * @param string $url the URL of the file to download
478  * @param int $timeout The timeout for the request to download the file default 300 seconds
479  * @return mixed WP_Error on failure, string Filename on success.
480  */
481 function download_url( $url, $timeout = 300 ) {
482         //WARNING: The file is not automatically deleted, The script must unlink() the file.
483         if ( ! $url )
484                 return new WP_Error('http_no_url', __('Invalid URL Provided.'));
485
486         $tmpfname = wp_tempnam($url);
487         if ( ! $tmpfname )
488                 return new WP_Error('http_no_file', __('Could not create Temporary file.'));
489
490         $response = wp_safe_remote_get( $url, array( 'timeout' => $timeout, 'stream' => true, 'filename' => $tmpfname ) );
491
492         if ( is_wp_error( $response ) ) {
493                 unlink( $tmpfname );
494                 return $response;
495         }
496
497         if ( 200 != wp_remote_retrieve_response_code( $response ) ){
498                 unlink( $tmpfname );
499                 return new WP_Error( 'http_404', trim( wp_remote_retrieve_response_message( $response ) ) );
500         }
501
502         $content_md5 = wp_remote_retrieve_header( $response, 'content-md5' );
503         if ( $content_md5 ) {
504                 $md5_check = verify_file_md5( $tmpfname, $content_md5 );
505                 if ( is_wp_error( $md5_check ) ) {
506                         unlink( $tmpfname );
507                         return $md5_check;
508                 }
509         }
510
511         return $tmpfname;
512 }
513
514 /**
515  * Calculates and compares the MD5 of a file to its expected value.
516  *
517  * @since 3.7.0
518  *
519  * @param string $filename The filename to check the MD5 of.
520  * @param string $expected_md5 The expected MD5 of the file, either a base64 encoded raw md5, or a hex-encoded md5
521  * @return bool|object WP_Error on failure, true on success, false when the MD5 format is unknown/unexpected
522  */
523 function verify_file_md5( $filename, $expected_md5 ) {
524         if ( 32 == strlen( $expected_md5 ) )
525                 $expected_raw_md5 = pack( 'H*', $expected_md5 );
526         elseif ( 24 == strlen( $expected_md5 ) )
527                 $expected_raw_md5 = base64_decode( $expected_md5 );
528         else
529                 return false; // unknown format
530
531         $file_md5 = md5_file( $filename, true );
532
533         if ( $file_md5 === $expected_raw_md5 )
534                 return true;
535
536         return new WP_Error( 'md5_mismatch', sprintf( __( 'The checksum of the file (%1$s) does not match the expected checksum value (%2$s).' ), bin2hex( $file_md5 ), bin2hex( $expected_raw_md5 ) ) );
537 }
538
539 /**
540  * Unzips a specified ZIP file to a location on the Filesystem via the WordPress Filesystem Abstraction.
541  * Assumes that WP_Filesystem() has already been called and set up. Does not extract a root-level __MACOSX directory, if present.
542  *
543  * Attempts to increase the PHP Memory limit to 256M before uncompressing,
544  * However, The most memory required shouldn't be much larger than the Archive itself.
545  *
546  * @since 2.5.0
547  *
548  * @global WP_Filesystem_Base $wp_filesystem Subclass
549  *
550  * @param string $file Full path and filename of zip archive
551  * @param string $to Full path on the filesystem to extract archive to
552  * @return mixed WP_Error on failure, True on success
553  */
554 function unzip_file($file, $to) {
555         global $wp_filesystem;
556
557         if ( ! $wp_filesystem || !is_object($wp_filesystem) )
558                 return new WP_Error('fs_unavailable', __('Could not access filesystem.'));
559
560         // Unzip can use a lot of memory, but not this much hopefully
561         /** This filter is documented in wp-admin/admin.php */
562         @ini_set( 'memory_limit', apply_filters( 'admin_memory_limit', WP_MAX_MEMORY_LIMIT ) );
563
564         $needed_dirs = array();
565         $to = trailingslashit($to);
566
567         // Determine any parent dir's needed (of the upgrade directory)
568         if ( ! $wp_filesystem->is_dir($to) ) { //Only do parents if no children exist
569                 $path = preg_split('![/\\\]!', untrailingslashit($to));
570                 for ( $i = count($path); $i >= 0; $i-- ) {
571                         if ( empty($path[$i]) )
572                                 continue;
573
574                         $dir = implode('/', array_slice($path, 0, $i+1) );
575                         if ( preg_match('!^[a-z]:$!i', $dir) ) // Skip it if it looks like a Windows Drive letter.
576                                 continue;
577
578                         if ( ! $wp_filesystem->is_dir($dir) )
579                                 $needed_dirs[] = $dir;
580                         else
581                                 break; // A folder exists, therefor, we dont need the check the levels below this
582                 }
583         }
584
585         /**
586          * Filter whether to use ZipArchive to unzip archives.
587          *
588          * @since 3.0.0
589          *
590          * @param bool $ziparchive Whether to use ZipArchive. Default true.
591          */
592         if ( class_exists( 'ZipArchive', false ) && apply_filters( 'unzip_file_use_ziparchive', true ) ) {
593                 $result = _unzip_file_ziparchive($file, $to, $needed_dirs);
594                 if ( true === $result ) {
595                         return $result;
596                 } elseif ( is_wp_error($result) ) {
597                         if ( 'incompatible_archive' != $result->get_error_code() )
598                                 return $result;
599                 }
600         }
601         // Fall through to PclZip if ZipArchive is not available, or encountered an error opening the file.
602         return _unzip_file_pclzip($file, $to, $needed_dirs);
603 }
604
605 /**
606  * This function should not be called directly, use unzip_file instead. Attempts to unzip an archive using the ZipArchive class.
607  * Assumes that WP_Filesystem() has already been called and set up.
608  *
609  * @since 3.0.0
610  * @see unzip_file
611  * @access private
612  *
613  * @global WP_Filesystem_Base $wp_filesystem Subclass
614  *
615  * @param string $file Full path and filename of zip archive
616  * @param string $to Full path on the filesystem to extract archive to
617  * @param array $needed_dirs A partial list of required folders needed to be created.
618  * @return mixed WP_Error on failure, True on success
619  */
620 function _unzip_file_ziparchive($file, $to, $needed_dirs = array() ) {
621         global $wp_filesystem;
622
623         $z = new ZipArchive();
624
625         $zopen = $z->open( $file, ZIPARCHIVE::CHECKCONS );
626         if ( true !== $zopen )
627                 return new WP_Error( 'incompatible_archive', __( 'Incompatible Archive.' ), array( 'ziparchive_error' => $zopen ) );
628
629         $uncompressed_size = 0;
630
631         for ( $i = 0; $i < $z->numFiles; $i++ ) {
632                 if ( ! $info = $z->statIndex($i) )
633                         return new WP_Error( 'stat_failed_ziparchive', __( 'Could not retrieve file from archive.' ) );
634
635                 if ( '__MACOSX/' === substr($info['name'], 0, 9) ) // Skip the OS X-created __MACOSX directory
636                         continue;
637
638                 $uncompressed_size += $info['size'];
639
640                 if ( '/' == substr($info['name'], -1) ) // directory
641                         $needed_dirs[] = $to . untrailingslashit($info['name']);
642                 else
643                         $needed_dirs[] = $to . untrailingslashit(dirname($info['name']));
644         }
645
646         /*
647          * disk_free_space() could return false. Assume that any falsey value is an error.
648          * A disk that has zero free bytes has bigger problems.
649          * Require we have enough space to unzip the file and copy its contents, with a 10% buffer.
650          */
651         if ( defined( 'DOING_CRON' ) && DOING_CRON ) {
652                 $available_space = @disk_free_space( WP_CONTENT_DIR );
653                 if ( $available_space && ( $uncompressed_size * 2.1 ) > $available_space )
654                         return new WP_Error( 'disk_full_unzip_file', __( 'Could not copy files. You may have run out of disk space.' ), compact( 'uncompressed_size', 'available_space' ) );
655         }
656
657         $needed_dirs = array_unique($needed_dirs);
658         foreach ( $needed_dirs as $dir ) {
659                 // Check the parent folders of the folders all exist within the creation array.
660                 if ( untrailingslashit($to) == $dir ) // Skip over the working directory, We know this exists (or will exist)
661                         continue;
662                 if ( strpos($dir, $to) === false ) // If the directory is not within the working directory, Skip it
663                         continue;
664
665                 $parent_folder = dirname($dir);
666                 while ( !empty($parent_folder) && untrailingslashit($to) != $parent_folder && !in_array($parent_folder, $needed_dirs) ) {
667                         $needed_dirs[] = $parent_folder;
668                         $parent_folder = dirname($parent_folder);
669                 }
670         }
671         asort($needed_dirs);
672
673         // Create those directories if need be:
674         foreach ( $needed_dirs as $_dir ) {
675                 // Only check to see if the Dir exists upon creation failure. Less I/O this way.
676                 if ( ! $wp_filesystem->mkdir( $_dir, FS_CHMOD_DIR ) && ! $wp_filesystem->is_dir( $_dir ) ) {
677                         return new WP_Error( 'mkdir_failed_ziparchive', __( 'Could not create directory.' ), substr( $_dir, strlen( $to ) ) );
678                 }
679         }
680         unset($needed_dirs);
681
682         for ( $i = 0; $i < $z->numFiles; $i++ ) {
683                 if ( ! $info = $z->statIndex($i) )
684                         return new WP_Error( 'stat_failed_ziparchive', __( 'Could not retrieve file from archive.' ) );
685
686                 if ( '/' == substr($info['name'], -1) ) // directory
687                         continue;
688
689                 if ( '__MACOSX/' === substr($info['name'], 0, 9) ) // Don't extract the OS X-created __MACOSX directory files
690                         continue;
691
692                 $contents = $z->getFromIndex($i);
693                 if ( false === $contents )
694                         return new WP_Error( 'extract_failed_ziparchive', __( 'Could not extract file from archive.' ), $info['name'] );
695
696                 if ( ! $wp_filesystem->put_contents( $to . $info['name'], $contents, FS_CHMOD_FILE) )
697                         return new WP_Error( 'copy_failed_ziparchive', __( 'Could not copy file.' ), $info['name'] );
698         }
699
700         $z->close();
701
702         return true;
703 }
704
705 /**
706  * This function should not be called directly, use unzip_file instead. Attempts to unzip an archive using the PclZip library.
707  * Assumes that WP_Filesystem() has already been called and set up.
708  *
709  * @since 3.0.0
710  * @see unzip_file
711  * @access private
712  *
713  * @global WP_Filesystem_Base $wp_filesystem Subclass
714  *
715  * @param string $file Full path and filename of zip archive
716  * @param string $to Full path on the filesystem to extract archive to
717  * @param array $needed_dirs A partial list of required folders needed to be created.
718  * @return mixed WP_Error on failure, True on success
719  */
720 function _unzip_file_pclzip($file, $to, $needed_dirs = array()) {
721         global $wp_filesystem;
722
723         mbstring_binary_safe_encoding();
724
725         require_once(ABSPATH . 'wp-admin/includes/class-pclzip.php');
726
727         $archive = new PclZip($file);
728
729         $archive_files = $archive->extract(PCLZIP_OPT_EXTRACT_AS_STRING);
730
731         reset_mbstring_encoding();
732
733         // Is the archive valid?
734         if ( !is_array($archive_files) )
735                 return new WP_Error('incompatible_archive', __('Incompatible Archive.'), $archive->errorInfo(true));
736
737         if ( 0 == count($archive_files) )
738                 return new WP_Error( 'empty_archive_pclzip', __( 'Empty archive.' ) );
739
740         $uncompressed_size = 0;
741
742         // Determine any children directories needed (From within the archive)
743         foreach ( $archive_files as $file ) {
744                 if ( '__MACOSX/' === substr($file['filename'], 0, 9) ) // Skip the OS X-created __MACOSX directory
745                         continue;
746
747                 $uncompressed_size += $file['size'];
748
749                 $needed_dirs[] = $to . untrailingslashit( $file['folder'] ? $file['filename'] : dirname($file['filename']) );
750         }
751
752         /*
753          * disk_free_space() could return false. Assume that any falsey value is an error.
754          * A disk that has zero free bytes has bigger problems.
755          * Require we have enough space to unzip the file and copy its contents, with a 10% buffer.
756          */
757         if ( defined( 'DOING_CRON' ) && DOING_CRON ) {
758                 $available_space = @disk_free_space( WP_CONTENT_DIR );
759                 if ( $available_space && ( $uncompressed_size * 2.1 ) > $available_space )
760                         return new WP_Error( 'disk_full_unzip_file', __( 'Could not copy files. You may have run out of disk space.' ), compact( 'uncompressed_size', 'available_space' ) );
761         }
762
763         $needed_dirs = array_unique($needed_dirs);
764         foreach ( $needed_dirs as $dir ) {
765                 // Check the parent folders of the folders all exist within the creation array.
766                 if ( untrailingslashit($to) == $dir ) // Skip over the working directory, We know this exists (or will exist)
767                         continue;
768                 if ( strpos($dir, $to) === false ) // If the directory is not within the working directory, Skip it
769                         continue;
770
771                 $parent_folder = dirname($dir);
772                 while ( !empty($parent_folder) && untrailingslashit($to) != $parent_folder && !in_array($parent_folder, $needed_dirs) ) {
773                         $needed_dirs[] = $parent_folder;
774                         $parent_folder = dirname($parent_folder);
775                 }
776         }
777         asort($needed_dirs);
778
779         // Create those directories if need be:
780         foreach ( $needed_dirs as $_dir ) {
781                 // Only check to see if the dir exists upon creation failure. Less I/O this way.
782                 if ( ! $wp_filesystem->mkdir( $_dir, FS_CHMOD_DIR ) && ! $wp_filesystem->is_dir( $_dir ) )
783                         return new WP_Error( 'mkdir_failed_pclzip', __( 'Could not create directory.' ), substr( $_dir, strlen( $to ) ) );
784         }
785         unset($needed_dirs);
786
787         // Extract the files from the zip
788         foreach ( $archive_files as $file ) {
789                 if ( $file['folder'] )
790                         continue;
791
792                 if ( '__MACOSX/' === substr($file['filename'], 0, 9) ) // Don't extract the OS X-created __MACOSX directory files
793                         continue;
794
795                 if ( ! $wp_filesystem->put_contents( $to . $file['filename'], $file['content'], FS_CHMOD_FILE) )
796                         return new WP_Error( 'copy_failed_pclzip', __( 'Could not copy file.' ), $file['filename'] );
797         }
798         return true;
799 }
800
801 /**
802  * Copies a directory from one location to another via the WordPress Filesystem Abstraction.
803  * Assumes that WP_Filesystem() has already been called and setup.
804  *
805  * @since 2.5.0
806  *
807  * @global WP_Filesystem_Base $wp_filesystem Subclass
808  *
809  * @param string $from source directory
810  * @param string $to destination directory
811  * @param array $skip_list a list of files/folders to skip copying
812  * @return mixed WP_Error on failure, True on success.
813  */
814 function copy_dir($from, $to, $skip_list = array() ) {
815         global $wp_filesystem;
816
817         $dirlist = $wp_filesystem->dirlist($from);
818
819         $from = trailingslashit($from);
820         $to = trailingslashit($to);
821
822         foreach ( (array) $dirlist as $filename => $fileinfo ) {
823                 if ( in_array( $filename, $skip_list ) )
824                         continue;
825
826                 if ( 'f' == $fileinfo['type'] ) {
827                         if ( ! $wp_filesystem->copy($from . $filename, $to . $filename, true, FS_CHMOD_FILE) ) {
828                                 // If copy failed, chmod file to 0644 and try again.
829                                 $wp_filesystem->chmod( $to . $filename, FS_CHMOD_FILE );
830                                 if ( ! $wp_filesystem->copy($from . $filename, $to . $filename, true, FS_CHMOD_FILE) )
831                                         return new WP_Error( 'copy_failed_copy_dir', __( 'Could not copy file.' ), $to . $filename );
832                         }
833                 } elseif ( 'd' == $fileinfo['type'] ) {
834                         if ( !$wp_filesystem->is_dir($to . $filename) ) {
835                                 if ( !$wp_filesystem->mkdir($to . $filename, FS_CHMOD_DIR) )
836                                         return new WP_Error( 'mkdir_failed_copy_dir', __( 'Could not create directory.' ), $to . $filename );
837                         }
838
839                         // generate the $sub_skip_list for the subdirectory as a sub-set of the existing $skip_list
840                         $sub_skip_list = array();
841                         foreach ( $skip_list as $skip_item ) {
842                                 if ( 0 === strpos( $skip_item, $filename . '/' ) )
843                                         $sub_skip_list[] = preg_replace( '!^' . preg_quote( $filename, '!' ) . '/!i', '', $skip_item );
844                         }
845
846                         $result = copy_dir($from . $filename, $to . $filename, $sub_skip_list);
847                         if ( is_wp_error($result) )
848                                 return $result;
849                 }
850         }
851         return true;
852 }
853
854 /**
855  * Initialises and connects the WordPress Filesystem Abstraction classes.
856  * This function will include the chosen transport and attempt connecting.
857  *
858  * Plugins may add extra transports, And force WordPress to use them by returning
859  * the filename via the {@see 'filesystem_method_file'} filter.
860  *
861  * @since 2.5.0
862  *
863  * @global WP_Filesystem_Base $wp_filesystem Subclass
864  *
865  * @param array|false  $args                         Optional. Connection args, These are passed directly to
866  *                                                   the `WP_Filesystem_*()` classes. Default false.
867  * @param string|false $context                      Optional. Context for get_filesystem_method(). Default false.
868  * @param bool         $allow_relaxed_file_ownership Optional. Whether to allow Group/World writable. Default false.
869  * @return null|bool false on failure, true on success.
870  */
871 function WP_Filesystem( $args = false, $context = false, $allow_relaxed_file_ownership = false ) {
872         global $wp_filesystem;
873
874         require_once(ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php');
875
876         $method = get_filesystem_method( $args, $context, $allow_relaxed_file_ownership );
877
878         if ( ! $method )
879                 return false;
880
881         if ( ! class_exists( "WP_Filesystem_$method" ) ) {
882
883                 /**
884                  * Filter the path for a specific filesystem method class file.
885                  *
886                  * @since 2.6.0
887                  *
888                  * @see get_filesystem_method()
889                  *
890                  * @param string $path   Path to the specific filesystem method class file.
891                  * @param string $method The filesystem method to use.
892                  */
893                 $abstraction_file = apply_filters( 'filesystem_method_file', ABSPATH . 'wp-admin/includes/class-wp-filesystem-' . $method . '.php', $method );
894
895                 if ( ! file_exists($abstraction_file) )
896                         return;
897
898                 require_once($abstraction_file);
899         }
900         $method = "WP_Filesystem_$method";
901
902         $wp_filesystem = new $method($args);
903
904         //Define the timeouts for the connections. Only available after the construct is called to allow for per-transport overriding of the default.
905         if ( ! defined('FS_CONNECT_TIMEOUT') )
906                 define('FS_CONNECT_TIMEOUT', 30);
907         if ( ! defined('FS_TIMEOUT') )
908                 define('FS_TIMEOUT', 30);
909
910         if ( is_wp_error($wp_filesystem->errors) && $wp_filesystem->errors->get_error_code() )
911                 return false;
912
913         if ( !$wp_filesystem->connect() )
914                 return false; //There was an error connecting to the server.
915
916         // Set the permission constants if not already set.
917         if ( ! defined('FS_CHMOD_DIR') )
918                 define('FS_CHMOD_DIR', ( fileperms( ABSPATH ) & 0777 | 0755 ) );
919         if ( ! defined('FS_CHMOD_FILE') )
920                 define('FS_CHMOD_FILE', ( fileperms( ABSPATH . 'index.php' ) & 0777 | 0644 ) );
921
922         return true;
923 }
924
925 /**
926  * Determines which method to use for reading, writing, modifying, or deleting
927  * files on the filesystem.
928  *
929  * The priority of the transports are: Direct, SSH2, FTP PHP Extension, FTP Sockets
930  * (Via Sockets class, or `fsockopen()`). Valid values for these are: 'direct', 'ssh2',
931  * 'ftpext' or 'ftpsockets'.
932  *
933  * The return value can be overridden by defining the `FS_METHOD` constant in `wp-config.php`,
934  * or filtering via {@see 'filesystem_method'}.
935  *
936  * @link https://codex.wordpress.org/Editing_wp-config.php#WordPress_Upgrade_Constants
937  *
938  * Plugins may define a custom transport handler, See WP_Filesystem().
939  *
940  * @since 2.5.0
941  *
942  * @global callable $_wp_filesystem_direct_method
943  *
944  * @param array  $args                         Optional. Connection details. Default empty array.
945  * @param string $context                      Optional. Full path to the directory that is tested
946  *                                             for being writable. Default false.
947  * @param bool   $allow_relaxed_file_ownership Optional. Whether to allow Group/World writable.
948  *                                             Default false.
949  * @return string The transport to use, see description for valid return values.
950  */
951 function get_filesystem_method( $args = array(), $context = false, $allow_relaxed_file_ownership = false ) {
952         $method = defined('FS_METHOD') ? FS_METHOD : false; // Please ensure that this is either 'direct', 'ssh2', 'ftpext' or 'ftpsockets'
953
954         if ( ! $context ) {
955                 $context = WP_CONTENT_DIR;
956         }
957
958         // If the directory doesn't exist (wp-content/languages) then use the parent directory as we'll create it.
959         if ( WP_LANG_DIR == $context && ! is_dir( $context ) ) {
960                 $context = dirname( $context );
961         }
962
963         $context = trailingslashit( $context );
964
965         if ( ! $method ) {
966
967                 $temp_file_name = $context . 'temp-write-test-' . time();
968                 $temp_handle = @fopen($temp_file_name, 'w');
969                 if ( $temp_handle ) {
970
971                         // Attempt to determine the file owner of the WordPress files, and that of newly created files
972                         $wp_file_owner = $temp_file_owner = false;
973                         if ( function_exists('fileowner') ) {
974                                 $wp_file_owner = @fileowner( __FILE__ );
975                                 $temp_file_owner = @fileowner( $temp_file_name );
976                         }
977
978                         if ( $wp_file_owner !== false && $wp_file_owner === $temp_file_owner ) {
979                                 // WordPress is creating files as the same owner as the WordPress files,
980                                 // this means it's safe to modify & create new files via PHP.
981                                 $method = 'direct';
982                                 $GLOBALS['_wp_filesystem_direct_method'] = 'file_owner';
983                         } elseif ( $allow_relaxed_file_ownership ) {
984                                 // The $context directory is writable, and $allow_relaxed_file_ownership is set, this means we can modify files
985                                 // safely in this directory. This mode doesn't create new files, only alter existing ones.
986                                 $method = 'direct';
987                                 $GLOBALS['_wp_filesystem_direct_method'] = 'relaxed_ownership';
988                         }
989
990                         @fclose($temp_handle);
991                         @unlink($temp_file_name);
992                 }
993         }
994
995         if ( ! $method && isset($args['connection_type']) && 'ssh' == $args['connection_type'] && extension_loaded('ssh2') && function_exists('stream_get_contents') ) $method = 'ssh2';
996         if ( ! $method && extension_loaded('ftp') ) $method = 'ftpext';
997         if ( ! $method && ( extension_loaded('sockets') || function_exists('fsockopen') ) ) $method = 'ftpsockets'; //Sockets: Socket extension; PHP Mode: FSockopen / fwrite / fread
998
999         /**
1000          * Filter the filesystem method to use.
1001          *
1002          * @since 2.6.0
1003          *
1004          * @param string $method  Filesystem method to return.
1005          * @param array  $args    An array of connection details for the method.
1006          * @param string $context Full path to the directory that is tested for being writable.
1007          * @param bool   $allow_relaxed_file_ownership Whether to allow Group/World writable.
1008          */
1009         return apply_filters( 'filesystem_method', $method, $args, $context, $allow_relaxed_file_ownership );
1010 }
1011
1012 /**
1013  * Displays a form to the user to request for their FTP/SSH details in order
1014  * to connect to the filesystem.
1015  *
1016  * All chosen/entered details are saved, Excluding the Password.
1017  *
1018  * Hostnames may be in the form of hostname:portnumber (eg: wordpress.org:2467)
1019  * to specify an alternate FTP/SSH port.
1020  *
1021  * Plugins may override this form by returning true|false via the
1022  * {@see 'request_filesystem_credentials'} filter.
1023  *
1024  * @since 2.5.
1025  *
1026  * @global string $pagenow
1027  *
1028  * @param string $form_post                    The URL to post the form to.
1029  * @param string $type                         Optional. Chosen type of filesystem. Default empty.
1030  * @param bool   $error                        Optional. Whether the current request has failed to connect.
1031  *                                             Default false.
1032  * @param string $context                      Optional. Full path to the directory that is tested
1033  *                                             for being writable. Default false.
1034  * @param array  $extra_fields                 Optional. Extra POST fields which should be checked for
1035  *                                             to be included in the post. Default null.
1036  * @param bool   $allow_relaxed_file_ownership Optional. Whether to allow Group/World writable.
1037  *                                             Default false.
1038  *
1039  * @return bool False on failure, true on success.
1040  */
1041 function request_filesystem_credentials( $form_post, $type = '', $error = false, $context = false, $extra_fields = null, $allow_relaxed_file_ownership = false ) {
1042         global $pagenow;
1043
1044         /**
1045          * Filter the filesystem credentials form output.
1046          *
1047          * Returning anything other than an empty string will effectively short-circuit
1048          * output of the filesystem credentials form, returning that value instead.
1049          *
1050          * @since 2.5.0
1051          *
1052          * @param mixed  $output                       Form output to return instead. Default empty.
1053          * @param string $form_post                    The URL to post the form to.
1054          * @param string $type                         Chosen type of filesystem.
1055          * @param bool   $error                        Whether the current request has failed to connect.
1056          *                                             Default false.
1057          * @param string $context                      Full path to the directory that is tested for
1058          *                                             being writable.
1059          * @param bool   $allow_relaxed_file_ownership Whether to allow Group/World writable.
1060          *                                             Default false.
1061          * @param array  $extra_fields                 Extra POST fields.
1062          */
1063         $req_cred = apply_filters( 'request_filesystem_credentials', '', $form_post, $type, $error, $context, $extra_fields, $allow_relaxed_file_ownership );
1064         if ( '' !== $req_cred )
1065                 return $req_cred;
1066
1067         if ( empty($type) ) {
1068                 $type = get_filesystem_method( array(), $context, $allow_relaxed_file_ownership );
1069         }
1070
1071         if ( 'direct' == $type )
1072                 return true;
1073
1074         if ( is_null( $extra_fields ) )
1075                 $extra_fields = array( 'version', 'locale' );
1076
1077         $credentials = get_option('ftp_credentials', array( 'hostname' => '', 'username' => ''));
1078
1079         // If defined, set it to that, Else, If POST'd, set it to that, If not, Set it to whatever it previously was(saved details in option)
1080         $credentials['hostname'] = defined('FTP_HOST') ? FTP_HOST : (!empty($_POST['hostname']) ? wp_unslash( $_POST['hostname'] ) : $credentials['hostname']);
1081         $credentials['username'] = defined('FTP_USER') ? FTP_USER : (!empty($_POST['username']) ? wp_unslash( $_POST['username'] ) : $credentials['username']);
1082         $credentials['password'] = defined('FTP_PASS') ? FTP_PASS : (!empty($_POST['password']) ? wp_unslash( $_POST['password'] ) : '');
1083
1084         // Check to see if we are setting the public/private keys for ssh
1085         $credentials['public_key'] = defined('FTP_PUBKEY') ? FTP_PUBKEY : (!empty($_POST['public_key']) ? wp_unslash( $_POST['public_key'] ) : '');
1086         $credentials['private_key'] = defined('FTP_PRIKEY') ? FTP_PRIKEY : (!empty($_POST['private_key']) ? wp_unslash( $_POST['private_key'] ) : '');
1087
1088         // Sanitize the hostname, Some people might pass in odd-data:
1089         $credentials['hostname'] = preg_replace('|\w+://|', '', $credentials['hostname']); //Strip any schemes off
1090
1091         if ( strpos($credentials['hostname'], ':') ) {
1092                 list( $credentials['hostname'], $credentials['port'] ) = explode(':', $credentials['hostname'], 2);
1093                 if ( ! is_numeric($credentials['port']) )
1094                         unset($credentials['port']);
1095         } else {
1096                 unset($credentials['port']);
1097         }
1098
1099         if ( ( defined( 'FTP_SSH' ) && FTP_SSH ) || ( defined( 'FS_METHOD' ) && 'ssh2' == FS_METHOD ) ) {
1100                 $credentials['connection_type'] = 'ssh';
1101         } elseif ( ( defined( 'FTP_SSL' ) && FTP_SSL ) && 'ftpext' == $type ) { //Only the FTP Extension understands SSL
1102                 $credentials['connection_type'] = 'ftps';
1103         } elseif ( ! empty( $_POST['connection_type'] ) ) {
1104                 $credentials['connection_type'] = wp_unslash( $_POST['connection_type'] );
1105         } elseif ( ! isset( $credentials['connection_type'] ) ) { //All else fails (And it's not defaulted to something else saved), Default to FTP
1106                 $credentials['connection_type'] = 'ftp';
1107         }
1108         if ( ! $error &&
1109                         (
1110                                 ( !empty($credentials['password']) && !empty($credentials['username']) && !empty($credentials['hostname']) ) ||
1111                                 ( 'ssh' == $credentials['connection_type'] && !empty($credentials['public_key']) && !empty($credentials['private_key']) )
1112                         ) ) {
1113                 $stored_credentials = $credentials;
1114                 if ( !empty($stored_credentials['port']) ) //save port as part of hostname to simplify above code.
1115                         $stored_credentials['hostname'] .= ':' . $stored_credentials['port'];
1116
1117                 unset($stored_credentials['password'], $stored_credentials['port'], $stored_credentials['private_key'], $stored_credentials['public_key']);
1118                 if ( ! wp_installing() ) {
1119                         update_option( 'ftp_credentials', $stored_credentials );
1120                 }
1121                 return $credentials;
1122         }
1123         $hostname = isset( $credentials['hostname'] ) ? $credentials['hostname'] : '';
1124         $username = isset( $credentials['username'] ) ? $credentials['username'] : '';
1125         $public_key = isset( $credentials['public_key'] ) ? $credentials['public_key'] : '';
1126         $private_key = isset( $credentials['private_key'] ) ? $credentials['private_key'] : '';
1127         $port = isset( $credentials['port'] ) ? $credentials['port'] : '';
1128         $connection_type = isset( $credentials['connection_type'] ) ? $credentials['connection_type'] : '';
1129
1130         if ( $error ) {
1131                 $error_string = __('<strong>ERROR:</strong> There was an error connecting to the server, Please verify the settings are correct.');
1132                 if ( is_wp_error($error) )
1133                         $error_string = esc_html( $error->get_error_message() );
1134                 echo '<div id="message" class="error"><p>' . $error_string . '</p></div>';
1135         }
1136
1137         $types = array();
1138         if ( extension_loaded('ftp') || extension_loaded('sockets') || function_exists('fsockopen') )
1139                 $types[ 'ftp' ] = __('FTP');
1140         if ( extension_loaded('ftp') ) //Only this supports FTPS
1141                 $types[ 'ftps' ] = __('FTPS (SSL)');
1142         if ( extension_loaded('ssh2') && function_exists('stream_get_contents') )
1143                 $types[ 'ssh' ] = __('SSH2');
1144
1145         /**
1146          * Filter the connection types to output to the filesystem credentials form.
1147          *
1148          * @since 2.9.0
1149          *
1150          * @param array  $types       Types of connections.
1151          * @param array  $credentials Credentials to connect with.
1152          * @param string $type        Chosen filesystem method.
1153          * @param object $error       Error object.
1154          * @param string $context     Full path to the directory that is tested
1155          *                            for being writable.
1156          */
1157         $types = apply_filters( 'fs_ftp_connection_types', $types, $credentials, $type, $error, $context );
1158
1159 ?>
1160 <script type="text/javascript">
1161 <!--
1162 jQuery(function($){
1163         jQuery("#ssh").click(function () {
1164                 jQuery("#ssh_keys").show();
1165         });
1166         jQuery("#ftp, #ftps").click(function () {
1167                 jQuery("#ssh_keys").hide();
1168         });
1169         jQuery('#request-filesystem-credentials-form input[value=""]:first').focus();
1170 });
1171 -->
1172 </script>
1173 <form action="<?php echo esc_url( $form_post ) ?>" method="post">
1174 <div id="request-filesystem-credentials-form" class="request-filesystem-credentials-form">
1175 <?php
1176 // Print a H1 heading in the FTP credentials modal dialog, default is a H2.
1177 $heading_tag = 'h2';
1178 if ( 'plugins.php' === $pagenow || 'plugin-install.php' === $pagenow ) {
1179         $heading_tag = 'h1';
1180 }
1181 echo "<$heading_tag id='request-filesystem-credentials-title'>" . __( 'Connection Information' ) . "</$heading_tag>";
1182 ?>
1183 <p id="request-filesystem-credentials-desc"><?php
1184         $label_user = __('Username');
1185         $label_pass = __('Password');
1186         _e('To perform the requested action, WordPress needs to access your web server.');
1187         echo ' ';
1188         if ( ( isset( $types['ftp'] ) || isset( $types['ftps'] ) ) ) {
1189                 if ( isset( $types['ssh'] ) ) {
1190                         _e('Please enter your FTP or SSH credentials to proceed.');
1191                         $label_user = __('FTP/SSH Username');
1192                         $label_pass = __('FTP/SSH Password');
1193                 } else {
1194                         _e('Please enter your FTP credentials to proceed.');
1195                         $label_user = __('FTP Username');
1196                         $label_pass = __('FTP Password');
1197                 }
1198                 echo ' ';
1199         }
1200         _e('If you do not remember your credentials, you should contact your web host.');
1201 ?></p>
1202 <label for="hostname">
1203         <span class="field-title"><?php _e( 'Hostname' ) ?></span>
1204         <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 esc_attr($hostname); if ( !empty($port) ) echo ":$port"; ?>"<?php disabled( defined('FTP_HOST') ); ?> />
1205 </label>
1206 <div class="ftp-username">
1207         <label for="username">
1208                 <span class="field-title"><?php echo $label_user; ?></span>
1209                 <input name="username" type="text" id="username" value="<?php echo esc_attr($username) ?>"<?php disabled( defined('FTP_USER') ); ?> />
1210         </label>
1211 </div>
1212 <div class="ftp-password">
1213         <label for="password">
1214                 <span class="field-title"><?php echo $label_pass; ?></span>
1215                 <input name="password" type="password" id="password" value="<?php if ( defined('FTP_PASS') ) echo '*****'; ?>"<?php disabled( defined('FTP_PASS') ); ?> />
1216                 <em><?php if ( ! defined('FTP_PASS') ) _e( 'This password will not be stored on the server.' ); ?></em>
1217         </label>
1218 </div>
1219 <?php if ( isset($types['ssh']) ) : ?>
1220 <fieldset>
1221 <legend><?php _e( 'Authentication Keys' ); ?></legend>
1222 <label for="public_key">
1223         <span class="field-title"><?php _e('Public Key:') ?></span>
1224         <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') ); ?> />
1225 </label>
1226 <label for="private_key">
1227         <span class="field-title"><?php _e('Private Key:') ?></span>
1228         <input name="private_key" type="text" id="private_key" value="<?php echo esc_attr($private_key) ?>"<?php disabled( defined('FTP_PRIKEY') ); ?> />
1229 </label>
1230 </fieldset>
1231 <span 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.') ?></span>
1232 <?php endif; ?>
1233 <fieldset>
1234 <legend><?php _e( 'Connection Type' ); ?></legend>
1235 <?php
1236         $disabled = disabled( (defined('FTP_SSL') && FTP_SSL) || (defined('FTP_SSH') && FTP_SSH), true, false );
1237         foreach ( $types as $name => $text ) : ?>
1238         <label for="<?php echo esc_attr($name) ?>">
1239                 <input type="radio" name="connection_type" id="<?php echo esc_attr($name) ?>" value="<?php echo esc_attr($name) ?>"<?php checked($name, $connection_type); echo $disabled; ?> />
1240                 <?php echo $text ?>
1241         </label>
1242         <?php endforeach; ?>
1243 </fieldset>
1244 <?php
1245 foreach ( (array) $extra_fields as $field ) {
1246         if ( isset( $_POST[ $field ] ) )
1247                 echo '<input type="hidden" name="' . esc_attr( $field ) . '" value="' . esc_attr( wp_unslash( $_POST[ $field ] ) ) . '" />';
1248 }
1249 ?>
1250         <p class="request-filesystem-credentials-action-buttons">
1251                 <button class="button cancel-button" data-js-action="close" type="button"><?php _e( 'Cancel' ); ?></button>
1252                 <?php submit_button( __( 'Proceed' ), 'button', 'upgrade', false ); ?>
1253         </p>
1254 </div>
1255 </form>
1256 <?php
1257         return false;
1258 }
1259
1260 /**
1261  * Print the filesystem credentials modal when needed.
1262  *
1263  * @since 4.2.0
1264  */
1265 function wp_print_request_filesystem_credentials_modal() {
1266         $filesystem_method = get_filesystem_method();
1267         ob_start();
1268         $filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1269         ob_end_clean();
1270         $request_filesystem_credentials = ( $filesystem_method != 'direct' && ! $filesystem_credentials_are_stored );
1271         if ( ! $request_filesystem_credentials ) {
1272                 return;
1273         }
1274         ?>
1275         <div id="request-filesystem-credentials-dialog" class="notification-dialog-wrap request-filesystem-credentials-dialog">
1276                 <div class="notification-dialog-background"></div>
1277                 <div class="notification-dialog" role="dialog" aria-labelledby="request-filesystem-credentials-title" tabindex="0">
1278                         <div class="request-filesystem-credentials-dialog-content">
1279                                 <?php request_filesystem_credentials( site_url() ); ?>
1280                         </div>
1281                 </div>
1282         </div>
1283         <?php
1284 }