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