PageRenderTime 89ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-admin/includes/file.php

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