PageRenderTime 45ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-admin/includes/file.php

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