]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-admin/includes/file.php
Wordpress 2.7.1-scripts
[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         'rtl.css' => __( 'RTL Stylesheet' ),
14         'comments.php' => __( 'Comments' ),
15         'comments-popup.php' => __( 'Popup Comments' ),
16         'footer.php' => __( 'Footer' ),
17         'header.php' => __( 'Header' ),
18         'sidebar.php' => __( 'Sidebar' ),
19         'archive.php' => __( 'Archives' ),
20         'category.php' => __( 'Category Template' ),
21         'page.php' => __( 'Page Template' ),
22         'search.php' => __( 'Search Results' ),
23         'searchform.php' => __( 'Search Form' ),
24         'single.php' => __( 'Single Post' ),
25         '404.php' => __( '404 Template' ),
26         'link.php' => __( 'Links Template' ),
27         'functions.php' => __( 'Theme Functions' ),
28         'attachment.php' => __( 'Attachment Template' ),
29         'image.php' => __('Image Attachment Template'),
30         'video.php' => __('Video Attachment Template'),
31         'audio.php' => __('Audio Attachment Template'),
32         'application.php' => __('Application Attachment Template'),
33         'my-hacks.php' => __( 'my-hacks.php (legacy hacks support)' ),
34         '.htaccess' => __( '.htaccess (for rewrite rules )' ),
35         // Deprecated files
36         'wp-layout.css' => __( 'Stylesheet' ), 'wp-comments.php' => __( 'Comments Template' ), 'wp-comments-popup.php' => __( 'Popup Comments Template' ));
37
38 /**
39  * {@internal Missing Short Description}}
40  *
41  * @since unknown
42  *
43  * @param unknown_type $file
44  * @return unknown
45  */
46 function get_file_description( $file ) {
47         global $wp_file_descriptions;
48
49         if ( isset( $wp_file_descriptions[basename( $file )] ) ) {
50                 return $wp_file_descriptions[basename( $file )];
51         }
52         elseif ( file_exists( WP_CONTENT_DIR . $file ) && is_file( WP_CONTENT_DIR . $file ) ) {
53                 $template_data = implode( '', file( WP_CONTENT_DIR . $file ) );
54                 if ( preg_match( '|Template Name:(.*)$|mi', $template_data, $name ))
55                         return $name[1] . ' Page Template';
56         }
57
58         return basename( $file );
59 }
60
61 /**
62  * {@internal Missing Short Description}}
63  *
64  * @since unknown
65  *
66  * @return unknown
67  */
68 function get_home_path() {
69         $home = get_option( 'home' );
70         if ( $home != '' && $home != get_option( 'siteurl' ) ) {
71                 $home_path = parse_url( $home );
72                 $home_path = $home_path['path'];
73                 $root = str_replace( $_SERVER["PHP_SELF"], '', $_SERVER["SCRIPT_FILENAME"] );
74                 $home_path = trailingslashit( $root.$home_path );
75         } else {
76                 $home_path = ABSPATH;
77         }
78
79         return $home_path;
80 }
81
82 /**
83  * {@internal Missing Short Description}}
84  *
85  * @since unknown
86  *
87  * @param unknown_type $file
88  * @return unknown
89  */
90 function get_real_file_to_edit( $file ) {
91         if ('index.php' == $file || '.htaccess' == $file ) {
92                 $real_file = get_home_path() . $file;
93         } else {
94                 $real_file = WP_CONTENT_DIR . $file;
95         }
96
97         return $real_file;
98 }
99
100 /**
101  * {@internal Missing Short Description}}
102  *
103  * @since unknown
104  *
105  * @param string $folder Optional. Full path to folder
106  * @param int $levels Optional. Levels of folders to follow, Default: 100 (PHP Loop limit).
107  * @return bool|array
108  */
109 function list_files( $folder = '', $levels = 100 ) {
110         if( empty($folder) )
111                 return false;
112
113         if( ! $levels )
114                 return false;
115
116         $files = array();
117         if ( $dir = @opendir( $folder ) ) {
118                 while (($file = readdir( $dir ) ) !== false ) {
119                         if ( in_array($file, array('.', '..') ) )
120                                 continue;
121                         if ( is_dir( $folder . '/' . $file ) ) {
122                                 $files2 = list_files( $folder . '/' . $file, $levels - 1);
123                                 if( $files2 )
124                                         $files = array_merge($files, $files2 );
125                                 else
126                                         $files[] = $folder . '/' . $file . '/';
127                         } else {
128                                 $files[] = $folder . '/' . $file;
129                         }
130                 }
131         }
132         @closedir( $dir );
133         return $files;
134 }
135
136 /**
137  * {@internal Missing Short Description}}
138  *
139  * @since unknown
140  *
141  * @return unknown
142  */
143 function get_temp_dir() {
144         if ( defined('WP_TEMP_DIR') )
145                 return trailingslashit(WP_TEMP_DIR);
146
147         $temp = WP_CONTENT_DIR . '/';
148         if ( is_dir($temp) && is_writable($temp) )
149                 return $temp;
150
151         if  ( function_exists('sys_get_temp_dir') )
152                 return trailingslashit(sys_get_temp_dir());
153
154         return '/tmp/';
155 }
156
157 /**
158  * {@internal Missing Short Description}}
159  *
160  * @since unknown
161  *
162  * @param unknown_type $filename
163  * @param unknown_type $dir
164  * @return unknown
165  */
166 function wp_tempnam($filename = '', $dir = ''){
167         if ( empty($dir) )
168                 $dir = get_temp_dir();
169         $filename = basename($filename);
170         if ( empty($filename) )
171                 $filename = time();
172
173         $filename = $dir . wp_unique_filename($dir, $filename);
174         touch($filename);
175         return $filename;
176 }
177
178 /**
179  * {@internal Missing Short Description}}
180  *
181  * @since unknown
182  *
183  * @param unknown_type $file
184  * @param unknown_type $allowed_files
185  * @return unknown
186  */
187 function validate_file_to_edit( $file, $allowed_files = '' ) {
188         $file = stripslashes( $file );
189
190         $code = validate_file( $file, $allowed_files );
191
192         if (!$code )
193                 return $file;
194
195         switch ( $code ) {
196                 case 1 :
197                         wp_die( __('Sorry, can&#8217;t edit files with ".." 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.' ));
198
199                 case 2 :
200                         wp_die( __('Sorry, can&#8217;t call files with their real path.' ));
201
202                 case 3 :
203                         wp_die( __('Sorry, that file cannot be edited.' ));
204         }
205 }
206
207 /**
208  * {@internal Missing Short Description}}
209  *
210  * @since unknown
211  *
212  * @param array $file Reference to a single element of $_FILES. Call the function once for each uploaded file.
213  * @param array $overrides Optional. An associative array of names=>values to override default variables with extract( $overrides, EXTR_OVERWRITE ).
214  * @return array On success, returns an associative array of file attributes. On failure, returns $overrides['upload_error_handler'](&$file, $message ) or array( 'error'=>$message ).
215  */
216 function wp_handle_upload( &$file, $overrides = false, $time = null ) {
217         // The default error handler.
218         if (! function_exists( 'wp_handle_upload_error' ) ) {
219                 function wp_handle_upload_error( &$file, $message ) {
220                         return array( 'error'=>$message );
221                 }
222         }
223
224         // You may define your own function and pass the name in $overrides['upload_error_handler']
225         $upload_error_handler = 'wp_handle_upload_error';
226
227         // You may define your own function and pass the name in $overrides['unique_filename_callback']
228         $unique_filename_callback = null;
229
230         // $_POST['action'] must be set and its value must equal $overrides['action'] or this:
231         $action = 'wp_handle_upload';
232
233         // Courtesy of php.net, the strings that describe the error indicated in $_FILES[{form field}]['error'].
234         $upload_error_strings = array( false,
235                 __( "The uploaded file exceeds the <code>upload_max_filesize</code> directive in <code>php.ini</code>." ),
236                 __( "The uploaded file exceeds the <em>MAX_FILE_SIZE</em> directive that was specified in the HTML form." ),
237                 __( "The uploaded file was only partially uploaded." ),
238                 __( "No file was uploaded." ),
239                 '',
240                 __( "Missing a temporary folder." ),
241                 __( "Failed to write file to disk." ));
242
243         // All tests are on by default. Most can be turned off by $override[{test_name}] = false;
244         $test_form = true;
245         $test_size = true;
246
247         // If you override this, you must provide $ext and $type!!!!
248         $test_type = true;
249         $mimes = false;
250
251         // Install user overrides. Did we mention that this voids your warranty?
252         if ( is_array( $overrides ) )
253                 extract( $overrides, EXTR_OVERWRITE );
254
255         // A correct form post will pass this test.
256         if ( $test_form && (!isset( $_POST['action'] ) || ($_POST['action'] != $action ) ) )
257                 return $upload_error_handler( $file, __( 'Invalid form submission.' ));
258
259         // A successful upload will pass this test. It makes no sense to override this one.
260         if ( $file['error'] > 0 )
261                 return $upload_error_handler( $file, $upload_error_strings[$file['error']] );
262
263         // A non-empty file will pass this test.
264         if ( $test_size && !($file['size'] > 0 ) )
265                 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.' ));
266
267         // A properly uploaded file will pass this test. There should be no reason to override this one.
268         if (! @ is_uploaded_file( $file['tmp_name'] ) )
269                 return $upload_error_handler( $file, __( 'Specified file failed upload test.' ));
270
271         // A correct MIME type will pass this test. Override $mimes or use the upload_mimes filter.
272         if ( $test_type ) {
273                 $wp_filetype = wp_check_filetype( $file['name'], $mimes );
274
275                 extract( $wp_filetype );
276
277                 if ( ( !$type || !$ext ) && !current_user_can( 'unfiltered_upload' ) )
278                         return $upload_error_handler( $file, __( 'File type does not meet security guidelines. Try another.' ));
279
280                 if ( !$ext )
281                         $ext = ltrim(strrchr($file['name'], '.'), '.');
282
283                 if ( !$type )
284                         $type = $file['type'];
285         }
286
287         // A writable uploads dir will pass this test. Again, there's no point overriding this one.
288         if ( ! ( ( $uploads = wp_upload_dir($time) ) && false === $uploads['error'] ) )
289                 return $upload_error_handler( $file, $uploads['error'] );
290
291         $filename = wp_unique_filename( $uploads['path'], $file['name'], $unique_filename_callback );
292
293         // Move the file to the uploads dir
294         $new_file = $uploads['path'] . "/$filename";
295         if ( false === @ move_uploaded_file( $file['tmp_name'], $new_file ) ) {
296                 return $upload_error_handler( $file, sprintf( __('The uploaded file could not be moved to %s.' ), $uploads['path'] ) );
297         }
298
299         // Set correct file permissions
300         $stat = stat( dirname( $new_file ));
301         $perms = $stat['mode'] & 0000666;
302         @ chmod( $new_file, $perms );
303
304         // Compute the URL
305         $url = $uploads['url'] . "/$filename";
306
307         $return = apply_filters( 'wp_handle_upload', array( 'file' => $new_file, 'url' => $url, 'type' => $type ) );
308
309         return $return;
310 }
311
312 /**
313  * {@internal Missing Short Description}}
314  *
315  * Pass this function an array similar to that of a $_FILES POST array.
316  *
317  * @since unknown
318  *
319  * @param unknown_type $file
320  * @param unknown_type $overrides
321  * @return unknown
322  */
323 function wp_handle_sideload( &$file, $overrides = false ) {
324         // The default error handler.
325         if (! function_exists( 'wp_handle_upload_error' ) ) {
326                 function wp_handle_upload_error( &$file, $message ) {
327                         return array( 'error'=>$message );
328                 }
329         }
330
331         // You may define your own function and pass the name in $overrides['upload_error_handler']
332         $upload_error_handler = 'wp_handle_upload_error';
333
334         // You may define your own function and pass the name in $overrides['unique_filename_callback']
335         $unique_filename_callback = null;
336
337         // $_POST['action'] must be set and its value must equal $overrides['action'] or this:
338         $action = 'wp_handle_sideload';
339
340         // Courtesy of php.net, the strings that describe the error indicated in $_FILES[{form field}]['error'].
341         $upload_error_strings = array( false,
342                 __( "The file exceeds the <code>upload_max_filesize</code> directive in <code>php.ini</code>." ),
343                 __( "The file exceeds the <em>MAX_FILE_SIZE</em> directive that was specified in the HTML form." ),
344                 __( "The file was only partially uploaded." ),
345                 __( "No file was sent." ),
346                 __( "Missing a temporary folder." ),
347                 __( "Failed to write file to disk." ));
348
349         // All tests are on by default. Most can be turned off by $override[{test_name}] = false;
350         $test_form = true;
351         $test_size = true;
352
353         // If you override this, you must provide $ext and $type!!!!
354         $test_type = true;
355         $mimes = false;
356
357         // Install user overrides. Did we mention that this voids your warranty?
358         if ( is_array( $overrides ) )
359                 extract( $overrides, EXTR_OVERWRITE );
360
361         // A correct form post will pass this test.
362         if ( $test_form && (!isset( $_POST['action'] ) || ($_POST['action'] != $action ) ) )
363                 return $upload_error_handler( $file, __( 'Invalid form submission.' ));
364
365         // A successful upload will pass this test. It makes no sense to override this one.
366         if ( $file['error'] > 0 )
367                 return $upload_error_handler( $file, $upload_error_strings[$file['error']] );
368
369         // A non-empty file will pass this test.
370         if ( $test_size && !(filesize($file['tmp_name']) > 0 ) )
371                 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.' ));
372
373         // A properly uploaded file will pass this test. There should be no reason to override this one.
374         if (! @ is_file( $file['tmp_name'] ) )
375                 return $upload_error_handler( $file, __( 'Specified file does not exist.' ));
376
377         // A correct MIME type will pass this test. Override $mimes or use the upload_mimes filter.
378         if ( $test_type ) {
379                 $wp_filetype = wp_check_filetype( $file['name'], $mimes );
380
381                 extract( $wp_filetype );
382
383                 if ( ( !$type || !$ext ) && !current_user_can( 'unfiltered_upload' ) )
384                         return $upload_error_handler( $file, __( 'File type does not meet security guidelines. Try another.' ));
385
386                 if ( !$ext )
387                         $ext = ltrim(strrchr($file['name'], '.'), '.');
388
389                 if ( !$type )
390                         $type = $file['type'];
391         }
392
393         // A writable uploads dir will pass this test. Again, there's no point overriding this one.
394         if ( ! ( ( $uploads = wp_upload_dir() ) && false === $uploads['error'] ) )
395                 return $upload_error_handler( $file, $uploads['error'] );
396
397         $filename = wp_unique_filename( $uploads['path'], $file['name'], $unique_filename_callback );
398
399         // Strip the query strings.
400         $filename = str_replace('?','-', $filename);
401         $filename = str_replace('&','-', $filename);
402
403         // Move the file to the uploads dir
404         $new_file = $uploads['path'] . "/$filename";
405         if ( false === @ rename( $file['tmp_name'], $new_file ) ) {
406                 return $upload_error_handler( $file, sprintf( __('The uploaded file could not be moved to %s.' ), $uploads['path'] ) );
407         }
408
409         // Set correct file permissions
410         $stat = stat( dirname( $new_file ));
411         $perms = $stat['mode'] & 0000666;
412         @ chmod( $new_file, $perms );
413
414         // Compute the URL
415         $url = $uploads['url'] . "/$filename";
416
417         $return = apply_filters( 'wp_handle_upload', array( 'file' => $new_file, 'url' => $url, 'type' => $type ) );
418
419         return $return;
420 }
421
422 /**
423  * Downloads a url to a local file using the Snoopy HTTP Class.
424  *
425  * @since unknown
426  * @todo Transition over to using the new HTTP Request API (jacob).
427  *
428  * @param string $url the URL of the file to download
429  * @return mixed WP_Error on failure, string Filename on success.
430  */
431 function download_url( $url ) {
432         //WARNING: The file is not automatically deleted, The script must unlink() the file.
433         if ( ! $url )
434                 return new WP_Error('http_no_url', __('Invalid URL Provided'));
435
436         $tmpfname = wp_tempnam($url);
437         if ( ! $tmpfname )
438                 return new WP_Error('http_no_file', __('Could not create Temporary file'));
439
440         $handle = @fopen($tmpfname, 'wb');
441         if ( ! $handle )
442                 return new WP_Error('http_no_file', __('Could not create Temporary file'));
443
444         $response = wp_remote_get($url, array('timeout' => 30));
445
446         if ( is_wp_error($response) ) {
447                 fclose($handle);
448                 unlink($tmpfname);
449                 return $response;
450         }
451
452         if ( $response['response']['code'] != '200' ){
453                 fclose($handle);
454                 unlink($tmpfname);
455                 return new WP_Error('http_404', trim($response['response']['message']));
456         }
457
458         fwrite($handle, $response['body']);
459         fclose($handle);
460
461         return $tmpfname;
462 }
463
464 /**
465  * {@internal Missing Short Description}}
466  *
467  * @since unknown
468  *
469  * @param unknown_type $file
470  * @param unknown_type $to
471  * @return unknown
472  */
473 function unzip_file($file, $to) {
474         global $wp_filesystem;
475
476         if ( ! $wp_filesystem || !is_object($wp_filesystem) )
477                 return new WP_Error('fs_unavailable', __('Could not access filesystem.'));
478
479         // Unzip uses a lot of memory
480         @ini_set('memory_limit', '256M');
481
482         $fs =& $wp_filesystem;
483
484         require_once(ABSPATH . 'wp-admin/includes/class-pclzip.php');
485
486         $archive = new PclZip($file);
487
488         // Is the archive valid?
489         if ( false == ($archive_files = $archive->extract(PCLZIP_OPT_EXTRACT_AS_STRING)) )
490                 return new WP_Error('incompatible_archive', __('Incompatible archive'), $archive->errorInfo(true));
491
492         if ( 0 == count($archive_files) )
493                 return new WP_Error('empty_archive', __('Empty archive'));
494
495         $path = explode('/', untrailingslashit($to));
496         for ( $i = count($path); $i > 0; $i-- ) { //>0 = first element is empty allways for paths starting with '/'
497                 $tmppath = implode('/', array_slice($path, 0, $i) );
498                 if ( $fs->is_dir($tmppath) ) { //Found the highest folder that exists, Create from here(ie +1)
499                         for ( $i = $i + 1; $i <= count($path); $i++ ) {
500                                 $tmppath = implode('/', array_slice($path, 0, $i) );
501                                 if ( ! $fs->mkdir($tmppath, FS_CHMOD_DIR) )
502                                         return new WP_Error('mkdir_failed', __('Could not create directory'), $tmppath);
503                         }
504                         break; //Exit main for loop
505                 }
506         }
507
508         $to = trailingslashit($to);
509         foreach ($archive_files as $file) {
510                 $path = $file['folder'] ? $file['filename'] : dirname($file['filename']);
511                 $path = explode('/', $path);
512                 for ( $i = count($path); $i >= 0; $i-- ) { //>=0 as the first element contains data
513                         if ( empty($path[$i]) )
514                                 continue;
515                         $tmppath = $to . implode('/', array_slice($path, 0, $i) );
516                         if ( $fs->is_dir($tmppath) ) {//Found the highest folder that exists, Create from here
517                                 for ( $i = $i + 1; $i <= count($path); $i++ ) { //< count() no file component please.
518                                         $tmppath = $to . implode('/', array_slice($path, 0, $i) );
519                                         if ( ! $fs->is_dir($tmppath) && ! $fs->mkdir($tmppath, FS_CHMOD_DIR) )
520                                                 return new WP_Error('mkdir_failed', __('Could not create directory'), $tmppath);
521                                 }
522                                 break; //Exit main for loop
523                         }
524                 }
525
526                 // We've made sure the folders are there, so let's extract the file now:
527                 if ( ! $file['folder'] ) {
528                         if ( !$fs->put_contents( $to . $file['filename'], $file['content']) )
529                                 return new WP_Error('copy_failed', __('Could not copy file'), $to . $file['filename']);
530                         $fs->chmod($to . $file['filename'], FS_CHMOD_FILE);
531                 }
532         }
533         return true;
534 }
535
536 /**
537  * {@internal Missing Short Description}}
538  *
539  * @since unknown
540  *
541  * @param unknown_type $from
542  * @param unknown_type $to
543  * @return unknown
544  */
545 function copy_dir($from, $to) {
546         global $wp_filesystem;
547
548         $dirlist = $wp_filesystem->dirlist($from);
549
550         $from = trailingslashit($from);
551         $to = trailingslashit($to);
552
553         foreach ( (array) $dirlist as $filename => $fileinfo ) {
554                 if ( 'f' == $fileinfo['type'] ) {
555                         if ( ! $wp_filesystem->copy($from . $filename, $to . $filename, true) ) {
556                                 // If copy failed, chmod file to 0644 and try again.
557                                 $wp_filesystem->chmod($to . $filename, 0644);
558                                 if ( ! $wp_filesystem->copy($from . $filename, $to . $filename, true) )
559                                         return new WP_Error('copy_failed', __('Could not copy file'), $to . $filename);
560                         }
561                         $wp_filesystem->chmod($to . $filename, FS_CHMOD_FILE);
562                 } elseif ( 'd' == $fileinfo['type'] ) {
563                         if ( !$wp_filesystem->is_dir($to . $filename) ) {
564                                 if ( !$wp_filesystem->mkdir($to . $filename, FS_CHMOD_DIR) )
565                                         return new WP_Error('mkdir_failed', __('Could not create directory'), $to . $filename);
566                         }
567                         $result = copy_dir($from . $filename, $to . $filename);
568                         if ( is_wp_error($result) )
569                                 return $result;
570                 }
571         }
572 }
573
574 /**
575  * {@internal Missing Short Description}}
576  *
577  * @since unknown
578  *
579  * @param unknown_type $args
580  * @return unknown
581  */
582 function WP_Filesystem( $args = false ) {
583         global $wp_filesystem;
584
585         require_once(ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php');
586
587         $method = get_filesystem_method($args);
588
589         if ( ! $method )
590                 return false;
591
592         $abstraction_file = apply_filters('filesystem_method_file', ABSPATH . 'wp-admin/includes/class-wp-filesystem-' . $method . '.php', $method);
593         if( ! file_exists($abstraction_file) )
594                 return;
595
596         require_once($abstraction_file);
597         $method = "WP_Filesystem_$method";
598
599         $wp_filesystem = new $method($args);
600
601         if ( $wp_filesystem->errors->get_error_code() )
602                 return false;
603
604         if ( !$wp_filesystem->connect() )
605                 return false; //There was an erorr connecting to the server.
606
607         // Set the permission constants if not already set.
608         if ( ! defined('FS_CHMOD_DIR') )
609                 define('FS_CHMOD_DIR', 0755 );
610         if ( ! defined('FS_CHMOD_FILE') )
611                 define('FS_CHMOD_FILE', 0644 );
612
613         return true;
614 }
615
616 /**
617  * {@internal Missing Short Description}}
618  *
619  * @since unknown
620  *
621  * @param unknown_type $args
622  * @return unknown
623  */
624 function get_filesystem_method($args = array()) {
625         $method = false;
626         if( function_exists('getmyuid') && function_exists('fileowner') ){
627                 $temp_file = wp_tempnam();
628                 if ( getmyuid() == fileowner($temp_file) )
629                         $method = 'direct';
630                 unlink($temp_file);
631         }
632
633         if ( ! $method && isset($args['connection_type']) && 'ssh' == $args['connection_type'] && extension_loaded('ssh2') ) $method = 'ssh2';
634         if ( ! $method && extension_loaded('ftp') ) $method = 'ftpext';
635         if ( ! $method && ( extension_loaded('sockets') || function_exists('fsockopen') ) ) $method = 'ftpsockets'; //Sockets: Socket extension; PHP Mode: FSockopen / fwrite / fread
636         return apply_filters('filesystem_method', $method);
637 }
638
639 /**
640  * {@internal Missing Short Description}}
641  *
642  * @since unknown
643  *
644  * @param unknown_type $form_post
645  * @param unknown_type $type
646  * @param unknown_type $error
647  * @return unknown
648  */
649 function request_filesystem_credentials($form_post, $type = '', $error = false) {
650         $req_cred = apply_filters('request_filesystem_credentials', '', $form_post, $type, $error);
651         if ( '' !== $req_cred )
652                 return $req_cred;
653
654         if ( empty($type) )
655                 $type = get_filesystem_method();
656
657         if ( 'direct' == $type )
658                 return true;
659
660         $credentials = get_option('ftp_credentials', array());
661         // 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)
662         $credentials['hostname'] = defined('FTP_HOST') ? FTP_HOST : (!empty($_POST['hostname']) ? $_POST['hostname'] : $credentials['hostname']);
663         $credentials['username'] = defined('FTP_USER') ? FTP_USER : (!empty($_POST['username']) ? $_POST['username'] : $credentials['username']);
664         $credentials['password'] = defined('FTP_PASS') ? FTP_PASS : (!empty($_POST['password']) ? $_POST['password'] : $credentials['password']);
665
666         // Check to see if we are setting the public/private keys for ssh
667         $credentials['public_key'] = defined('FTP_PUBKEY') ? FTP_PUBKEY : (!empty($_POST['public_key']) ? $_POST['public_key'] : $credentials['public_key']);
668         $credentials['private_key'] = defined('FTP_PRIKEY') ? FTP_PRIKEY : (!empty($_POST['private_key']) ? $_POST['private_key'] : $credentials['private_key']);
669
670         //sanitize the hostname, Some people might pass in odd-data:
671         $credentials['hostname'] = preg_replace('|\w+://|', '', $credentials['hostname']); //Strip any schemes off
672
673         if ( strpos($credentials['hostname'], ':') )
674                 list( $credentials['hostname'], $credentials['port'] ) = explode(':', $credentials['hostname'], 2);
675         else
676                 unset($credentials['port']);
677
678         if ( defined('FTP_SSH') || (isset($_POST['connection_type']) && 'ssh' == $_POST['connection_type']) )
679                 $credentials['connection_type'] = 'ssh';
680         else if ( defined('FTP_SSL') || (isset($_POST['connection_type']) && 'ftps' == $_POST['connection_type']) )
681                 $credentials['connection_type'] = 'ftps';
682         else if ( !isset($credentials['connection_type']) || (isset($_POST['connection_type']) && 'ftp' == $_POST['connection_type']) )
683                 $credentials['connection_type'] = 'ftp';
684
685         if ( ! $error && !empty($credentials['password']) && !empty($credentials['username']) && !empty($credentials['hostname']) ) {
686                 $stored_credentials = $credentials;
687                 if ( !empty($stored_credentials['port']) ) //save port as part of hostname to simplify above code.
688                         $stored_credentials['hostname'] .= ':' . $stored_credentials['port'];
689
690                 unset($stored_credentials['password'], $stored_credentials['port'], $stored_credentials['private_key'], $stored_credentials['public_key']);
691                 update_option('ftp_credentials', $stored_credentials);
692                 return $credentials;
693         }
694         $hostname = '';
695         $username = '';
696         $password = '';
697         $connection_type = '';
698         if ( !empty($credentials) )
699                 extract($credentials, EXTR_OVERWRITE);
700         if ( $error ) {
701                 $error_string = __('<strong>Error:</strong> There was an error connecting to the server, Please verify the settings are correct.');
702                 if ( is_wp_error($error) )
703                         $error_string = $error->get_error_message();
704                 echo '<div id="message" class="error"><p>' . $error_string . '</p></div>';
705         }
706 ?>
707 <script type="text/javascript">
708 <!--
709 jQuery(function($){
710         jQuery("#ssh").click(function () {
711                 jQuery("#ssh_keys").show();
712         });
713         jQuery("#ftp, #ftps").click(function () {
714                 jQuery("#ssh_keys").hide();
715         });
716 });
717 -->
718 </script>
719 <form action="<?php echo $form_post ?>" method="post">
720 <div class="wrap">
721 <h2><?php _e('Connection Information') ?></h2>
722 <p><?php _e('To perform the requested action, connection information is required.') ?></p>
723
724 <table class="form-table">
725 <tr valign="top">
726 <th scope="row"><label for="hostname"><?php _e('Hostname') ?></label></th>
727 <td><input name="hostname" type="text" id="hostname" value="<?php echo attribute_escape($hostname); if ( !empty($port) ) echo ":$port"; ?>"<?php if( defined('FTP_HOST') ) echo ' disabled="disabled"' ?> size="40" /></td>
728 </tr>
729
730 <tr valign="top">
731 <th scope="row"><label for="username"><?php _e('Username') ?></label></th>
732 <td><input name="username" type="text" id="username" value="<?php echo attribute_escape($username) ?>"<?php if( defined('FTP_USER') ) echo ' disabled="disabled"' ?> size="40" /></td>
733 </tr>
734
735 <tr valign="top">
736 <th scope="row"><label for="password"><?php _e('Password') ?></label></th>
737 <td><input name="password" type="password" id="password" value=""<?php if( defined('FTP_PASS') ) echo ' disabled="disabled"' ?> size="40" /><?php if( defined('FTP_PASS') && !empty($password) ) echo '<em>'.__('(Password not shown)').'</em>'; ?></td>
738 </tr>
739
740 <tr id="ssh_keys" valign="top" style="<?php if ( 'ssh' != $connection_type ) echo 'display:none' ?>">
741 <th scope="row"><?php _e('Authentication Keys') ?>
742 <div class="key-labels textright">
743 <label for="public_key"><?php _e('Public Key:') ?></label ><br />
744 <label for="private_key"><?php _e('Private Key:') ?></label>
745 </div></th>
746 <td><br /><input name="public_key" type="text" id="public_key" value=""<?php if( defined('FTP_PUBKEY') ) echo ' disabled="disabled"' ?> size="40" /><br /><input name="private_key" type="text" id="private_key" value=""<?php if( defined('FTP_PRIKEY') ) echo ' disabled="disabled"' ?> size="40" />
747 <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>
748 </tr>
749
750 <tr valign="top">
751 <th scope="row"><?php _e('Connection Type') ?></th>
752 <td>
753 <fieldset><legend class="hidden"><?php _e('Connection Type') ?></legend>
754 <label><input id="ftp" name="connection_type"  type="radio" value="ftp" <?php checked('ftp', $connection_type); if ( defined('FTP_SSL') || defined('FTP_SSH') ) echo ' disabled="disabled"'; ?>/> <?php _e('FTP') ?></label><br />
755 <label><input id="ftps" name="connection_type" type="radio" value="ftps" <?php checked('ftps', $connection_type); if ( defined('FTP_SSH') || defined('FTP_SSH') ) echo ' disabled="disabled"';  ?>/> <?php _e('FTPS (SSL)') ?></label><br />
756 <?php if ( extension_loaded('ssh2') ) { ?><label><input id="ssh" name="connection_type" type="radio" value="ssh" <?php checked('ssh', $connection_type);  if ( defined('FTP_SSL') || defined('FTP_SSH') ) echo ' disabled="disabled"'; ?>/> <?php _e('SSH') ?></label><?php } ?>
757 </fieldset>
758 </td>
759 </tr>
760 </table>
761
762 <?php if ( isset( $_POST['version'] ) ) : ?>
763 <input type="hidden" name="version" value="<?php echo attribute_escape($_POST['version']) ?>" />
764 <?php endif; ?>
765 <?php if ( isset( $_POST['locale'] ) ) : ?>
766 <input type="hidden" name="locale" value="<?php echo attribute_escape($_POST['locale']) ?>" />
767 <?php endif; ?>
768 <p class="submit">
769 <input id="upgrade" name="upgrade" type="submit" class="button" value="<?php _e('Proceed'); ?>" />
770 </p>
771 </div>
772 </form>
773 <?php
774         return false;
775 }
776
777 ?>