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.
8 * @subpackage Administration
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 )' ),
42 'wp-layout.css' => __( 'Stylesheet' ),
43 'wp-comments.php' => __( 'Comments Template' ),
44 'wp-comments-popup.php' => __( 'Popup Comments Template' ),
48 * Get the description for standard WordPress theme files and other various standard
53 * @uses _cleanup_header_comment
54 * @uses $wp_file_descriptions
55 * @param string $file Filesystem path or filename
56 * @return string Description of file from $wp_file_descriptions or basename of $file if description doesn't exist
58 function get_file_description( $file ) {
59 global $wp_file_descriptions;
61 if ( isset( $wp_file_descriptions[basename( $file )] ) ) {
62 return $wp_file_descriptions[basename( $file )];
64 elseif ( file_exists( $file ) && is_file( $file ) ) {
65 $template_data = implode( '', file( $file ) );
66 if ( preg_match( '|Template Name:(.*)$|mi', $template_data, $name ))
67 return sprintf( __( '%s Page Template' ), _cleanup_header_comment($name[1]) );
70 return trim( basename( $file ) );
74 * Get the absolute filesystem path to the root of the WordPress installation
79 * @return string Full filesystem path to the root of the WordPress installation
81 function get_home_path() {
82 $home = get_option( 'home' );
83 $siteurl = get_option( 'siteurl' );
84 if ( ! empty( $home ) && 0 !== strcasecmp( $home, $siteurl ) ) {
85 $wp_path_rel_to_home = str_ireplace( $home, '', $siteurl ); /* $siteurl - $home */
86 $pos = strripos( str_replace( '\\', '/', $_SERVER['SCRIPT_FILENAME'] ), trailingslashit( $wp_path_rel_to_home ) );
87 $home_path = substr( $_SERVER['SCRIPT_FILENAME'], 0, $pos );
88 $home_path = trailingslashit( $home_path );
93 return str_replace( '\\', '/', $home_path );
97 * Returns a listing of all files in the specified folder and all subdirectories up to 100 levels deep.
98 * The depth of the recursiveness can be controlled by the $levels param.
102 * @param string $folder Full path to folder
103 * @param int $levels (optional) Levels of folders to follow, Default: 100 (PHP Loop limit).
104 * @return bool|array False on failure, Else array of files
106 function list_files( $folder = '', $levels = 100 ) {
107 if ( empty($folder) )
114 if ( $dir = @opendir( $folder ) ) {
115 while (($file = readdir( $dir ) ) !== false ) {
116 if ( in_array($file, array('.', '..') ) )
118 if ( is_dir( $folder . '/' . $file ) ) {
119 $files2 = list_files( $folder . '/' . $file, $levels - 1);
121 $files = array_merge($files, $files2 );
123 $files[] = $folder . '/' . $file . '/';
125 $files[] = $folder . '/' . $file;
134 * Returns a filename of a Temporary unique file.
135 * Please note that the calling function must unlink() this itself.
137 * The filename is based off the passed parameter or defaults to the current unix timestamp,
138 * while the directory can either be passed as well, or by leaving it blank, default to a writable temporary directory.
142 * @param string $filename (optional) Filename to base the Unique file off
143 * @param string $dir (optional) Directory to store the file in
144 * @return string a writable filename
146 function wp_tempnam($filename = '', $dir = '') {
148 $dir = get_temp_dir();
149 $filename = basename($filename);
150 if ( empty($filename) )
153 $filename = preg_replace('|\..*$|', '.tmp', $filename);
154 $filename = $dir . wp_unique_filename($dir, $filename);
160 * Make sure that the file that was requested to edit, is allowed to be edited
162 * Function will die if if you are not allowed to edit the file
167 * @uses validate_file
168 * @param string $file file the users is attempting to edit
169 * @param array $allowed_files Array of allowed files to edit, $file must match an entry exactly
172 function validate_file_to_edit( $file, $allowed_files = '' ) {
173 $code = validate_file( $file, $allowed_files );
180 wp_die( __( 'Sorry, that file cannot be edited.' ) );
183 // wp_die( __('Sorry, can’t call files with their real path.' ));
186 wp_die( __( 'Sorry, that file cannot be edited.' ) );
191 * Handle PHP uploads in WordPress, sanitizing file names, checking extensions for mime type,
192 * and moving the file to the appropriate directory within the uploads directory.
196 * @uses wp_handle_upload_error
198 * @uses wp_check_filetype_and_ext
199 * @uses current_user_can
200 * @uses wp_upload_dir
201 * @uses wp_unique_filename
202 * @uses delete_transient
203 * @param array $file Reference to a single element of $_FILES. Call the function once for each uploaded file.
204 * @param array $overrides Optional. An associative array of names=>values to override default variables with extract( $overrides, EXTR_OVERWRITE ).
205 * @param string $time Optional. Time formatted in 'yyyy/mm'.
206 * @return array On success, returns an associative array of file attributes. On failure, returns $overrides['upload_error_handler'](&$file, $message ) or array( 'error'=>$message ).
208 function wp_handle_upload( &$file, $overrides = false, $time = null ) {
209 // The default error handler.
210 if ( ! function_exists( 'wp_handle_upload_error' ) ) {
211 function wp_handle_upload_error( &$file, $message ) {
212 return array( 'error'=>$message );
217 * Filter data for the current file to upload.
221 * @param array $file An array of data for a single file.
223 $file = apply_filters( 'wp_handle_upload_prefilter', $file );
225 // You may define your own function and pass the name in $overrides['upload_error_handler']
226 $upload_error_handler = 'wp_handle_upload_error';
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'] );
232 // You may define your own function and pass the name in $overrides['unique_filename_callback']
233 $unique_filename_callback = null;
235 // $_POST['action'] must be set and its value must equal $overrides['action'] or this:
236 $action = 'wp_handle_upload';
238 // Courtesy of php.net, the strings that describe the error indicated in $_FILES[{form field}]['error'].
239 $upload_error_strings = array( false,
240 __( "The uploaded file exceeds the upload_max_filesize directive in php.ini." ),
241 __( "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form." ),
242 __( "The uploaded file was only partially uploaded." ),
243 __( "No file was uploaded." ),
245 __( "Missing a temporary folder." ),
246 __( "Failed to write file to disk." ),
247 __( "File upload stopped by extension." ));
249 // All tests are on by default. Most can be turned off by $overrides[{test_name}] = false;
254 // If you override this, you must provide $ext and $type!!!!
258 // Install user overrides. Did we mention that this voids your warranty?
259 if ( is_array( $overrides ) )
260 extract( $overrides, EXTR_OVERWRITE );
262 // A correct form post will pass this test.
263 if ( $test_form && (!isset( $_POST['action'] ) || ($_POST['action'] != $action ) ) )
264 return call_user_func($upload_error_handler, $file, __( 'Invalid form submission.' ));
266 // A successful upload will pass this test. It makes no sense to override this one.
267 if ( isset( $file['error'] ) && $file['error'] > 0 ) {
268 return call_user_func( $upload_error_handler, $file, $upload_error_strings[ $file['error'] ] );
271 // A non-empty file will pass this test.
272 if ( $test_size && !($file['size'] > 0 ) ) {
273 if ( is_multisite() )
274 $error_msg = __( 'File is empty. Please upload something more substantial.' );
276 $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.' );
277 return call_user_func($upload_error_handler, $file, $error_msg);
280 // A properly uploaded file will pass this test. There should be no reason to override this one.
281 if ( $test_upload && ! @ is_uploaded_file( $file['tmp_name'] ) )
282 return call_user_func($upload_error_handler, $file, __( 'Specified file failed upload test.' ));
284 // A correct MIME type will pass this test. Override $mimes or use the upload_mimes filter.
286 $wp_filetype = wp_check_filetype_and_ext( $file['tmp_name'], $file['name'], $mimes );
288 extract( $wp_filetype );
290 // Check to see if wp_check_filetype_and_ext() determined the filename was incorrect
291 if ( $proper_filename )
292 $file['name'] = $proper_filename;
294 if ( ( !$type || !$ext ) && !current_user_can( 'unfiltered_upload' ) )
295 return call_user_func($upload_error_handler, $file, __( 'Sorry, this file type is not permitted for security reasons.' ));
298 $ext = ltrim(strrchr($file['name'], '.'), '.');
301 $type = $file['type'];
306 // A writable uploads dir will pass this test. Again, there's no point overriding this one.
307 if ( ! ( ( $uploads = wp_upload_dir($time) ) && false === $uploads['error'] ) )
308 return call_user_func($upload_error_handler, $file, $uploads['error'] );
310 $filename = wp_unique_filename( $uploads['path'], $file['name'], $unique_filename_callback );
312 // Move the file to the uploads dir
313 $new_file = $uploads['path'] . "/$filename";
314 if ( false === @ move_uploaded_file( $file['tmp_name'], $new_file ) ) {
315 if ( 0 === strpos( $uploads['basedir'], ABSPATH ) )
316 $error_path = str_replace( ABSPATH, '', $uploads['basedir'] ) . $uploads['subdir'];
318 $error_path = basename( $uploads['basedir'] ) . $uploads['subdir'];
320 return $upload_error_handler( $file, sprintf( __('The uploaded file could not be moved to %s.' ), $error_path ) );
323 // Set correct file permissions
324 $stat = stat( dirname( $new_file ));
325 $perms = $stat['mode'] & 0000666;
326 @ chmod( $new_file, $perms );
329 $url = $uploads['url'] . "/$filename";
331 if ( is_multisite() )
332 delete_transient( 'dirsize_cache' );
335 * Filter the data array for the uploaded file.
339 * @param array $upload {
340 * Array of upload data.
342 * @type string $file Filename of the newly-uploaded file.
343 * @type string $url URL of the uploaded file.
344 * @type string $type File type.
346 * @param string $context The type of upload action. Accepts 'upload' or 'sideload'.
348 return apply_filters( 'wp_handle_upload', array( 'file' => $new_file, 'url' => $url, 'type' => $type ), 'upload' );
352 * Handle sideloads, which is the process of retrieving a media item from another server instead of
353 * a traditional media upload. This process involves sanitizing the filename, checking extensions
354 * for mime type, and moving the file to the appropriate directory within the uploads directory.
358 * @uses wp_handle_upload_error
359 * @uses wp_check_filetype_and_ext
360 * @uses current_user_can
361 * @uses wp_upload_dir
362 * @uses wp_unique_filename
363 * @param array $file an array similar to that of a PHP $_FILES POST array
364 * @param array $overrides Optional. An associative array of names=>values to override default variables with extract( $overrides, EXTR_OVERWRITE ).
365 * @param string $time Optional. Time formatted in 'yyyy/mm'.
366 * @return array On success, returns an associative array of file attributes. On failure, returns $overrides['upload_error_handler'](&$file, $message ) or array( 'error'=>$message ).
368 function wp_handle_sideload( &$file, $overrides = false, $time = null ) {
369 // The default error handler.
370 if (! function_exists( 'wp_handle_upload_error' ) ) {
371 function wp_handle_upload_error( &$file, $message ) {
372 return array( 'error'=>$message );
376 // You may define your own function and pass the name in $overrides['upload_error_handler']
377 $upload_error_handler = 'wp_handle_upload_error';
379 // You may define your own function and pass the name in $overrides['unique_filename_callback']
380 $unique_filename_callback = null;
382 // $_POST['action'] must be set and its value must equal $overrides['action'] or this:
383 $action = 'wp_handle_sideload';
385 // Courtesy of php.net, the strings that describe the error indicated in $_FILES[{form field}]['error'].
386 $upload_error_strings = array( false,
387 __( "The uploaded file exceeds the <code>upload_max_filesize</code> directive in <code>php.ini</code>." ),
388 __( "The uploaded file exceeds the <em>MAX_FILE_SIZE</em> directive that was specified in the HTML form." ),
389 __( "The uploaded file was only partially uploaded." ),
390 __( "No file was uploaded." ),
392 __( "Missing a temporary folder." ),
393 __( "Failed to write file to disk." ),
394 __( "File upload stopped by extension." ));
396 // All tests are on by default. Most can be turned off by $overrides[{test_name}] = false;
400 // If you override this, you must provide $ext and $type!!!!
404 // Install user overrides. Did we mention that this voids your warranty?
405 if ( is_array( $overrides ) )
406 extract( $overrides, EXTR_OVERWRITE );
408 // A correct form post will pass this test.
409 if ( $test_form && (!isset( $_POST['action'] ) || ($_POST['action'] != $action ) ) )
410 return $upload_error_handler( $file, __( 'Invalid form submission.' ));
412 // A successful upload will pass this test. It makes no sense to override this one.
413 if ( ! empty( $file['error'] ) )
414 return $upload_error_handler( $file, $upload_error_strings[$file['error']] );
416 // A non-empty file will pass this test.
417 if ( $test_size && !(filesize($file['tmp_name']) > 0 ) )
418 return $upload_error_handler( $file, __( 'File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your php.ini.' ));
420 // A properly uploaded file will pass this test. There should be no reason to override this one.
421 if (! @ is_file( $file['tmp_name'] ) )
422 return $upload_error_handler( $file, __( 'Specified file does not exist.' ));
424 // A correct MIME type will pass this test. Override $mimes or use the upload_mimes filter.
426 $wp_filetype = wp_check_filetype_and_ext( $file['tmp_name'], $file['name'], $mimes );
428 extract( $wp_filetype );
430 // Check to see if wp_check_filetype_and_ext() determined the filename was incorrect
431 if ( $proper_filename )
432 $file['name'] = $proper_filename;
434 if ( ( !$type || !$ext ) && !current_user_can( 'unfiltered_upload' ) )
435 return $upload_error_handler( $file, __( 'Sorry, this file type is not permitted for security reasons.' ));
438 $ext = ltrim(strrchr($file['name'], '.'), '.');
441 $type = $file['type'];
444 // A writable uploads dir will pass this test. Again, there's no point overriding this one.
445 if ( ! ( ( $uploads = wp_upload_dir( $time ) ) && false === $uploads['error'] ) )
446 return $upload_error_handler( $file, $uploads['error'] );
448 $filename = wp_unique_filename( $uploads['path'], $file['name'], $unique_filename_callback );
450 // Strip the query strings.
451 $filename = str_replace('?','-', $filename);
452 $filename = str_replace('&','-', $filename);
454 // Move the file to the uploads dir
455 $new_file = $uploads['path'] . "/$filename";
456 if ( false === @ rename( $file['tmp_name'], $new_file ) ) {
457 if ( 0 === strpos( $uploads['basedir'], ABSPATH ) )
458 $error_path = str_replace( ABSPATH, '', $uploads['basedir'] ) . $uploads['subdir'];
460 $error_path = basename( $uploads['basedir'] ) . $uploads['subdir'];
461 return $upload_error_handler( $file, sprintf( __('The uploaded file could not be moved to %s.' ), $error_path ) );
464 // Set correct file permissions
465 $stat = stat( dirname( $new_file ));
466 $perms = $stat['mode'] & 0000666;
467 @ chmod( $new_file, $perms );
470 $url = $uploads['url'] . "/$filename";
472 /** This filter is documented in wp-admin/includes/file.php */
473 $return = apply_filters( 'wp_handle_upload', array( 'file' => $new_file, 'url' => $url, 'type' => $type ), 'sideload' );
479 * Downloads a url to a local temporary file using the WordPress HTTP Class.
480 * Please note, That the calling function must unlink() the file.
484 * @param string $url the URL of the file to download
485 * @param int $timeout The timeout for the request to download the file default 300 seconds
486 * @return mixed WP_Error on failure, string Filename on success.
488 function download_url( $url, $timeout = 300 ) {
489 //WARNING: The file is not automatically deleted, The script must unlink() the file.
491 return new WP_Error('http_no_url', __('Invalid URL Provided.'));
493 $tmpfname = wp_tempnam($url);
495 return new WP_Error('http_no_file', __('Could not create Temporary file.'));
497 $response = wp_safe_remote_get( $url, array( 'timeout' => $timeout, 'stream' => true, 'filename' => $tmpfname ) );
499 if ( is_wp_error( $response ) ) {
504 if ( 200 != wp_remote_retrieve_response_code( $response ) ){
506 return new WP_Error( 'http_404', trim( wp_remote_retrieve_response_message( $response ) ) );
509 $content_md5 = wp_remote_retrieve_header( $response, 'content-md5' );
510 if ( $content_md5 ) {
511 $md5_check = verify_file_md5( $tmpfname, $content_md5 );
512 if ( is_wp_error( $md5_check ) ) {
522 * Calculates and compares the MD5 of a file to its expected value.
526 * @param string $filename The filename to check the MD5 of.
527 * @param string $expected_md5 The expected MD5 of the file, either a base64 encoded raw md5, or a hex-encoded md5
528 * @return bool|object WP_Error on failure, true on success, false when the MD5 format is unknown/unexpected
530 function verify_file_md5( $filename, $expected_md5 ) {
531 if ( 32 == strlen( $expected_md5 ) )
532 $expected_raw_md5 = pack( 'H*', $expected_md5 );
533 elseif ( 24 == strlen( $expected_md5 ) )
534 $expected_raw_md5 = base64_decode( $expected_md5 );
536 return false; // unknown format
538 $file_md5 = md5_file( $filename, true );
540 if ( $file_md5 === $expected_raw_md5 )
543 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 ) ) );
547 * Unzips a specified ZIP file to a location on the Filesystem via the WordPress Filesystem Abstraction.
548 * Assumes that WP_Filesystem() has already been called and set up. Does not extract a root-level __MACOSX directory, if present.
550 * Attempts to increase the PHP Memory limit to 256M before uncompressing,
551 * However, The most memory required shouldn't be much larger than the Archive itself.
555 * @param string $file Full path and filename of zip archive
556 * @param string $to Full path on the filesystem to extract archive to
557 * @return mixed WP_Error on failure, True on success
559 function unzip_file($file, $to) {
560 global $wp_filesystem;
562 if ( ! $wp_filesystem || !is_object($wp_filesystem) )
563 return new WP_Error('fs_unavailable', __('Could not access filesystem.'));
565 // Unzip can use a lot of memory, but not this much hopefully
566 /** This filter is documented in wp-admin/admin.php */
567 @ini_set( 'memory_limit', apply_filters( 'admin_memory_limit', WP_MAX_MEMORY_LIMIT ) );
569 $needed_dirs = array();
570 $to = trailingslashit($to);
572 // Determine any parent dir's needed (of the upgrade directory)
573 if ( ! $wp_filesystem->is_dir($to) ) { //Only do parents if no children exist
574 $path = preg_split('![/\\\]!', untrailingslashit($to));
575 for ( $i = count($path); $i >= 0; $i-- ) {
576 if ( empty($path[$i]) )
579 $dir = implode('/', array_slice($path, 0, $i+1) );
580 if ( preg_match('!^[a-z]:$!i', $dir) ) // Skip it if it looks like a Windows Drive letter.
583 if ( ! $wp_filesystem->is_dir($dir) )
584 $needed_dirs[] = $dir;
586 break; // A folder exists, therefor, we dont need the check the levels below this
591 * Filter whether to use ZipArchive to unzip archives.
595 * @param bool $ziparchive Whether to use ZipArchive. Default true.
597 if ( class_exists( 'ZipArchive' ) && apply_filters( 'unzip_file_use_ziparchive', true ) ) {
598 $result = _unzip_file_ziparchive($file, $to, $needed_dirs);
599 if ( true === $result ) {
601 } elseif ( is_wp_error($result) ) {
602 if ( 'incompatible_archive' != $result->get_error_code() )
606 // Fall through to PclZip if ZipArchive is not available, or encountered an error opening the file.
607 return _unzip_file_pclzip($file, $to, $needed_dirs);
611 * This function should not be called directly, use unzip_file instead. Attempts to unzip an archive using the ZipArchive class.
612 * Assumes that WP_Filesystem() has already been called and set up.
618 * @param string $file Full path and filename of zip archive
619 * @param string $to Full path on the filesystem to extract archive to
620 * @param array $needed_dirs A partial list of required folders needed to be created.
621 * @return mixed WP_Error on failure, True on success
623 function _unzip_file_ziparchive($file, $to, $needed_dirs = array() ) {
624 global $wp_filesystem;
626 $z = new ZipArchive();
628 $zopen = $z->open( $file, ZIPARCHIVE::CHECKCONS );
629 if ( true !== $zopen )
630 return new WP_Error( 'incompatible_archive', __( 'Incompatible Archive.' ), array( 'ziparchive_error' => $zopen ) );
632 $uncompressed_size = 0;
634 for ( $i = 0; $i < $z->numFiles; $i++ ) {
635 if ( ! $info = $z->statIndex($i) )
636 return new WP_Error( 'stat_failed_ziparchive', __( 'Could not retrieve file from archive.' ) );
638 if ( '__MACOSX/' === substr($info['name'], 0, 9) ) // Skip the OS X-created __MACOSX directory
641 $uncompressed_size += $info['size'];
643 if ( '/' == substr($info['name'], -1) ) // directory
644 $needed_dirs[] = $to . untrailingslashit($info['name']);
646 $needed_dirs[] = $to . untrailingslashit(dirname($info['name']));
650 * disk_free_space() could return false. Assume that any falsey value is an error.
651 * A disk that has zero free bytes has bigger problems.
652 * Require we have enough space to unzip the file and copy its contents, with a 10% buffer.
654 if ( defined( 'DOING_CRON' ) && DOING_CRON ) {
655 $available_space = @disk_free_space( WP_CONTENT_DIR );
656 if ( $available_space && ( $uncompressed_size * 2.1 ) > $available_space )
657 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' ) );
660 $needed_dirs = array_unique($needed_dirs);
661 foreach ( $needed_dirs as $dir ) {
662 // Check the parent folders of the folders all exist within the creation array.
663 if ( untrailingslashit($to) == $dir ) // Skip over the working directory, We know this exists (or will exist)
665 if ( strpos($dir, $to) === false ) // If the directory is not within the working directory, Skip it
668 $parent_folder = dirname($dir);
669 while ( !empty($parent_folder) && untrailingslashit($to) != $parent_folder && !in_array($parent_folder, $needed_dirs) ) {
670 $needed_dirs[] = $parent_folder;
671 $parent_folder = dirname($parent_folder);
676 // Create those directories if need be:
677 foreach ( $needed_dirs as $_dir ) {
678 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.
679 return new WP_Error( 'mkdir_failed_ziparchive', __( 'Could not create directory.' ), substr( $_dir, strlen( $to ) ) );
683 for ( $i = 0; $i < $z->numFiles; $i++ ) {
684 if ( ! $info = $z->statIndex($i) )
685 return new WP_Error( 'stat_failed_ziparchive', __( 'Could not retrieve file from archive.' ) );
687 if ( '/' == substr($info['name'], -1) ) // directory
690 if ( '__MACOSX/' === substr($info['name'], 0, 9) ) // Don't extract the OS X-created __MACOSX directory files
693 $contents = $z->getFromIndex($i);
694 if ( false === $contents )
695 return new WP_Error( 'extract_failed_ziparchive', __( 'Could not extract file from archive.' ), $info['name'] );
697 if ( ! $wp_filesystem->put_contents( $to . $info['name'], $contents, FS_CHMOD_FILE) )
698 return new WP_Error( 'copy_failed_ziparchive', __( 'Could not copy file.' ), $info['name'] );
707 * This function should not be called directly, use unzip_file instead. Attempts to unzip an archive using the PclZip library.
708 * Assumes that WP_Filesystem() has already been called and set up.
714 * @param string $file Full path and filename of zip archive
715 * @param string $to Full path on the filesystem to extract archive to
716 * @param array $needed_dirs A partial list of required folders needed to be created.
717 * @return mixed WP_Error on failure, True on success
719 function _unzip_file_pclzip($file, $to, $needed_dirs = array()) {
720 global $wp_filesystem;
722 mbstring_binary_safe_encoding();
724 require_once(ABSPATH . 'wp-admin/includes/class-pclzip.php');
726 $archive = new PclZip($file);
728 $archive_files = $archive->extract(PCLZIP_OPT_EXTRACT_AS_STRING);
730 reset_mbstring_encoding();
732 // Is the archive valid?
733 if ( !is_array($archive_files) )
734 return new WP_Error('incompatible_archive', __('Incompatible Archive.'), $archive->errorInfo(true));
736 if ( 0 == count($archive_files) )
737 return new WP_Error( 'empty_archive_pclzip', __( 'Empty archive.' ) );
739 $uncompressed_size = 0;
741 // Determine any children directories needed (From within the archive)
742 foreach ( $archive_files as $file ) {
743 if ( '__MACOSX/' === substr($file['filename'], 0, 9) ) // Skip the OS X-created __MACOSX directory
746 $uncompressed_size += $file['size'];
748 $needed_dirs[] = $to . untrailingslashit( $file['folder'] ? $file['filename'] : dirname($file['filename']) );
752 * disk_free_space() could return false. Assume that any falsey value is an error.
753 * A disk that has zero free bytes has bigger problems.
754 * Require we have enough space to unzip the file and copy its contents, with a 10% buffer.
756 if ( defined( 'DOING_CRON' ) && DOING_CRON ) {
757 $available_space = @disk_free_space( WP_CONTENT_DIR );
758 if ( $available_space && ( $uncompressed_size * 2.1 ) > $available_space )
759 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' ) );
762 $needed_dirs = array_unique($needed_dirs);
763 foreach ( $needed_dirs as $dir ) {
764 // Check the parent folders of the folders all exist within the creation array.
765 if ( untrailingslashit($to) == $dir ) // Skip over the working directory, We know this exists (or will exist)
767 if ( strpos($dir, $to) === false ) // If the directory is not within the working directory, Skip it
770 $parent_folder = dirname($dir);
771 while ( !empty($parent_folder) && untrailingslashit($to) != $parent_folder && !in_array($parent_folder, $needed_dirs) ) {
772 $needed_dirs[] = $parent_folder;
773 $parent_folder = dirname($parent_folder);
778 // Create those directories if need be:
779 foreach ( $needed_dirs as $_dir ) {
780 // Only check to see if the dir exists upon creation failure. Less I/O this way.
781 if ( ! $wp_filesystem->mkdir( $_dir, FS_CHMOD_DIR ) && ! $wp_filesystem->is_dir( $_dir ) )
782 return new WP_Error( 'mkdir_failed_pclzip', __( 'Could not create directory.' ), substr( $_dir, strlen( $to ) ) );
786 // Extract the files from the zip
787 foreach ( $archive_files as $file ) {
788 if ( $file['folder'] )
791 if ( '__MACOSX/' === substr($file['filename'], 0, 9) ) // Don't extract the OS X-created __MACOSX directory files
794 if ( ! $wp_filesystem->put_contents( $to . $file['filename'], $file['content'], FS_CHMOD_FILE) )
795 return new WP_Error( 'copy_failed_pclzip', __( 'Could not copy file.' ), $file['filename'] );
801 * Copies a directory from one location to another via the WordPress Filesystem Abstraction.
802 * Assumes that WP_Filesystem() has already been called and setup.
806 * @param string $from source directory
807 * @param string $to destination directory
808 * @param array $skip_list a list of files/folders to skip copying
809 * @return mixed WP_Error on failure, True on success.
811 function copy_dir($from, $to, $skip_list = array() ) {
812 global $wp_filesystem;
814 $dirlist = $wp_filesystem->dirlist($from);
816 $from = trailingslashit($from);
817 $to = trailingslashit($to);
819 foreach ( (array) $dirlist as $filename => $fileinfo ) {
820 if ( in_array( $filename, $skip_list ) )
823 if ( 'f' == $fileinfo['type'] ) {
824 if ( ! $wp_filesystem->copy($from . $filename, $to . $filename, true, FS_CHMOD_FILE) ) {
825 // If copy failed, chmod file to 0644 and try again.
826 $wp_filesystem->chmod( $to . $filename, FS_CHMOD_FILE );
827 if ( ! $wp_filesystem->copy($from . $filename, $to . $filename, true, FS_CHMOD_FILE) )
828 return new WP_Error( 'copy_failed_copy_dir', __( 'Could not copy file.' ), $to . $filename );
830 } elseif ( 'd' == $fileinfo['type'] ) {
831 if ( !$wp_filesystem->is_dir($to . $filename) ) {
832 if ( !$wp_filesystem->mkdir($to . $filename, FS_CHMOD_DIR) )
833 return new WP_Error( 'mkdir_failed_copy_dir', __( 'Could not create directory.' ), $to . $filename );
836 // generate the $sub_skip_list for the subdirectory as a sub-set of the existing $skip_list
837 $sub_skip_list = array();
838 foreach ( $skip_list as $skip_item ) {
839 if ( 0 === strpos( $skip_item, $filename . '/' ) )
840 $sub_skip_list[] = preg_replace( '!^' . preg_quote( $filename, '!' ) . '/!i', '', $skip_item );
843 $result = copy_dir($from . $filename, $to . $filename, $sub_skip_list);
844 if ( is_wp_error($result) )
852 * Initialises and connects the WordPress Filesystem Abstraction classes.
853 * This function will include the chosen transport and attempt connecting.
855 * Plugins may add extra transports, And force WordPress to use them by returning the filename via the 'filesystem_method_file' filter.
859 * @param array $args (optional) Connection args, These are passed directly to the WP_Filesystem_*() classes.
860 * @param string $context (optional) Context for get_filesystem_method(), See function declaration for more information.
861 * @return boolean false on failure, true on success
863 function WP_Filesystem( $args = false, $context = false ) {
864 global $wp_filesystem;
866 require_once(ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php');
868 $method = get_filesystem_method($args, $context);
873 if ( ! class_exists("WP_Filesystem_$method") ) {
876 * Filter the path for a specific filesystem method class file.
880 * @see get_filesystem_method()
882 * @param string $path Path to the specific filesystem method class file.
883 * @param string $method The filesystem method to use.
885 $abstraction_file = apply_filters( 'filesystem_method_file', ABSPATH . 'wp-admin/includes/class-wp-filesystem-' . $method . '.php', $method );
887 if ( ! file_exists($abstraction_file) )
890 require_once($abstraction_file);
892 $method = "WP_Filesystem_$method";
894 $wp_filesystem = new $method($args);
896 //Define the timeouts for the connections. Only available after the construct is called to allow for per-transport overriding of the default.
897 if ( ! defined('FS_CONNECT_TIMEOUT') )
898 define('FS_CONNECT_TIMEOUT', 30);
899 if ( ! defined('FS_TIMEOUT') )
900 define('FS_TIMEOUT', 30);
902 if ( is_wp_error($wp_filesystem->errors) && $wp_filesystem->errors->get_error_code() )
905 if ( !$wp_filesystem->connect() )
906 return false; //There was an error connecting to the server.
908 // Set the permission constants if not already set.
909 if ( ! defined('FS_CHMOD_DIR') )
910 define('FS_CHMOD_DIR', ( fileperms( ABSPATH ) & 0777 | 0755 ) );
911 if ( ! defined('FS_CHMOD_FILE') )
912 define('FS_CHMOD_FILE', ( fileperms( ABSPATH . 'index.php' ) & 0777 | 0644 ) );
918 * Determines which Filesystem Method to use.
919 * The priority of the Transports are: Direct, SSH2, FTP PHP Extension, FTP Sockets (Via Sockets class, or fsockopen())
921 * Note that the return value of this function can be overridden in 2 ways
922 * - By defining FS_METHOD in your <code>wp-config.php</code> file
923 * - By using the filesystem_method filter
924 * Valid values for these are: 'direct', 'ssh2', 'ftpext' or 'ftpsockets'
925 * Plugins may also define a custom transport handler, See the WP_Filesystem function for more information.
929 * @param array $args Connection details.
930 * @param string $context Full path to the directory that is tested for being writable.
931 * @return string The transport to use, see description for valid return values.
933 function get_filesystem_method($args = array(), $context = false) {
934 $method = defined('FS_METHOD') ? FS_METHOD : false; // Please ensure that this is either 'direct', 'ssh2', 'ftpext' or 'ftpsockets'
936 if ( ! $method && function_exists('getmyuid') && function_exists('fileowner') ){
938 $context = WP_CONTENT_DIR;
940 // If the directory doesn't exist (wp-content/languages) then use the parent directory as we'll create it.
941 if ( WP_LANG_DIR == $context && ! is_dir( $context ) )
942 $context = dirname( $context );
944 $context = trailingslashit($context);
945 $temp_file_name = $context . 'temp-write-test-' . time();
946 $temp_handle = @fopen($temp_file_name, 'w');
947 if ( $temp_handle ) {
948 if ( getmyuid() == @fileowner($temp_file_name) )
950 @fclose($temp_handle);
951 @unlink($temp_file_name);
955 if ( ! $method && isset($args['connection_type']) && 'ssh' == $args['connection_type'] && extension_loaded('ssh2') && function_exists('stream_get_contents') ) $method = 'ssh2';
956 if ( ! $method && extension_loaded('ftp') ) $method = 'ftpext';
957 if ( ! $method && ( extension_loaded('sockets') || function_exists('fsockopen') ) ) $method = 'ftpsockets'; //Sockets: Socket extension; PHP Mode: FSockopen / fwrite / fread
960 * Filter the filesystem method to use.
964 * @param string $method Filesystem method to return.
965 * @param array $args An array of connection details for the method.
967 return apply_filters( 'filesystem_method', $method, $args );
971 * Displays a form to the user to request for their FTP/SSH details in order to connect to the filesystem.
972 * All chosen/entered details are saved, Excluding the Password.
974 * Hostnames may be in the form of hostname:portnumber (eg: wordpress.org:2467) to specify an alternate FTP/SSH port.
976 * Plugins may override this form by returning true|false via the <code>request_filesystem_credentials</code> filter.
980 * @param string $form_post the URL to post the form to
981 * @param string $type the chosen Filesystem method in use
982 * @param boolean $error if the current request has failed to connect
983 * @param string $context The directory which is needed access to, The write-test will be performed on this directory by get_filesystem_method()
984 * @param string $extra_fields Extra POST fields which should be checked for to be included in the post.
985 * @return boolean False on failure. True on success.
987 function request_filesystem_credentials($form_post, $type = '', $error = false, $context = false, $extra_fields = null) {
990 * Filter the filesystem credentials form output.
992 * Returning anything other than an empty string will effectively short-circuit
993 * output of the filesystem credentials form, returning that value instead.
997 * @param mixed $output Form output to return instead. Default empty.
998 * @param string $form_post URL to POST the form to.
999 * @param string $type Chosen type of filesystem.
1000 * @param bool $error Whether the current request has failed to connect.
1002 * @param string $context Full path to the directory that is tested for
1004 * @param array $extra_fields Extra POST fields.
1006 $req_cred = apply_filters( 'request_filesystem_credentials', '', $form_post, $type, $error, $context, $extra_fields );
1007 if ( '' !== $req_cred )
1011 $type = get_filesystem_method(array(), $context);
1013 if ( 'direct' == $type )
1016 if ( is_null( $extra_fields ) )
1017 $extra_fields = array( 'version', 'locale' );
1019 $credentials = get_option('ftp_credentials', array( 'hostname' => '', 'username' => ''));
1021 // 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)
1022 $credentials['hostname'] = defined('FTP_HOST') ? FTP_HOST : (!empty($_POST['hostname']) ? wp_unslash( $_POST['hostname'] ) : $credentials['hostname']);
1023 $credentials['username'] = defined('FTP_USER') ? FTP_USER : (!empty($_POST['username']) ? wp_unslash( $_POST['username'] ) : $credentials['username']);
1024 $credentials['password'] = defined('FTP_PASS') ? FTP_PASS : (!empty($_POST['password']) ? wp_unslash( $_POST['password'] ) : '');
1026 // Check to see if we are setting the public/private keys for ssh
1027 $credentials['public_key'] = defined('FTP_PUBKEY') ? FTP_PUBKEY : (!empty($_POST['public_key']) ? wp_unslash( $_POST['public_key'] ) : '');
1028 $credentials['private_key'] = defined('FTP_PRIKEY') ? FTP_PRIKEY : (!empty($_POST['private_key']) ? wp_unslash( $_POST['private_key'] ) : '');
1030 //sanitize the hostname, Some people might pass in odd-data:
1031 $credentials['hostname'] = preg_replace('|\w+://|', '', $credentials['hostname']); //Strip any schemes off
1033 if ( strpos($credentials['hostname'], ':') ) {
1034 list( $credentials['hostname'], $credentials['port'] ) = explode(':', $credentials['hostname'], 2);
1035 if ( ! is_numeric($credentials['port']) )
1036 unset($credentials['port']);
1038 unset($credentials['port']);
1041 if ( ( defined('FTP_SSH') && FTP_SSH ) || ( defined('FS_METHOD') && 'ssh2' == FS_METHOD ) )
1042 $credentials['connection_type'] = 'ssh';
1043 else if ( (defined('FTP_SSL') && FTP_SSL) && 'ftpext' == $type ) //Only the FTP Extension understands SSL
1044 $credentials['connection_type'] = 'ftps';
1045 else if ( !empty($_POST['connection_type']) )
1046 $credentials['connection_type'] = wp_unslash( $_POST['connection_type'] );
1047 else if ( !isset($credentials['connection_type']) ) //All else fails (And it's not defaulted to something else saved), Default to FTP
1048 $credentials['connection_type'] = 'ftp';
1052 ( !empty($credentials['password']) && !empty($credentials['username']) && !empty($credentials['hostname']) ) ||
1053 ( 'ssh' == $credentials['connection_type'] && !empty($credentials['public_key']) && !empty($credentials['private_key']) )
1055 $stored_credentials = $credentials;
1056 if ( !empty($stored_credentials['port']) ) //save port as part of hostname to simplify above code.
1057 $stored_credentials['hostname'] .= ':' . $stored_credentials['port'];
1059 unset($stored_credentials['password'], $stored_credentials['port'], $stored_credentials['private_key'], $stored_credentials['public_key']);
1060 update_option('ftp_credentials', $stored_credentials);
1061 return $credentials;
1066 $connection_type = '';
1067 if ( !empty($credentials) )
1068 extract($credentials, EXTR_OVERWRITE);
1070 $error_string = __('<strong>ERROR:</strong> There was an error connecting to the server, Please verify the settings are correct.');
1071 if ( is_wp_error($error) )
1072 $error_string = esc_html( $error->get_error_message() );
1073 echo '<div id="message" class="error"><p>' . $error_string . '</p></div>';
1077 if ( extension_loaded('ftp') || extension_loaded('sockets') || function_exists('fsockopen') )
1078 $types[ 'ftp' ] = __('FTP');
1079 if ( extension_loaded('ftp') ) //Only this supports FTPS
1080 $types[ 'ftps' ] = __('FTPS (SSL)');
1081 if ( extension_loaded('ssh2') && function_exists('stream_get_contents') )
1082 $types[ 'ssh' ] = __('SSH2');
1085 * Filter the connection types to output to the filesystem credentials form.
1089 * @param array $types Types of connections.
1090 * @param array $credentials Credentials to connect with.
1091 * @param string $type Chosen filesystem method.
1092 * @param object $error Error object.
1093 * @param string $context Full path to the directory that is tested
1094 * for being writable.
1096 $types = apply_filters( 'fs_ftp_connection_types', $types, $credentials, $type, $error, $context );
1099 <script type="text/javascript">
1102 jQuery("#ssh").click(function () {
1103 jQuery("#ssh_keys").show();
1105 jQuery("#ftp, #ftps").click(function () {
1106 jQuery("#ssh_keys").hide();
1108 jQuery('form input[value=""]:first').focus();
1112 <form action="<?php echo esc_url( $form_post ) ?>" method="post">
1114 <h3><?php _e('Connection Information') ?></h3>
1116 $label_user = __('Username');
1117 $label_pass = __('Password');
1118 _e('To perform the requested action, WordPress needs to access your web server.');
1120 if ( ( isset( $types['ftp'] ) || isset( $types['ftps'] ) ) ) {
1121 if ( isset( $types['ssh'] ) ) {
1122 _e('Please enter your FTP or SSH credentials to proceed.');
1123 $label_user = __('FTP/SSH Username');
1124 $label_pass = __('FTP/SSH Password');
1126 _e('Please enter your FTP credentials to proceed.');
1127 $label_user = __('FTP Username');
1128 $label_pass = __('FTP Password');
1132 _e('If you do not remember your credentials, you should contact your web host.');
1134 <table class="form-table">
1136 <th scope="row"><label for="hostname"><?php _e('Hostname') ?></label></th>
1137 <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>
1141 <th scope="row"><label for="username"><?php echo $label_user; ?></label></th>
1142 <td><input name="username" type="text" id="username" value="<?php echo esc_attr($username) ?>"<?php disabled( defined('FTP_USER') ); ?> size="40" /></td>
1146 <th scope="row"><label for="password"><?php echo $label_pass; ?></label></th>
1147 <td><div><input name="password" type="password" id="password" value="<?php if ( defined('FTP_PASS') ) echo '*****'; ?>"<?php disabled( defined('FTP_PASS') ); ?> size="40" /></div>
1148 <div><em><?php if ( ! defined('FTP_PASS') ) _e( 'This password will not be stored on the server.' ); ?></em></div></td>
1151 <?php if ( isset($types['ssh']) ) : ?>
1152 <tr id="ssh_keys" style="<?php if ( 'ssh' != $connection_type ) echo 'display:none' ?>">
1153 <th scope="row"><?php _e('Authentication Keys') ?>
1154 <div class="key-labels textright">
1155 <label for="public_key"><?php _e('Public Key:') ?></label ><br />
1156 <label for="private_key"><?php _e('Private Key:') ?></label>
1158 <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" /><br /><input name="private_key" type="text" id="private_key" value="<?php echo esc_attr($private_key) ?>"<?php disabled( defined('FTP_PRIKEY') ); ?> size="40" />
1159 <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>
1164 <th scope="row"><?php _e('Connection Type') ?></th>
1166 <fieldset><legend class="screen-reader-text"><span><?php _e('Connection Type') ?></span></legend>
1168 $disabled = disabled( (defined('FTP_SSL') && FTP_SSL) || (defined('FTP_SSH') && FTP_SSH), true, false );
1169 foreach ( $types as $name => $text ) : ?>
1170 <label for="<?php echo esc_attr($name) ?>">
1171 <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 endforeach; ?>
1181 foreach ( (array) $extra_fields as $field ) {
1182 if ( isset( $_POST[ $field ] ) )
1183 echo '<input type="hidden" name="' . esc_attr( $field ) . '" value="' . esc_attr( wp_unslash( $_POST[ $field ] ) ) . '" />';
1185 submit_button( __( 'Proceed' ), 'button', 'upgrade' );