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