PageRenderTime 72ms CodeModel.GetById 30ms RepoModel.GetById 1ms app.codeStats 0ms

/blog/wp-admin/includes/file.php

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