PageRenderTime 60ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-admin/includes/file.php

https://bitbucket.org/opehei/wordpress-trunk
PHP | 1061 lines | 683 code | 148 blank | 230 comment | 200 complexity | 08fb98888ccc81dc2d1227cf78b6497f MD5 | raw file
Possible License(s): AGPL-1.0, LGPL-2.1, GPL-2.0
  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'] ), $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. return $upload_error_handler( $file, sprintf( __('The uploaded file could not be moved to %s.' ), $uploads['path'] ) );
  292. // Set correct file permissions
  293. $stat = stat( dirname( $new_file ));
  294. $perms = $stat['mode'] & 0000666;
  295. @ chmod( $new_file, $perms );
  296. // Compute the URL
  297. $url = $uploads['url'] . "/$filename";
  298. if ( is_multisite() )
  299. delete_transient( 'dirsize_cache' );
  300. return apply_filters( 'wp_handle_upload', array( 'file' => $new_file, 'url' => $url, 'type' => $type ), 'upload' );
  301. }
  302. /**
  303. * Handle sideloads, which is the process of retrieving a media item from another server instead of
  304. * a traditional media upload. This process involves sanitizing the filename, checking extensions
  305. * for mime type, and moving the file to the appropriate directory within the uploads directory.
  306. *
  307. * @since 2.6.0
  308. *
  309. * @uses wp_handle_upload_error
  310. * @uses apply_filters
  311. * @uses wp_check_filetype_and_ext
  312. * @uses current_user_can
  313. * @uses wp_upload_dir
  314. * @uses wp_unique_filename
  315. * @param array $file an array similar to that of a PHP $_FILES POST array
  316. * @param array $overrides Optional. An associative array of names=>values to override default variables with extract( $overrides, EXTR_OVERWRITE ).
  317. * @param string $time Optional. Time formatted in 'yyyy/mm'.
  318. * @return array On success, returns an associative array of file attributes. On failure, returns $overrides['upload_error_handler'](&$file, $message ) or array( 'error'=>$message ).
  319. */
  320. function wp_handle_sideload( &$file, $overrides = false, $time = null ) {
  321. // The default error handler.
  322. if (! function_exists( 'wp_handle_upload_error' ) ) {
  323. function wp_handle_upload_error( &$file, $message ) {
  324. return array( 'error'=>$message );
  325. }
  326. }
  327. // You may define your own function and pass the name in $overrides['upload_error_handler']
  328. $upload_error_handler = 'wp_handle_upload_error';
  329. // You may define your own function and pass the name in $overrides['unique_filename_callback']
  330. $unique_filename_callback = null;
  331. // $_POST['action'] must be set and its value must equal $overrides['action'] or this:
  332. $action = 'wp_handle_sideload';
  333. // Courtesy of php.net, the strings that describe the error indicated in $_FILES[{form field}]['error'].
  334. $upload_error_strings = array( false,
  335. __( "The uploaded file exceeds the <code>upload_max_filesize</code> directive in <code>php.ini</code>." ),
  336. __( "The uploaded file exceeds the <em>MAX_FILE_SIZE</em> directive that was specified in the HTML form." ),
  337. __( "The uploaded file was only partially uploaded." ),
  338. __( "No file was uploaded." ),
  339. '',
  340. __( "Missing a temporary folder." ),
  341. __( "Failed to write file to disk." ),
  342. __( "File upload stopped by extension." ));
  343. // All tests are on by default. Most can be turned off by $overrides[{test_name}] = false;
  344. $test_form = true;
  345. $test_size = true;
  346. // If you override this, you must provide $ext and $type!!!!
  347. $test_type = true;
  348. $mimes = false;
  349. // Install user overrides. Did we mention that this voids your warranty?
  350. if ( is_array( $overrides ) )
  351. extract( $overrides, EXTR_OVERWRITE );
  352. // A correct form post will pass this test.
  353. if ( $test_form && (!isset( $_POST['action'] ) || ($_POST['action'] != $action ) ) )
  354. return $upload_error_handler( $file, __( 'Invalid form submission.' ));
  355. // A successful upload will pass this test. It makes no sense to override this one.
  356. if ( ! empty( $file['error'] ) )
  357. return $upload_error_handler( $file, $upload_error_strings[$file['error']] );
  358. // A non-empty file will pass this test.
  359. if ( $test_size && !(filesize($file['tmp_name']) > 0 ) )
  360. 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.' ));
  361. // A properly uploaded file will pass this test. There should be no reason to override this one.
  362. if (! @ is_file( $file['tmp_name'] ) )
  363. return $upload_error_handler( $file, __( 'Specified file does not exist.' ));
  364. // A correct MIME type will pass this test. Override $mimes or use the upload_mimes filter.
  365. if ( $test_type ) {
  366. $wp_filetype = wp_check_filetype_and_ext( $file['tmp_name'], $file['name'], $mimes );
  367. extract( $wp_filetype );
  368. // Check to see if wp_check_filetype_and_ext() determined the filename was incorrect
  369. if ( $proper_filename )
  370. $file['name'] = $proper_filename;
  371. if ( ( !$type || !$ext ) && !current_user_can( 'unfiltered_upload' ) )
  372. return $upload_error_handler( $file, __( 'Sorry, this file type is not permitted for security reasons.' ));
  373. if ( !$ext )
  374. $ext = ltrim(strrchr($file['name'], '.'), '.');
  375. if ( !$type )
  376. $type = $file['type'];
  377. }
  378. // A writable uploads dir will pass this test. Again, there's no point overriding this one.
  379. if ( ! ( ( $uploads = wp_upload_dir( $time ) ) && false === $uploads['error'] ) )
  380. return $upload_error_handler( $file, $uploads['error'] );
  381. $filename = wp_unique_filename( $uploads['path'], $file['name'], $unique_filename_callback );
  382. // Strip the query strings.
  383. $filename = str_replace('?','-', $filename);
  384. $filename = str_replace('&','-', $filename);
  385. // Move the file to the uploads dir
  386. $new_file = $uploads['path'] . "/$filename";
  387. if ( false === @ rename( $file['tmp_name'], $new_file ) ) {
  388. return $upload_error_handler( $file, sprintf( __('The uploaded file could not be moved to %s.' ), $uploads['path'] ) );
  389. }
  390. // Set correct file permissions
  391. $stat = stat( dirname( $new_file ));
  392. $perms = $stat['mode'] & 0000666;
  393. @ chmod( $new_file, $perms );
  394. // Compute the URL
  395. $url = $uploads['url'] . "/$filename";
  396. $return = apply_filters( 'wp_handle_upload', array( 'file' => $new_file, 'url' => $url, 'type' => $type ), 'sideload' );
  397. return $return;
  398. }
  399. /**
  400. * Downloads a url to a local temporary file using the WordPress HTTP Class.
  401. * Please note, That the calling function must unlink() the file.
  402. *
  403. * @since 2.5.0
  404. *
  405. * @param string $url the URL of the file to download
  406. * @param int $timeout The timeout for the request to download the file default 300 seconds
  407. * @return mixed WP_Error on failure, string Filename on success.
  408. */
  409. function download_url( $url, $timeout = 300 ) {
  410. //WARNING: The file is not automatically deleted, The script must unlink() the file.
  411. if ( ! $url )
  412. return new WP_Error('http_no_url', __('Invalid URL Provided.'));
  413. $tmpfname = wp_tempnam($url);
  414. if ( ! $tmpfname )
  415. return new WP_Error('http_no_file', __('Could not create Temporary file.'));
  416. $response = wp_remote_get( $url, array( 'timeout' => $timeout, 'stream' => true, 'filename' => $tmpfname ) );
  417. if ( is_wp_error( $response ) ) {
  418. unlink( $tmpfname );
  419. return $response;
  420. }
  421. if ( 200 != wp_remote_retrieve_response_code( $response ) ){
  422. unlink( $tmpfname );
  423. return new WP_Error( 'http_404', trim( wp_remote_retrieve_response_message( $response ) ) );
  424. }
  425. return $tmpfname;
  426. }
  427. /**
  428. * Unzips a specified ZIP file to a location on the Filesystem via the WordPress Filesystem Abstraction.
  429. * Assumes that WP_Filesystem() has already been called and set up. Does not extract a root-level __MACOSX directory, if present.
  430. *
  431. * Attempts to increase the PHP Memory limit to 256M before uncompressing,
  432. * However, The most memory required shouldn't be much larger than the Archive itself.
  433. *
  434. * @since 2.5.0
  435. *
  436. * @param string $file Full path and filename of zip archive
  437. * @param string $to Full path on the filesystem to extract archive to
  438. * @return mixed WP_Error on failure, True on success
  439. */
  440. function unzip_file($file, $to) {
  441. global $wp_filesystem;
  442. if ( ! $wp_filesystem || !is_object($wp_filesystem) )
  443. return new WP_Error('fs_unavailable', __('Could not access filesystem.'));
  444. // Unzip can use a lot of memory, but not this much hopefully
  445. @ini_set( 'memory_limit', apply_filters( 'admin_memory_limit', WP_MAX_MEMORY_LIMIT ) );
  446. $needed_dirs = array();
  447. $to = trailingslashit($to);
  448. // Determine any parent dir's needed (of the upgrade directory)
  449. if ( ! $wp_filesystem->is_dir($to) ) { //Only do parents if no children exist
  450. $path = preg_split('![/\\\]!', untrailingslashit($to));
  451. for ( $i = count($path); $i >= 0; $i-- ) {
  452. if ( empty($path[$i]) )
  453. continue;
  454. $dir = implode('/', array_slice($path, 0, $i+1) );
  455. if ( preg_match('!^[a-z]:$!i', $dir) ) // Skip it if it looks like a Windows Drive letter.
  456. continue;
  457. if ( ! $wp_filesystem->is_dir($dir) )
  458. $needed_dirs[] = $dir;
  459. else
  460. break; // A folder exists, therefor, we dont need the check the levels below this
  461. }
  462. }
  463. if ( class_exists('ZipArchive') && apply_filters('unzip_file_use_ziparchive', true ) ) {
  464. $result = _unzip_file_ziparchive($file, $to, $needed_dirs);
  465. if ( true === $result ) {
  466. return $result;
  467. } elseif ( is_wp_error($result) ) {
  468. if ( 'incompatible_archive' != $result->get_error_code() )
  469. return $result;
  470. }
  471. }
  472. // Fall through to PclZip if ZipArchive is not available, or encountered an error opening the file.
  473. return _unzip_file_pclzip($file, $to, $needed_dirs);
  474. }
  475. /**
  476. * This function should not be called directly, use unzip_file instead. Attempts to unzip an archive using the ZipArchive class.
  477. * Assumes that WP_Filesystem() has already been called and set up.
  478. *
  479. * @since 3.0.0
  480. * @see unzip_file
  481. * @access private
  482. *
  483. * @param string $file Full path and filename of zip archive
  484. * @param string $to Full path on the filesystem to extract archive to
  485. * @param array $needed_dirs A partial list of required folders needed to be created.
  486. * @return mixed WP_Error on failure, True on success
  487. */
  488. function _unzip_file_ziparchive($file, $to, $needed_dirs = array() ) {
  489. global $wp_filesystem;
  490. $z = new ZipArchive();
  491. // PHP4-compat - php4 classes can't contain constants
  492. $zopen = $z->open($file, /* ZIPARCHIVE::CHECKCONS */ 4);
  493. if ( true !== $zopen )
  494. return new WP_Error('incompatible_archive', __('Incompatible Archive.'));
  495. for ( $i = 0; $i < $z->numFiles; $i++ ) {
  496. if ( ! $info = $z->statIndex($i) )
  497. return new WP_Error('stat_failed', __('Could not retrieve file from archive.'));
  498. if ( '__MACOSX/' === substr($info['name'], 0, 9) ) // Skip the OS X-created __MACOSX directory
  499. continue;
  500. if ( '/' == substr($info['name'], -1) ) // directory
  501. $needed_dirs[] = $to . untrailingslashit($info['name']);
  502. else
  503. $needed_dirs[] = $to . untrailingslashit(dirname($info['name']));
  504. }
  505. $needed_dirs = array_unique($needed_dirs);
  506. foreach ( $needed_dirs as $dir ) {
  507. // Check the parent folders of the folders all exist within the creation array.
  508. if ( untrailingslashit($to) == $dir ) // Skip over the working directory, We know this exists (or will exist)
  509. continue;
  510. if ( strpos($dir, $to) === false ) // If the directory is not within the working directory, Skip it
  511. continue;
  512. $parent_folder = dirname($dir);
  513. while ( !empty($parent_folder) && untrailingslashit($to) != $parent_folder && !in_array($parent_folder, $needed_dirs) ) {
  514. $needed_dirs[] = $parent_folder;
  515. $parent_folder = dirname($parent_folder);
  516. }
  517. }
  518. asort($needed_dirs);
  519. // Create those directories if need be:
  520. foreach ( $needed_dirs as $_dir ) {
  521. 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.
  522. return new WP_Error('mkdir_failed', __('Could not create directory.'), $_dir);
  523. }
  524. unset($needed_dirs);
  525. for ( $i = 0; $i < $z->numFiles; $i++ ) {
  526. if ( ! $info = $z->statIndex($i) )
  527. return new WP_Error('stat_failed', __('Could not retrieve file from archive.'));
  528. if ( '/' == substr($info['name'], -1) ) // directory
  529. continue;
  530. if ( '__MACOSX/' === substr($info['name'], 0, 9) ) // Don't extract the OS X-created __MACOSX directory files
  531. continue;
  532. $contents = $z->getFromIndex($i);
  533. if ( false === $contents )
  534. return new WP_Error('extract_failed', __('Could not extract file from archive.'), $info['name']);
  535. if ( ! $wp_filesystem->put_contents( $to . $info['name'], $contents, FS_CHMOD_FILE) )
  536. return new WP_Error('copy_failed', __('Could not copy file.'), $to . $info['name']);
  537. }
  538. $z->close();
  539. return true;
  540. }
  541. /**
  542. * This function should not be called directly, use unzip_file instead. Attempts to unzip an archive using the PclZip library.
  543. * Assumes that WP_Filesystem() has already been called and set up.
  544. *
  545. * @since 3.0.0
  546. * @see unzip_file
  547. * @access private
  548. *
  549. * @param string $file Full path and filename of zip archive
  550. * @param string $to Full path on the filesystem to extract archive to
  551. * @param array $needed_dirs A partial list of required folders needed to be created.
  552. * @return mixed WP_Error on failure, True on success
  553. */
  554. function _unzip_file_pclzip($file, $to, $needed_dirs = array()) {
  555. global $wp_filesystem;
  556. // See #15789 - PclZip uses string functions on binary data, If it's overloaded with Multibyte safe functions the results are incorrect.
  557. if ( ini_get('mbstring.func_overload') && function_exists('mb_internal_encoding') ) {
  558. $previous_encoding = mb_internal_encoding();
  559. mb_internal_encoding('ISO-8859-1');
  560. }
  561. require_once(ABSPATH . 'wp-admin/includes/class-pclzip.php');
  562. $archive = new PclZip($file);
  563. $archive_files = $archive->extract(PCLZIP_OPT_EXTRACT_AS_STRING);
  564. if ( isset($previous_encoding) )
  565. mb_internal_encoding($previous_encoding);
  566. // Is the archive valid?
  567. if ( !is_array($archive_files) )
  568. return new WP_Error('incompatible_archive', __('Incompatible Archive.'), $archive->errorInfo(true));
  569. if ( 0 == count($archive_files) )
  570. return new WP_Error('empty_archive', __('Empty archive.'));
  571. // Determine any children directories needed (From within the archive)
  572. foreach ( $archive_files as $file ) {
  573. if ( '__MACOSX/' === substr($file['filename'], 0, 9) ) // Skip the OS X-created __MACOSX directory
  574. continue;
  575. $needed_dirs[] = $to . untrailingslashit( $file['folder'] ? $file['filename'] : dirname($file['filename']) );
  576. }
  577. $needed_dirs = array_unique($needed_dirs);
  578. foreach ( $needed_dirs as $dir ) {
  579. // Check the parent folders of the folders all exist within the creation array.
  580. if ( untrailingslashit($to) == $dir ) // Skip over the working directory, We know this exists (or will exist)
  581. continue;
  582. if ( strpos($dir, $to) === false ) // If the directory is not within the working directory, Skip it
  583. continue;
  584. $parent_folder = dirname($dir);
  585. while ( !empty($parent_folder) && untrailingslashit($to) != $parent_folder && !in_array($parent_folder, $needed_dirs) ) {
  586. $needed_dirs[] = $parent_folder;
  587. $parent_folder = dirname($parent_folder);
  588. }
  589. }
  590. asort($needed_dirs);
  591. // Create those directories if need be:
  592. foreach ( $needed_dirs as $_dir ) {
  593. 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.
  594. return new WP_Error('mkdir_failed', __('Could not create directory.'), $_dir);
  595. }
  596. unset($needed_dirs);
  597. // Extract the files from the zip
  598. foreach ( $archive_files as $file ) {
  599. if ( $file['folder'] )
  600. continue;
  601. if ( '__MACOSX/' === substr($file['filename'], 0, 9) ) // Don't extract the OS X-created __MACOSX directory files
  602. continue;
  603. if ( ! $wp_filesystem->put_contents( $to . $file['filename'], $file['content'], FS_CHMOD_FILE) )
  604. return new WP_Error('copy_failed', __('Could not copy file.'), $to . $file['filename']);
  605. }
  606. return true;
  607. }
  608. /**
  609. * Copies a directory from one location to another via the WordPress Filesystem Abstraction.
  610. * Assumes that WP_Filesystem() has already been called and setup.
  611. *
  612. * @since 2.5.0
  613. *
  614. * @param string $from source directory
  615. * @param string $to destination directory
  616. * @param array $skip_list a list of files/folders to skip copying
  617. * @return mixed WP_Error on failure, True on success.
  618. */
  619. function copy_dir($from, $to, $skip_list = array() ) {
  620. global $wp_filesystem;
  621. $dirlist = $wp_filesystem->dirlist($from);
  622. $from = trailingslashit($from);
  623. $to = trailingslashit($to);
  624. $skip_regex = '';
  625. foreach ( (array)$skip_list as $key => $skip_file )
  626. $skip_regex .= preg_quote($skip_file, '!') . '|';
  627. if ( !empty($skip_regex) )
  628. $skip_regex = '!(' . rtrim($skip_regex, '|') . ')$!i';
  629. foreach ( (array) $dirlist as $filename => $fileinfo ) {
  630. if ( !empty($skip_regex) )
  631. if ( preg_match($skip_regex, $from . $filename) )
  632. continue;
  633. if ( 'f' == $fileinfo['type'] ) {
  634. if ( ! $wp_filesystem->copy($from . $filename, $to . $filename, true, FS_CHMOD_FILE) ) {
  635. // If copy failed, chmod file to 0644 and try again.
  636. $wp_filesystem->chmod($to . $filename, 0644);
  637. if ( ! $wp_filesystem->copy($from . $filename, $to . $filename, true, FS_CHMOD_FILE) )
  638. return new WP_Error('copy_failed', __('Could not copy file.'), $to . $filename);
  639. }
  640. } elseif ( 'd' == $fileinfo['type'] ) {
  641. if ( !$wp_filesystem->is_dir($to . $filename) ) {
  642. if ( !$wp_filesystem->mkdir($to . $filename, FS_CHMOD_DIR) )
  643. return new WP_Error('mkdir_failed', __('Could not create directory.'), $to . $filename);
  644. }
  645. $result = copy_dir($from . $filename, $to . $filename, $skip_list);
  646. if ( is_wp_error($result) )
  647. return $result;
  648. }
  649. }
  650. return true;
  651. }
  652. /**
  653. * Initialises and connects the WordPress Filesystem Abstraction classes.
  654. * This function will include the chosen transport and attempt connecting.
  655. *
  656. * Plugins may add extra transports, And force WordPress to use them by returning the filename via the 'filesystem_method_file' filter.
  657. *
  658. * @since 2.5.0
  659. *
  660. * @param array $args (optional) Connection args, These are passed directly to the WP_Filesystem_*() classes.
  661. * @param string $context (optional) Context for get_filesystem_method(), See function declaration for more information.
  662. * @return boolean false on failure, true on success
  663. */
  664. function WP_Filesystem( $args = false, $context = false ) {
  665. global $wp_filesystem;
  666. require_once(ABSPATH . 'wp-admin/includes/class-wp-filesystem-base.php');
  667. $method = get_filesystem_method($args, $context);
  668. if ( ! $method )
  669. return false;
  670. if ( ! class_exists("WP_Filesystem_$method") ) {
  671. $abstraction_file = apply_filters('filesystem_method_file', ABSPATH . 'wp-admin/includes/class-wp-filesystem-' . $method . '.php', $method);
  672. if ( ! file_exists($abstraction_file) )
  673. return;
  674. require_once($abstraction_file);
  675. }
  676. $method = "WP_Filesystem_$method";
  677. $wp_filesystem = new $method($args);
  678. //Define the timeouts for the connections. Only available after the construct is called to allow for per-transport overriding of the default.
  679. if ( ! defined('FS_CONNECT_TIMEOUT') )
  680. define('FS_CONNECT_TIMEOUT', 30);
  681. if ( ! defined('FS_TIMEOUT') )
  682. define('FS_TIMEOUT', 30);
  683. if ( is_wp_error($wp_filesystem->errors) && $wp_filesystem->errors->get_error_code() )
  684. return false;
  685. if ( !$wp_filesystem->connect() )
  686. return false; //There was an error connecting to the server.
  687. // Set the permission constants if not already set.
  688. if ( ! defined('FS_CHMOD_DIR') )
  689. define('FS_CHMOD_DIR', 0755 );
  690. if ( ! defined('FS_CHMOD_FILE') )
  691. define('FS_CHMOD_FILE', 0644 );
  692. return true;
  693. }
  694. /**
  695. * Determines which Filesystem Method to use.
  696. * The priority of the Transports are: Direct, SSH2, FTP PHP Extension, FTP Sockets (Via Sockets class, or fsockopen())
  697. *
  698. * Note that the return value of this function can be overridden in 2 ways
  699. * - By defining FS_METHOD in your <code>wp-config.php</code> file
  700. * - By using the filesystem_method filter
  701. * Valid values for these are: 'direct', 'ssh', 'ftpext' or 'ftpsockets'
  702. * Plugins may also define a custom transport handler, See the WP_Filesystem function for more information.
  703. *
  704. * @since 2.5.0
  705. *
  706. * @param array $args Connection details.
  707. * @param string $context Full path to the directory that is tested for being writable.
  708. * @return string The transport to use, see description for valid return values.
  709. */
  710. function get_filesystem_method($args = array(), $context = false) {
  711. $method = defined('FS_METHOD') ? FS_METHOD : false; //Please ensure that this is either 'direct', 'ssh', 'ftpext' or 'ftpsockets'
  712. if ( ! $method && function_exists('getmyuid') && function_exists('fileowner') ){
  713. if ( !$context )
  714. $context = WP_CONTENT_DIR;
  715. $context = trailingslashit($context);
  716. $temp_file_name = $context . 'temp-write-test-' . time();
  717. $temp_handle = @fopen($temp_file_name, 'w');
  718. if ( $temp_handle ) {
  719. if ( getmyuid() == @fileowner($temp_file_name) )
  720. $method = 'direct';
  721. @fclose($temp_handle);
  722. @unlink($temp_file_name);
  723. }
  724. }
  725. if ( ! $method && isset($args['connection_type']) && 'ssh' == $args['connection_type'] && extension_loaded('ssh2') && function_exists('stream_get_contents') ) $method = 'ssh2';
  726. if ( ! $method && extension_loaded('ftp') ) $method = 'ftpext';
  727. if ( ! $method && ( extension_loaded('sockets') || function_exists('fsockopen') ) ) $method = 'ftpsockets'; //Sockets: Socket extension; PHP Mode: FSockopen / fwrite / fread
  728. return apply_filters('filesystem_method', $method, $args);
  729. }
  730. /**
  731. * Displays a form to the user to request for their FTP/SSH details in order to connect to the filesystem.
  732. * All chosen/entered details are saved, Excluding the Password.
  733. *
  734. * Hostnames may be in the form of hostname:portnumber (eg: wordpress.org:2467) to specify an alternate FTP/SSH port.
  735. *
  736. * Plugins may override this form by returning true|false via the <code>request_filesystem_credentials</code> filter.
  737. *
  738. * @since 2.5.0
  739. *
  740. * @param string $form_post the URL to post the form to
  741. * @param string $type the chosen Filesystem method in use
  742. * @param boolean $error if the current request has failed to connect
  743. * @param string $context The directory which is needed access to, The write-test will be performed on this directory by get_filesystem_method()
  744. * @param string $extra_fields Extra POST fields which should be checked for to be included in the post.
  745. * @return boolean False on failure. True on success.
  746. */
  747. function request_filesystem_credentials($form_post, $type = '', $error = false, $context = false, $extra_fields = null) {
  748. $req_cred = apply_filters( 'request_filesystem_credentials', '', $form_post, $type, $error, $context, $extra_fields );
  749. if ( '' !== $req_cred )
  750. return $req_cred;
  751. if ( empty($type) )
  752. $type = get_filesystem_method(array(), $context);
  753. if ( 'direct' == $type )
  754. return true;
  755. if ( is_null( $extra_fields ) )
  756. $extra_fields = array( 'version', 'locale' );
  757. $credentials = get_option('ftp_credentials', array( 'hostname' => '', 'username' => ''));
  758. // 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)
  759. $credentials['hostname'] = defined('FTP_HOST') ? FTP_HOST : (!empty($_POST['hostname']) ? stripslashes($_POST['hostname']) : $credentials['hostname']);
  760. $credentials['username'] = defined('FTP_USER') ? FTP_USER : (!empty($_POST['username']) ? stripslashes($_POST['username']) : $credentials['username']);
  761. $credentials['password'] = defined('FTP_PASS') ? FTP_PASS : (!empty($_POST['password']) ? stripslashes($_POST['password']) : '');
  762. // Check to see if we are setting the public/private keys for ssh
  763. $credentials['public_key'] = defined('FTP_PUBKEY') ? FTP_PUBKEY : (!empty($_POST['public_key']) ? stripslashes($_POST['public_key']) : '');
  764. $credentials['private_key'] = defined('FTP_PRIKEY') ? FTP_PRIKEY : (!empty($_POST['private_key']) ? stripslashes($_POST['private_key']) : '');
  765. //sanitize the hostname, Some people might pass in odd-data:
  766. $credentials['hostname'] = preg_replace('|\w+://|', '', $credentials['hostname']); //Strip any schemes off
  767. if ( strpos($credentials['hostname'], ':') ) {
  768. list( $credentials['hostname'], $credentials['port'] ) = explode(':', $credentials['hostname'], 2);
  769. if ( ! is_numeric($credentials['port']) )
  770. unset($credentials['port']);
  771. } else {
  772. unset($credentials['port']);
  773. }
  774. if ( (defined('FTP_SSH') && FTP_SSH) || (defined('FS_METHOD') && 'ssh' == FS_METHOD) )
  775. $credentials['connection_type'] = 'ssh';
  776. else if ( (defined('FTP_SSL') && FTP_SSL) && 'ftpext' == $type ) //Only the FTP Extension understands SSL
  777. $credentials['connection_type'] = 'ftps';
  778. else if ( !empty($_POST['connection_type']) )
  779. $credentials['connection_type'] = stripslashes($_POST['connection_type']);
  780. else if ( !isset($credentials['connection_type']) ) //All else fails (And its not defaulted to something else saved), Default to FTP
  781. $credentials['connection_type'] = 'ftp';
  782. if ( ! $error &&
  783. (
  784. ( !empty($credentials['password']) && !empty($credentials['username']) && !empty($credentials['hostname']) ) ||
  785. ( 'ssh' == $credentials['connection_type'] && !empty($credentials['public_key']) && !empty($credentials['private_key']) )
  786. ) ) {
  787. $stored_credentials = $credentials;
  788. if ( !empty($stored_credentials['port']) ) //save port as part of hostname to simplify above code.
  789. $stored_credentials['hostname'] .= ':' . $stored_credentials['port'];
  790. unset($stored_credentials['password'], $stored_credentials['port'], $stored_credentials['private_key'], $stored_credentials['public_key']);
  791. update_option('ftp_credentials', $stored_credentials);
  792. return $credentials;
  793. }
  794. $hostname = '';
  795. $username = '';
  796. $password = '';
  797. $connection_type = '';
  798. if ( !empty($credentials) )
  799. extract($credentials, EXTR_OVERWRITE);
  800. if ( $error ) {
  801. $error_string = __('<strong>ERROR:</strong> There was an error connecting to the server, Please verify the settings are correct.');
  802. if ( is_wp_error($error) )
  803. $error_string = esc_html( $error->get_error_message() );
  804. echo '<div id="message" class="error"><p>' . $error_string . '</p></div>';
  805. }
  806. $types = array();
  807. if ( extension_loaded('ftp') || extension_loaded('sockets') || function_exists('fsockopen') )
  808. $types[ 'ftp' ] = __('FTP');
  809. if ( extension_loaded('ftp') ) //Only this supports FTPS
  810. $types[ 'ftps' ] = __('FTPS (SSL)');
  811. if ( extension_loaded('ssh2') && function_exists('stream_get_contents') )
  812. $types[ 'ssh' ] = __('SSH2');
  813. $types = apply_filters('fs_ftp_connection_types', $types, $credentials, $type, $error, $context);
  814. ?>
  815. <script type="text/javascript">
  816. <!--
  817. jQuery(function($){
  818. jQuery("#ssh").click(function () {
  819. jQuery("#ssh_keys").show();
  820. });
  821. jQuery("#ftp, #ftps").click(function () {
  822. jQuery("#ssh_keys").hide();
  823. });
  824. jQuery('form input[value=""]:first').focus();
  825. });
  826. -->
  827. </script>
  828. <form action="<?php echo $form_post ?>" method="post">
  829. <div class="wrap">
  830. <?php screen_icon(); ?>
  831. <h2><?php _e('Connection Information') ?></h2>
  832. <p><?php
  833. $label_user = __('Username');
  834. $label_pass = __('Password');
  835. _e('To perform the requested action, WordPress needs to access your web server.');
  836. echo ' ';
  837. if ( ( isset( $types['ftp'] ) || isset( $types['ftps'] ) ) ) {
  838. if ( isset( $types['ssh'] ) ) {
  839. _e('Please enter your FTP or SSH credentials to proceed.');
  840. $label_user = __('FTP/SSH Username');
  841. $label_pass = __('FTP/SSH Password');
  842. } else {
  843. _e('Please enter your FTP credentials to proceed.');
  844. $label_user = __('FTP Username');
  845. $label_pass = __('FTP Password');
  846. }
  847. echo ' ';
  848. }
  849. _e('If you do not remember your credentials, you should contact your web host.');
  850. ?></p>
  851. <table class="form-table">
  852. <tr valign="top">
  853. <th scope="row"><label for="hostname"><?php _e('Hostname') ?></label></th>
  854. <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>
  855. </tr>
  856. <tr valign="top">
  857. <th scope="row"><label for="username"><?php echo $label_user; ?></label></th>
  858. <td><input name="username" type="text" id="username" value="<?php echo esc_attr($username) ?>"<?php disabled( defined('FTP_USER') ); ?> size="40" /></td>
  859. </tr>
  860. <tr valign="top">
  861. <th scope="row"><label for="password"><?php echo $label_pass; ?></label></th>
  862. <td><input name="password" type="password" id="password" value="<?php if ( defined('FTP_PASS') ) echo '*****'; ?>"<?php disabled( defined('FTP_PASS') ); ?> size="40" /></td>
  863. </tr>
  864. <?php if ( isset($types['ssh']) ) : ?>
  865. <tr id="ssh_keys" valign="top" style="<?php if ( 'ssh' != $connection_type ) echo 'display:none' ?>">
  866. <th scope="row"><?php _e('Authentication Keys') ?>
  867. <div class="key-labels textright">
  868. <label for="public_key"><?php _e('Public Key:') ?></label ><br />
  869. <label for="private_key"><?php _e('Private Key:') ?></label>
  870. </div></th>
  871. <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" />
  872. <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>
  873. </tr>
  874. <?php endif; ?>
  875. <tr valign="top">
  876. <th scope="row"><?php _e('Connection Type') ?></th>
  877. <td>
  878. <fieldset><legend class="screen-reader-text"><span><?php _e('Connection Type') ?></span></legend>
  879. <?php
  880. $disabled = disabled( (defined('FTP_SSL') && FTP_SSL) || (defined('FTP_SSH') && FTP_SSH), true, false );
  881. foreach ( $types as $name => $text ) : ?>
  882. <label for="<?php echo esc_attr($name) ?>">
  883. <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; ?> />
  884. <?php echo $text ?>
  885. </label>
  886. <?php endforeach; ?>
  887. </fieldset>
  888. </td>
  889. </tr>
  890. </table>
  891. <?php
  892. foreach ( (array) $extra_fields as $field ) {
  893. if ( isset( $_POST[ $field ] ) )
  894. echo '<input type="hidden" name="' . esc_attr( $field ) . '" value="' . esc_attr( stripslashes( $_POST[ $field ] ) ) . '" />';
  895. }
  896. submit_button( __( 'Proceed' ), 'button', 'upgrade' );
  897. ?>
  898. </div>
  899. </form>
  900. <?php
  901. return false;
  902. }