Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 

1297 lignes
51 KiB

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