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