PageRenderTime 55ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-admin/includes/file.php

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