Make WordPress Core

Ticket #30663: file.php

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