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