/wp-admin/includes/file.php

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