]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-admin/includes/file.php
Wordpress 3.5.2-scripts
[autoinstalls/wordpress.git] / wp-admin / includes / file.php
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 _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
57  */
58 function get_file_description( $file ) {
59         global $wp_file_descriptions;
60
61         if ( isset( $wp_file_descriptions[basename( $file )] ) ) {
62                 return $wp_file_descriptions[basename( $file )];
63         }
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]) );
68         }
69
70         return trim( basename( $file ) );
71 }
72
73 /**
74  * Get the absolute filesystem path to the root of the WordPress installation
75  *
76  * @since 1.5.0
77  *
78  * @uses get_option
79  * @return string Full filesystem path to the root of the WordPress installation
80  */
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 );
89         } else {
90                 $home_path = ABSPATH;
91         }
92
93         return $home_path;
94 }
95
96 /**
97  * Get the real file system path to a file to edit within the admin
98  *
99  * If the $file is index.php or .htaccess this function will assume it is relative
100  * to the install root, otherwise it is assumed the file is relative to the wp-content
101  * directory
102  *
103  * @since 1.5.0
104  *
105  * @uses get_home_path
106  * @uses WP_CONTENT_DIR full filesystem path to the wp-content directory
107  * @param string $file filesystem path relative to the WordPress install directory or to the wp-content directory
108  * @return string full file system path to edit
109  */
110 function get_real_file_to_edit( $file ) {
111         if ('index.php' == $file || '.htaccess' == $file ) {
112                 $real_file = get_home_path() . $file;
113         } else {
114                 $real_file = WP_CONTENT_DIR . $file;
115         }
116
117         return $real_file;
118 }
119
120 /**
121  * Returns a listing of all files in the specified folder and all subdirectories up to 100 levels deep.
122  * The depth of the recursiveness can be controlled by the $levels param.
123  *
124  * @since 2.6.0
125  *
126  * @param string $folder Full path to folder
127  * @param int $levels (optional) Levels of folders to follow, Default: 100 (PHP Loop limit).
128  * @return bool|array False on failure, Else array of files
129  */
130 function list_files( $folder = '', $levels = 100 ) {
131         if ( empty($folder) )
132                 return false;
133
134         if ( ! $levels )
135                 return false;
136
137         $files = array();
138         if ( $dir = @opendir( $folder ) ) {
139                 while (($file = readdir( $dir ) ) !== false ) {
140                         if ( in_array($file, array('.', '..') ) )
141                                 continue;
142                         if ( is_dir( $folder . '/' . $file ) ) {
143                                 $files2 = list_files( $folder . '/' . $file, $levels - 1);
144                                 if ( $files2 )
145                                         $files = array_merge($files, $files2 );
146                                 else
147                                         $files[] = $folder . '/' . $file . '/';
148                         } else {
149                                 $files[] = $folder . '/' . $file;
150                         }
151                 }
152         }
153         @closedir( $dir );
154         return $files;
155 }
156
157 /**
158  * Returns a filename of a Temporary unique file.
159  * Please note that the calling function must unlink() this itself.
160  *
161  * The filename is based off the passed parameter or defaults to the current unix timestamp,
162  * while the directory can either be passed as well, or by leaving it blank, default to a writable temporary directory.
163  *
164  * @since 2.6.0
165  *
166  * @param string $filename (optional) Filename to base the Unique file off
167  * @param string $dir (optional) Directory to store the file in
168  * @return string a writable filename
169  */
170 function wp_tempnam($filename = '', $dir = '') {
171         if ( empty($dir) )
172                 $dir = get_temp_dir();
173         $filename = basename($filename);
174         if ( empty($filename) )
175                 $filename = time();
176
177         $filename = preg_replace('|\..*$|', '.tmp', $filename);
178         $filename = $dir . wp_unique_filename($dir, $filename);
179         touch($filename);
180         return $filename;
181 }
182
183 /**
184  * Make sure that the file that was requested to edit, is allowed to be edited
185  *
186  * Function will die if if you are not allowed to edit the file
187  *
188  * @since 1.5.0
189  *
190  * @uses wp_die
191  * @uses validate_file
192  * @param string $file file the users is attempting to edit
193  * @param array $allowed_files Array of allowed files to edit, $file must match an entry exactly
194  * @return null
195  */
196 function validate_file_to_edit( $file, $allowed_files = '' ) {
197         $code = validate_file( $file, $allowed_files );
198
199         if (!$code )
200                 return $file;
201
202         switch ( $code ) {
203                 case 1 :
204                         wp_die( __('Sorry, can&#8217;t edit files with &#8220;..&#8221; in the name. If you are trying to edit a file in your WordPress home directory, you can just type the name of the file in.' ));
205
206                 //case 2 :
207                 //      wp_die( __('Sorry, can&#8217;t call files with their real path.' ));
208
209                 case 3 :
210                         wp_die( __('Sorry, that file cannot be edited.' ));
211         }
212 }
213
214 /**
215  * Handle PHP uploads in WordPress, sanitizing file names, checking extensions for mime type,
216  * and moving the file to the appropriate directory within the uploads directory.
217  *
218  * @since 2.0
219  *
220  * @uses wp_handle_upload_error
221  * @uses apply_filters
222  * @uses is_multisite
223  * @uses wp_check_filetype_and_ext
224  * @uses current_user_can
225  * @uses wp_upload_dir
226  * @uses wp_unique_filename
227  * @uses delete_transient
228  * @param array $file Reference to a single element of $_FILES. Call the function once for each uploaded file.
229  * @param array $overrides Optional. An associative array of names=>values to override default variables with extract( $overrides, EXTR_OVERWRITE ).
230  * @param string $time Optional. Time formatted in 'yyyy/mm'.
231  * @return array On success, returns an associative array of file attributes. On failure, returns $overrides['upload_error_handler'](&$file, $message ) or array( 'error'=>$message ).
232  */
233 function wp_handle_upload( &$file, $overrides = false, $time = null ) {
234         // The default error handler.
235         if ( ! function_exists( 'wp_handle_upload_error' ) ) {
236                 function wp_handle_upload_error( &$file, $message ) {
237                         return array( 'error'=>$message );
238                 }
239         }
240
241         $file = apply_filters( 'wp_handle_upload_prefilter', $file );
242
243         // You may define your own function and pass the name in $overrides['upload_error_handler']
244         $upload_error_handler = 'wp_handle_upload_error';
245
246         // You may have had one or more 'wp_handle_upload_prefilter' functions error out the file. Handle that gracefully.
247         if ( isset( $file['error'] ) && !is_numeric( $file['error'] ) && $file['error'] )
248                 return $upload_error_handler( $file, $file['error'] );
249
250         // You may define your own function and pass the name in $overrides['unique_filename_callback']
251         $unique_filename_callback = null;
252
253         // $_POST['action'] must be set and its value must equal $overrides['action'] or this:
254         $action = 'wp_handle_upload';
255
256         // Courtesy of php.net, the strings that describe the error indicated in $_FILES[{form field}]['error'].
257         $upload_error_strings = array( false,
258                 __( "The uploaded file exceeds the upload_max_filesize directive in php.ini." ),
259                 __( "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form." ),
260                 __( "The uploaded file was only partially uploaded." ),
261                 __( "No file was uploaded." ),
262                 '',
263                 __( "Missing a temporary folder." ),
264                 __( "Failed to write file to disk." ),
265                 __( "File upload stopped by extension." ));
266
267         // All tests are on by default. Most can be turned off by $overrides[{test_name}] = false;
268         $test_form = true;
269         $test_size = true;
270         $test_upload = true;
271
272         // If you override this, you must provide $ext and $type!!!!
273         $test_type = true;
274         $mimes = false;
275
276         // Install user overrides. Did we mention that this voids your warranty?
277         if ( is_array( $overrides ) )
278                 extract( $overrides, EXTR_OVERWRITE );
279
280         // A correct form post will pass this test.
281         if ( $test_form && (!isset( $_POST['action'] ) || ($_POST['action'] != $action ) ) )
282                 return call_user_func($upload_error_handler, $file, __( 'Invalid form submission.' ));
283
284         // A successful upload will pass this test. It makes no sense to override this one.
285         if ( $file['error'] > 0 )
286                 return call_user_func($upload_error_handler, $file, $upload_error_strings[$file['error']] );
287
288         // A non-empty file will pass this test.
289         if ( $test_size && !($file['size'] > 0 ) ) {
290                 if ( is_multisite() )
291                         $error_msg = __( 'File is empty. Please upload something more substantial.' );
292                 else
293                         $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.' );
294                 return call_user_func($upload_error_handler, $file, $error_msg);
295         }
296
297         // A properly uploaded file will pass this test. There should be no reason to override this one.
298         if ( $test_upload && ! @ is_uploaded_file( $file['tmp_name'] ) )
299                 return call_user_func($upload_error_handler, $file, __( 'Specified file failed upload test.' ));
300
301         // A correct MIME type will pass this test. Override $mimes or use the upload_mimes filter.
302         if ( $test_type ) {
303                 $wp_filetype = wp_check_filetype_and_ext( $file['tmp_name'], $file['name'], $mimes );
304
305                 extract( $wp_filetype );
306
307                 // Check to see if wp_check_filetype_and_ext() determined the filename was incorrect
308                 if ( $proper_filename )
309                         $file['name'] = $proper_filename;
310
311                 if ( ( !$type || !$ext ) && !current_user_can( 'unfiltered_upload' ) )
312                         return call_user_func($upload_error_handler, $file, __( 'Sorry, this file type is not permitted for security reasons.' ));
313
314                 if ( !$ext )
315                         $ext = ltrim(strrchr($file['name'], '.'), '.');
316
317                 if ( !$type )
318                         $type = $file['type'];
319         } else {
320                 $type = '';
321         }
322
323         // A writable uploads dir will pass this test. Again, there's no point overriding this one.
324         if ( ! ( ( $uploads = wp_upload_dir($time) ) && false === $uploads['error'] ) )
325                 return call_user_func($upload_error_handler, $file, $uploads['error'] );
326
327         $filename = wp_unique_filename( $uploads['path'], $file['name'], $unique_filename_callback );
328
329         // Move the file to the uploads dir
330         $new_file = $uploads['path'] . "/$filename";
331         if ( false === @ move_uploaded_file( $file['tmp_name'], $new_file ) ) {
332                 if ( 0 === strpos( $uploads['basedir'], ABSPATH ) )
333                         $error_path = str_replace( ABSPATH, '', $uploads['basedir'] ) . $uploads['subdir'];
334                 else
335                         $error_path = basename( $uploads['basedir'] ) . $uploads['subdir'];
336
337                 return $upload_error_handler( $file, sprintf( __('The uploaded file could not be moved to %s.' ), $error_path ) );
338         }
339
340         // Set correct file permissions
341         $stat = stat( dirname( $new_file ));
342         $perms = $stat['mode'] & 0000666;
343         @ chmod( $new_file, $perms );
344
345         // Compute the URL
346         $url = $uploads['url'] . "/$filename";
347
348         if ( is_multisite() )
349                 delete_transient( 'dirsize_cache' );
350
351         return apply_filters( 'wp_handle_upload', array( 'file' => $new_file, 'url' => $url, 'type' => $type ), 'upload' );
352 }
353
354 /**
355  * Handle sideloads, which is the process of retrieving a media item from another server instead of
356  * a traditional media upload. This process involves sanitizing the filename, checking extensions
357  * for mime type, and moving the file to the appropriate directory within the uploads directory.
358  *
359  * @since 2.6.0
360  *
361  * @uses wp_handle_upload_error
362  * @uses apply_filters
363  * @uses wp_check_filetype_and_ext
364  * @uses current_user_can
365  * @uses wp_upload_dir
366  * @uses wp_unique_filename
367  * @param array $file an array similar to that of a PHP $_FILES POST array
368  * @param array $overrides Optional. An associative array of names=>values to override default variables with extract( $overrides, EXTR_OVERWRITE ).
369  * @param string $time Optional. Time formatted in 'yyyy/mm'.
370  * @return array On success, returns an associative array of file attributes. On failure, returns $overrides['upload_error_handler'](&$file, $message ) or array( 'error'=>$message ).
371  */
372 function wp_handle_sideload( &$file, $overrides = false, $time = null ) {
373         // The default error handler.
374         if (! function_exists( 'wp_handle_upload_error' ) ) {
375                 function wp_handle_upload_error( &$file, $message ) {
376                         return array( 'error'=>$message );
377                 }
378         }
379
380         // You may define your own function and pass the name in $overrides['upload_error_handler']
381         $upload_error_handler = 'wp_handle_upload_error';
382
383         // You may define your own function and pass the name in $overrides['unique_filename_callback']
384         $unique_filename_callback = null;
385
386         // $_POST['action'] must be set and its value must equal $overrides['action'] or this:
387         $action = 'wp_handle_sideload';
388
389         // Courtesy of php.net, the strings that describe the error indicated in $_FILES[{form field}]['error'].
390         $upload_error_strings = array( false,
391                 __( "The uploaded file exceeds the <code>upload_max_filesize</code> directive in <code>php.ini</code>." ),
392                 __( "The uploaded file exceeds the <em>MAX_FILE_SIZE</em> directive that was specified in the HTML form." ),
393                 __( "The uploaded file was only partially uploaded." ),
394                 __( "No file was uploaded." ),
395                 '',
396                 __( "Missing a temporary folder." ),
397                 __( "Failed to write file to disk." ),
398                 __( "File upload stopped by extension." ));
399
400         // All tests are on by default. Most can be turned off by $overrides[{test_name}] = false;
401         $test_form = true;
402         $test_size = true;
403
404         // If you override this, you must provide $ext and $type!!!!
405         $test_type = true;
406         $mimes = false;
407
408         // Install user overrides. Did we mention that this voids your warranty?
409         if ( is_array( $overrides ) )
410                 extract( $overrides, EXTR_OVERWRITE );
411
412         // A correct form post will pass this test.
413         if ( $test_form && (!isset( $_POST['action'] ) || ($_POST['action'] != $action ) ) )
414                 return $upload_error_handler( $file, __( 'Invalid form submission.' ));
415
416         // A successful upload will pass this test. It makes no sense to override this one.
417         if ( ! empty( $file['error'] ) )
418                 return $upload_error_handler( $file, $upload_error_strings[$file['error']] );
419
420         // A non-empty file will pass this test.
421         if ( $test_size && !(filesize($file['tmp_name']) > 0 ) )
422                 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.' ));
423
424         // A properly uploaded file will pass this test. There should be no reason to override this one.
425         if (! @ is_file( $file['tmp_name'] ) )
426                 return $upload_error_handler( $file, __( 'Specified file does not exist.' ));
427
428         // A correct MIME type will pass this test. Override $mimes or use the upload_mimes filter.
429         if ( $test_type ) {
430                 $wp_filetype = wp_check_filetype_and_ext( $file['tmp_name'], $file['name'], $mimes );
431
432                 extract( $wp_filetype );
433
434                 // Check to see if wp_check_filetype_and_ext() determined the filename was incorrect
435                 if ( $proper_filename )
436                         $file['name'] = $proper_filename;
437
438                 if ( ( !$type || !$ext ) && !current_user_can( 'unfiltered_upload' ) )
439                         return $upload_error_handler( $file, __( 'Sorry, this file type is not permitted for security reasons.' ));
440
441                 if ( !$ext )
442                         $ext = ltrim(strrchr($file['name'], '.'), '.');
443
444                 if ( !$type )
445                         $type = $file['type'];
446         }
447
448         // A writable uploads dir will pass this test. Again, there's no point overriding this one.
449         if ( ! ( ( $uploads = wp_upload_dir( $time ) ) && false === $uploads['error'] ) )
450                 return $upload_error_handler( $file, $uploads['error'] );
451
452         $filename = wp_unique_filename( $uploads['path'], $file['name'], $unique_filename_callback );
453
454         // Strip the query strings.
455         $filename = str_replace('?','-', $filename);
456         $filename = str_replace('&','-', $filename);
457
458         // Move the file to the uploads dir
459         $new_file = $uploads['path'] . "/$filename";
460         if ( false === @ rename( $file['tmp_name'], $new_file ) ) {
461                 if ( 0 === strpos( $uploads['basedir'], ABSPATH ) )
462                         $error_path = str_replace( ABSPATH, '', $uploads['basedir'] ) . $uploads['subdir'];
463                 else
464                         $error_path = basename( $uploads['basedir'] ) . $uploads['subdir'];
465                 return $upload_error_handler( $file, sprintf( __('The uploaded file could not be moved to %s.' ), $error_path ) );
466         }
467
468         // Set correct file permissions
469         $stat = stat( dirname( $new_file ));
470         $perms = $stat['mode'] & 0000666;
471         @ chmod( $new_file, $perms );
472
473         // Compute the URL
474         $url = $uploads['url'] . "/$filename";
475
476         $return = apply_filters( 'wp_handle_upload', array( 'file' => $new_file, 'url' => $url, 'type' => $type ), 'sideload' );
477
478         return $return;
479 }
480
481 /**
482  * Downloads a url to a local temporary file using the WordPress HTTP Class.
483  * Please note, That the calling function must unlink() the file.
484  *
485  * @since 2.5.0
486  *
487  * @param string $url the URL of the file to download
488  * @param int $timeout The timeout for the request to download the file default 300 seconds
489  * @return mixed WP_Error on failure, string Filename on success.
490  */
491 function download_url( $url, $timeout = 300 ) {
492         //WARNING: The file is not automatically deleted, The script must unlink() the file.
493         if ( ! $url )
494                 return new WP_Error('http_no_url', __('Invalid URL Provided.'));
495
496         $tmpfname = wp_tempnam($url);
497         if ( ! $tmpfname )
498                 return new WP_Error('http_no_file', __('Could not create Temporary file.'));
499
500         $response = wp_remote_get( $url, array( 'timeout' => $timeout, 'stream' => true, 'filename' => $tmpfname, 'reject_unsafe_urls' => true ) );
501
502         if ( is_wp_error( $response ) ) {
503                 unlink( $tmpfname );
504                 return $response;
505         }
506
507         if ( 200 != wp_remote_retrieve_response_code( $response ) ){
508                 unlink( $tmpfname );
509                 return new WP_Error( 'http_404', trim( wp_remote_retrieve_response_message( $response ) ) );
510         }
511
512         return $tmpfname;
513 }
514
515 /**
516  * Unzips a specified ZIP file to a location on the Filesystem via the WordPress Filesystem Abstraction.
517  * Assumes that WP_Filesystem() has already been called and set up. Does not extract a root-level __MACOSX directory, if present.
518  *
519  * Attempts to increase the PHP Memory limit to 256M before uncompressing,
520  * However, The most memory required shouldn't be much larger than the Archive itself.
521  *
522  * @since 2.5.0
523  *
524  * @param string $file Full path and filename of zip archive
525  * @param string $to Full path on the filesystem to extract archive to
526  * @return mixed WP_Error on failure, True on success
527  */
528 function unzip_file($file, $to) {
529         global $wp_filesystem;
530
531         if ( ! $wp_filesystem || !is_object($wp_filesystem) )
532                 return new WP_Error('fs_unavailable', __('Could not access filesystem.'));
533
534         // Unzip can use a lot of memory, but not this much hopefully
535         @ini_set( 'memory_limit', apply_filters( 'admin_memory_limit', WP_MAX_MEMORY_LIMIT ) );
536
537         $needed_dirs = array();
538         $to = trailingslashit($to);
539
540         // Determine any parent dir's needed (of the upgrade directory)
541         if ( ! $wp_filesystem->is_dir($to) ) { //Only do parents if no children exist
542                 $path = preg_split('![/\\\]!', untrailingslashit($to));
543                 for ( $i = count($path); $i >= 0; $i-- ) {
544                         if ( empty($path[$i]) )
545                                 continue;
546
547                         $dir = implode('/', array_slice($path, 0, $i+1) );
548                         if ( preg_match('!^[a-z]:$!i', $dir) ) // Skip it if it looks like a Windows Drive letter.
549                                 continue;
550
551                         if ( ! $wp_filesystem->is_dir($dir) )
552                                 $needed_dirs[] = $dir;
553                         else
554                                 break; // A folder exists, therefor, we dont need the check the levels below this
555                 }
556         }
557
558         if ( class_exists('ZipArchive') && apply_filters('unzip_file_use_ziparchive', true ) ) {
559                 $result = _unzip_file_ziparchive($file, $to, $needed_dirs);
560                 if ( true === $result ) {
561                         return $result;
562                 } elseif ( is_wp_error($result) ) {
563                         if ( 'incompatible_archive' != $result->get_error_code() )
564                                 return $result;
565                 }
566         }
567         // Fall through to PclZip if ZipArchive is not available, or encountered an error opening the file.
568         return _unzip_file_pclzip($file, $to, $needed_dirs);
569 }
570
571 /**
572  * This function should not be called directly, use unzip_file instead. Attempts to unzip an archive using the ZipArchive class.
573  * Assumes that WP_Filesystem() has already been called and set up.
574  *
575  * @since 3.0.0
576  * @see unzip_file
577  * @access private
578  *
579  * @param string $file Full path and filename of zip archive
580  * @param string $to Full path on the filesystem to extract archive to
581  * @param array $needed_dirs A partial list of required folders needed to be created.
582  * @return mixed WP_Error on failure, True on success
583  */
584 function _unzip_file_ziparchive($file, $to, $needed_dirs = array() ) {
585         global $wp_filesystem;
586
587         $z = new ZipArchive();
588
589         // PHP4-compat - php4 classes can't contain constants
590         $zopen = $z->open($file, /* ZIPARCHIVE::CHECKCONS */ 4);
591         if ( true !== $zopen )
592                 return new WP_Error('incompatible_archive', __('Incompatible Archive.'));
593
594         for ( $i = 0; $i < $z->numFiles; $i++ ) {
595                 if ( ! $info = $z->statIndex($i) )
596                         return new WP_Error('stat_failed', __('Could not retrieve file from archive.'));
597
598                 if ( '__MACOSX/' === substr($info['name'], 0, 9) ) // Skip the OS X-created __MACOSX directory
599                         continue;
600
601                 if ( '/' == substr($info['name'], -1) ) // directory
602                         $needed_dirs[] = $to . untrailingslashit($info['name']);
603                 else
604                         $needed_dirs[] = $to . untrailingslashit(dirname($info['name']));
605         }
606
607         $needed_dirs = array_unique($needed_dirs);
608         foreach ( $needed_dirs as $dir ) {
609                 // Check the parent folders of the folders all exist within the creation array.
610                 if ( untrailingslashit($to) == $dir ) // Skip over the working directory, We know this exists (or will exist)
611                         continue;
612                 if ( strpos($dir, $to) === false ) // If the directory is not within the working directory, Skip it
613                         continue;
614
615                 $parent_folder = dirname($dir);
616                 while ( !empty($parent_folder) && untrailingslashit($to) != $parent_folder && !in_array($parent_folder, $needed_dirs) ) {
617                         $needed_dirs[] = $parent_folder;
618                         $parent_folder = dirname($parent_folder);
619                 }
620         }
621         asort($needed_dirs);
622
623         // Create those directories if need be:
624         foreach ( $needed_dirs as $_dir ) {
625                 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.
626                         return new WP_Error('mkdir_failed', __('Could not create directory.'), $_dir);
627         }
628         unset($needed_dirs);
629
630         for ( $i = 0; $i < $z->numFiles; $i++ ) {
631                 if ( ! $info = $z->statIndex($i) )
632                         return new WP_Error('stat_failed', __('Could not retrieve file from archive.'));
633
634                 if ( '/' == substr($info['name'], -1) ) // directory
635                         continue;
636
637                 if ( '__MACOSX/' === substr($info['name'], 0, 9) ) // Don't extract the OS X-created __MACOSX directory files
638                         continue;
639
640                 $contents = $z->getFromIndex($i);
641                 if ( false === $contents )
642                         return new WP_Error('extract_failed', __('Could not extract file from archive.'), $info['name']);
643
644                 if ( ! $wp_filesystem->put_contents( $to . $info['name'], $contents, FS_CHMOD_FILE) )
645                         return new WP_Error('copy_failed', __('Could not copy file.'), $to . $info['name']);
646         }
647
648         $z->close();
649
650         return true;
651 }
652
653 /**
654  * This function should not be called directly, use unzip_file instead. Attempts to unzip an archive using the PclZip library.
655  * Assumes that WP_Filesystem() has already been called and set up.
656  *
657  * @since 3.0.0
658  * @see unzip_file
659  * @access private
660  *
661  * @param string $file Full path and filename of zip archive
662  * @param string $to Full path on the filesystem to extract archive to
663  * @param array $needed_dirs A partial list of required folders needed to be created.
664  * @return mixed WP_Error on failure, True on success
665  */
666 function _unzip_file_pclzip($file, $to, $needed_dirs = array()) {
667         global $wp_filesystem;
668
669         // See #15789 - PclZip uses string functions on binary data, If it's overloaded with Multibyte safe functions the results are incorrect.
670         if ( ini_get('mbstring.func_overload') && function_exists('mb_internal_encoding') ) {
671                 $previous_encoding = mb_internal_encoding();
672                 mb_internal_encoding('ISO-8859-1');
673         }
674
675         require_once(ABSPATH . 'wp-admin/includes/class-pclzip.php');
676
677         $archive = new PclZip($file);
678
679         $archive_files = $archive->extract(PCLZIP_OPT_EXTRACT_AS_STRING);
680
681         if ( isset($previous_encoding) )
682                 mb_internal_encoding($previous_encoding);
683
684         // Is the archive valid?
685         if ( !is_array($archive_files) )
686                 return new WP_Error('incompatible_archive', __('Incompatible Archive.'), $archive->errorInfo(true));
687
688         if ( 0 == count($archive_files) )
689                 return new WP_Error('empty_archive', __('Empty archive.'));
690
691         // Determine any children directories needed (From within the archive)
692         foreach ( $archive_files as $file ) {
693                 if ( '__MACOSX/' === substr($file['filename'], 0, 9) ) // Skip the OS X-created __MACOSX directory
694                         continue;
695
696                 $needed_dirs[] = $to . untrailingslashit( $file['folder'] ? $file['filename'] : dirname($file['filename']) );
697         }
698
699         $needed_dirs = array_unique($needed_dirs);
700         foreach ( $needed_dirs as $dir ) {
701                 // Check the parent folders of the folders all exist within the creation array.
702                 if ( untrailingslashit($to) == $dir ) // Skip over the working directory, We know this exists (or will exist)
703                         continue;
704                 if ( strpos($dir, $to) === false ) // If the directory is not within the working directory, Skip it
705                         continue;
706
707                 $parent_folder = dirname($dir);
708                 while ( !empty($parent_folder) && untrailingslashit($to) != $parent_folder && !in_array($parent_folder, $needed_dirs) ) {
709                         $needed_dirs[] = $parent_folder;
710                         $parent_folder = dirname($parent_folder);
711                 }
712         }
713         asort($needed_dirs);
714
715         // Create those directories if need be:
716         foreach ( $needed_dirs as $_dir ) {
717                 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.
718                         return new WP_Error('mkdir_failed', __('Could not create directory.'), $_dir);
719         }
720         unset($needed_dirs);
721
722         // Extract the files from the zip
723         foreach ( $archive_files as $file ) {
724                 if ( $file['folder'] )
725                         continue;
726
727                 if ( '__MACOSX/' === substr($file['filename'], 0, 9) ) // Don't extract the OS X-created __MACOSX directory files
728                         continue;
729
730                 if ( ! $wp_filesystem->put_contents( $to . $file['filename'], $file['content'], FS_CHMOD_FILE) )
731                         return new WP_Error('copy_failed', __('Could not copy file.'), $to . $file['filename']);
732         }
733         return true;
734 }
735
736 /**
737  * Copies a directory from one location to another via the WordPress Filesystem Abstraction.
738  * Assumes that WP_Filesystem() has already been called and setup.
739  *
740  * @since 2.5.0
741  *
742  * @param string $from source directory
743  * @param string $to destination directory
744  * @param array $skip_list a list of files/folders to skip copying
745  * @return mixed WP_Error on failure, True on success.
746  */
747 function copy_dir($from, $to, $skip_list = array() ) {
748         global $wp_filesystem;
749
750         $dirlist = $wp_filesystem->dirlist($from);
751
752         $from = trailingslashit($from);
753         $to = trailingslashit($to);
754
755         $skip_regex = '';
756         foreach ( (array)$skip_list as $key => $skip_file )
757                 $skip_regex .= preg_quote($skip_file, '!') . '|';
758
759         if ( !empty($skip_regex) )
760                 $skip_regex = '!(' . rtrim($skip_regex, '|') . ')$!i';
761
762         foreach ( (array) $dirlist as $filename => $fileinfo ) {
763                 if ( !empty($skip_regex) )
764                         if ( preg_match($skip_regex, $from . $filename) )
765                                 continue;
766
767                 if ( 'f' == $fileinfo['type'] ) {
768                         if ( ! $wp_filesystem->copy($from . $filename, $to . $filename, true, FS_CHMOD_FILE) ) {
769                                 // If copy failed, chmod file to 0644 and try again.
770                                 $wp_filesystem->chmod($to . $filename, 0644);
771                                 if ( ! $wp_filesystem->copy($from . $filename, $to . $filename, true, FS_CHMOD_FILE) )
772                                         return new WP_Error('copy_failed', __('Could not copy file.'), $to . $filename);
773                         }
774                 } elseif ( 'd' == $fileinfo['type'] ) {
775                         if ( !$wp_filesystem->is_dir($to . $filename) ) {
776                                 if ( !$wp_filesystem->mkdir($to . $filename, FS_CHMOD_DIR) )
777                                         return new WP_Error('mkdir_failed', __('Could not create directory.'), $to . $filename);
778                         }
779                         $result = copy_dir($from . $filename, $to . $filename, $skip_list);
780                         if ( is_wp_error($result) )
781                                 return $result;
782                 }
783         }
784         return true;
785 }
786
787 /**
788  * Initialises and connects the WordPress Filesystem Abstraction classes.
789  * This function will include the chosen transport and attempt connecting.
790  *
791  * Plugins may add extra transports, And force WordPress to use them by returning the filename via the 'filesystem_method_file' filter.
792  *
793  * @since 2.5.0
794  *
795  * @param array $args (optional) Connection args, These are passed directly to the WP_Filesystem_*() classes.
796  * @param string $context (optional) Context for get_filesystem_method(), See function declaration for more information.
797  * @return boolean false on failure, true on success
798  */
799 function WP_Filesystem( $args = false, $context = false ) {
800         global $wp_filesystem;
801
802         require_once(ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php');
803
804         $method = get_filesystem_method($args, $context);
805
806         if ( ! $method )
807                 return false;
808
809         if ( ! class_exists("WP_Filesystem_$method") ) {
810                 $abstraction_file = apply_filters('filesystem_method_file', ABSPATH . 'wp-admin/includes/class-wp-filesystem-' . $method . '.php', $method);
811                 if ( ! file_exists($abstraction_file) )
812                         return;
813
814                 require_once($abstraction_file);
815         }
816         $method = "WP_Filesystem_$method";
817
818         $wp_filesystem = new $method($args);
819
820         //Define the timeouts for the connections. Only available after the construct is called to allow for per-transport overriding of the default.
821         if ( ! defined('FS_CONNECT_TIMEOUT') )
822                 define('FS_CONNECT_TIMEOUT', 30);
823         if ( ! defined('FS_TIMEOUT') )
824                 define('FS_TIMEOUT', 30);
825
826         if ( is_wp_error($wp_filesystem->errors) && $wp_filesystem->errors->get_error_code() )
827                 return false;
828
829         if ( !$wp_filesystem->connect() )
830                 return false; //There was an error connecting to the server.
831
832         // Set the permission constants if not already set.
833         if ( ! defined('FS_CHMOD_DIR') )
834                 define('FS_CHMOD_DIR', 0755 );
835         if ( ! defined('FS_CHMOD_FILE') )
836                 define('FS_CHMOD_FILE', 0644 );
837
838         return true;
839 }
840
841 /**
842  * Determines which Filesystem Method to use.
843  * The priority of the Transports are: Direct, SSH2, FTP PHP Extension, FTP Sockets (Via Sockets class, or fsockopen())
844  *
845  * Note that the return value of this function can be overridden in 2 ways
846  *  - By defining FS_METHOD in your <code>wp-config.php</code> file
847  *  - By using the filesystem_method filter
848  * Valid values for these are: 'direct', 'ssh', 'ftpext' or 'ftpsockets'
849  * Plugins may also define a custom transport handler, See the WP_Filesystem function for more information.
850  *
851  * @since 2.5.0
852  *
853  * @param array $args Connection details.
854  * @param string $context Full path to the directory that is tested for being writable.
855  * @return string The transport to use, see description for valid return values.
856  */
857 function get_filesystem_method($args = array(), $context = false) {
858         $method = defined('FS_METHOD') ? FS_METHOD : false; //Please ensure that this is either 'direct', 'ssh', 'ftpext' or 'ftpsockets'
859
860         if ( ! $method && function_exists('getmyuid') && function_exists('fileowner') ){
861                 if ( !$context )
862                         $context = WP_CONTENT_DIR;
863                 $context = trailingslashit($context);
864                 $temp_file_name = $context . 'temp-write-test-' . time();
865                 $temp_handle = @fopen($temp_file_name, 'w');
866                 if ( $temp_handle ) {
867                         if ( getmyuid() == @fileowner($temp_file_name) )
868                                 $method = 'direct';
869                         @fclose($temp_handle);
870                         @unlink($temp_file_name);
871                 }
872         }
873
874         if ( ! $method && isset($args['connection_type']) && 'ssh' == $args['connection_type'] && extension_loaded('ssh2') && function_exists('stream_get_contents') ) $method = 'ssh2';
875         if ( ! $method && extension_loaded('ftp') ) $method = 'ftpext';
876         if ( ! $method && ( extension_loaded('sockets') || function_exists('fsockopen') ) ) $method = 'ftpsockets'; //Sockets: Socket extension; PHP Mode: FSockopen / fwrite / fread
877         return apply_filters('filesystem_method', $method, $args);
878 }
879
880 /**
881  * Displays a form to the user to request for their FTP/SSH details in order to connect to the filesystem.
882  * All chosen/entered details are saved, Excluding the Password.
883  *
884  * Hostnames may be in the form of hostname:portnumber (eg: wordpress.org:2467) to specify an alternate FTP/SSH port.
885  *
886  * Plugins may override this form by returning true|false via the <code>request_filesystem_credentials</code> filter.
887  *
888  * @since 2.5.0
889  *
890  * @param string $form_post the URL to post the form to
891  * @param string $type the chosen Filesystem method in use
892  * @param boolean $error if the current request has failed to connect
893  * @param string $context The directory which is needed access to, The write-test will be performed on this directory by get_filesystem_method()
894  * @param string $extra_fields Extra POST fields which should be checked for to be included in the post.
895  * @return boolean False on failure. True on success.
896  */
897 function request_filesystem_credentials($form_post, $type = '', $error = false, $context = false, $extra_fields = null) {
898         $req_cred = apply_filters( 'request_filesystem_credentials', '', $form_post, $type, $error, $context, $extra_fields );
899         if ( '' !== $req_cred )
900                 return $req_cred;
901
902         if ( empty($type) )
903                 $type = get_filesystem_method(array(), $context);
904
905         if ( 'direct' == $type )
906                 return true;
907
908         if ( is_null( $extra_fields ) )
909                 $extra_fields = array( 'version', 'locale' );
910
911         $credentials = get_option('ftp_credentials', array( 'hostname' => '', 'username' => ''));
912
913         // 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)
914         $credentials['hostname'] = defined('FTP_HOST') ? FTP_HOST : (!empty($_POST['hostname']) ? stripslashes($_POST['hostname']) : $credentials['hostname']);
915         $credentials['username'] = defined('FTP_USER') ? FTP_USER : (!empty($_POST['username']) ? stripslashes($_POST['username']) : $credentials['username']);
916         $credentials['password'] = defined('FTP_PASS') ? FTP_PASS : (!empty($_POST['password']) ? stripslashes($_POST['password']) : '');
917
918         // Check to see if we are setting the public/private keys for ssh
919         $credentials['public_key'] = defined('FTP_PUBKEY') ? FTP_PUBKEY : (!empty($_POST['public_key']) ? stripslashes($_POST['public_key']) : '');
920         $credentials['private_key'] = defined('FTP_PRIKEY') ? FTP_PRIKEY : (!empty($_POST['private_key']) ? stripslashes($_POST['private_key']) : '');
921
922         //sanitize the hostname, Some people might pass in odd-data:
923         $credentials['hostname'] = preg_replace('|\w+://|', '', $credentials['hostname']); //Strip any schemes off
924
925         if ( strpos($credentials['hostname'], ':') ) {
926                 list( $credentials['hostname'], $credentials['port'] ) = explode(':', $credentials['hostname'], 2);
927                 if ( ! is_numeric($credentials['port']) )
928                         unset($credentials['port']);
929         } else {
930                 unset($credentials['port']);
931         }
932
933         if ( (defined('FTP_SSH') && FTP_SSH) || (defined('FS_METHOD') && 'ssh' == FS_METHOD) )
934                 $credentials['connection_type'] = 'ssh';
935         else if ( (defined('FTP_SSL') && FTP_SSL) && 'ftpext' == $type ) //Only the FTP Extension understands SSL
936                 $credentials['connection_type'] = 'ftps';
937         else if ( !empty($_POST['connection_type']) )
938                 $credentials['connection_type'] = stripslashes($_POST['connection_type']);
939         else if ( !isset($credentials['connection_type']) ) //All else fails (And its not defaulted to something else saved), Default to FTP
940                 $credentials['connection_type'] = 'ftp';
941
942         if ( ! $error &&
943                         (
944                                 ( !empty($credentials['password']) && !empty($credentials['username']) && !empty($credentials['hostname']) ) ||
945                                 ( 'ssh' == $credentials['connection_type'] && !empty($credentials['public_key']) && !empty($credentials['private_key']) )
946                         ) ) {
947                 $stored_credentials = $credentials;
948                 if ( !empty($stored_credentials['port']) ) //save port as part of hostname to simplify above code.
949                         $stored_credentials['hostname'] .= ':' . $stored_credentials['port'];
950
951                 unset($stored_credentials['password'], $stored_credentials['port'], $stored_credentials['private_key'], $stored_credentials['public_key']);
952                 update_option('ftp_credentials', $stored_credentials);
953                 return $credentials;
954         }
955         $hostname = '';
956         $username = '';
957         $password = '';
958         $connection_type = '';
959         if ( !empty($credentials) )
960                 extract($credentials, EXTR_OVERWRITE);
961         if ( $error ) {
962                 $error_string = __('<strong>ERROR:</strong> There was an error connecting to the server, Please verify the settings are correct.');
963                 if ( is_wp_error($error) )
964                         $error_string = esc_html( $error->get_error_message() );
965                 echo '<div id="message" class="error"><p>' . $error_string . '</p></div>';
966         }
967
968         $types = array();
969         if ( extension_loaded('ftp') || extension_loaded('sockets') || function_exists('fsockopen') )
970                 $types[ 'ftp' ] = __('FTP');
971         if ( extension_loaded('ftp') ) //Only this supports FTPS
972                 $types[ 'ftps' ] = __('FTPS (SSL)');
973         if ( extension_loaded('ssh2') && function_exists('stream_get_contents') )
974                 $types[ 'ssh' ] = __('SSH2');
975
976         $types = apply_filters('fs_ftp_connection_types', $types, $credentials, $type, $error, $context);
977
978 ?>
979 <script type="text/javascript">
980 <!--
981 jQuery(function($){
982         jQuery("#ssh").click(function () {
983                 jQuery("#ssh_keys").show();
984         });
985         jQuery("#ftp, #ftps").click(function () {
986                 jQuery("#ssh_keys").hide();
987         });
988         jQuery('form input[value=""]:first').focus();
989 });
990 -->
991 </script>
992 <form action="<?php echo $form_post ?>" method="post">
993 <div class="wrap">
994 <?php screen_icon(); ?>
995 <h2><?php _e('Connection Information') ?></h2>
996 <p><?php
997         $label_user = __('Username');
998         $label_pass = __('Password');
999         _e('To perform the requested action, WordPress needs to access your web server.');
1000         echo ' ';
1001         if ( ( isset( $types['ftp'] ) || isset( $types['ftps'] ) ) ) {
1002                 if ( isset( $types['ssh'] ) ) {
1003                         _e('Please enter your FTP or SSH credentials to proceed.');
1004                         $label_user = __('FTP/SSH Username');
1005                         $label_pass = __('FTP/SSH Password');
1006                 } else {
1007                         _e('Please enter your FTP credentials to proceed.');
1008                         $label_user = __('FTP Username');
1009                         $label_pass = __('FTP Password');
1010                 }
1011                 echo ' ';
1012         }
1013         _e('If you do not remember your credentials, you should contact your web host.');
1014 ?></p>
1015 <table class="form-table">
1016 <tr valign="top">
1017 <th scope="row"><label for="hostname"><?php _e('Hostname') ?></label></th>
1018 <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>
1019 </tr>
1020
1021 <tr valign="top">
1022 <th scope="row"><label for="username"><?php echo $label_user; ?></label></th>
1023 <td><input name="username" type="text" id="username" value="<?php echo esc_attr($username) ?>"<?php disabled( defined('FTP_USER') ); ?> size="40" /></td>
1024 </tr>
1025
1026 <tr valign="top">
1027 <th scope="row"><label for="password"><?php echo $label_pass; ?></label></th>
1028 <td><input name="password" type="password" id="password" value="<?php if ( defined('FTP_PASS') ) echo '*****'; ?>"<?php disabled( defined('FTP_PASS') ); ?> size="40" /></td>
1029 </tr>
1030
1031 <?php if ( isset($types['ssh']) ) : ?>
1032 <tr id="ssh_keys" valign="top" style="<?php if ( 'ssh' != $connection_type ) echo 'display:none' ?>">
1033 <th scope="row"><?php _e('Authentication Keys') ?>
1034 <div class="key-labels textright">
1035 <label for="public_key"><?php _e('Public Key:') ?></label ><br />
1036 <label for="private_key"><?php _e('Private Key:') ?></label>
1037 </div></th>
1038 <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" />
1039 <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>
1040 </tr>
1041 <?php endif; ?>
1042
1043 <tr valign="top">
1044 <th scope="row"><?php _e('Connection Type') ?></th>
1045 <td>
1046 <fieldset><legend class="screen-reader-text"><span><?php _e('Connection Type') ?></span></legend>
1047 <?php
1048         $disabled = disabled( (defined('FTP_SSL') && FTP_SSL) || (defined('FTP_SSH') && FTP_SSH), true, false );
1049         foreach ( $types as $name => $text ) : ?>
1050         <label for="<?php echo esc_attr($name) ?>">
1051                 <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; ?> />
1052                 <?php echo $text ?>
1053         </label>
1054         <?php endforeach; ?>
1055 </fieldset>
1056 </td>
1057 </tr>
1058 </table>
1059
1060 <?php
1061 foreach ( (array) $extra_fields as $field ) {
1062         if ( isset( $_POST[ $field ] ) )
1063                 echo '<input type="hidden" name="' . esc_attr( $field ) . '" value="' . esc_attr( stripslashes( $_POST[ $field ] ) ) . '" />';
1064 }
1065 submit_button( __( 'Proceed' ), 'button', 'upgrade' );
1066 ?>
1067 </div>
1068 </form>
1069 <?php
1070         return false;
1071 }