PageRenderTime 53ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-admin/includes/file.php

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