PageRenderTime 50ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-admin/includes/file.php

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