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