PageRenderTime 64ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-admin/includes/file.php

https://github.com/markjaquith/WordPress
PHP | 2557 lines | 1453 code | 321 blank | 783 comment | 295 complexity | d3bb5d2bda3a3cbfd8257c93f3433ee5 MD5 | raw file
Possible License(s): GPL-2.0, AGPL-1.0, LGPL-2.1

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * Filesystem API: Top-level functionality
  4. *
  5. * Functions for reading, writing, modifying, and deleting files on the file system.
  6. * Includes functionality for theme-specific files as well as operations for uploading,
  7. * archiving, and rendering output when necessary.
  8. *
  9. * @package WordPress
  10. * @subpackage Filesystem
  11. * @since 2.3.0
  12. */
  13. /** The descriptions for theme files. */
  14. $wp_file_descriptions = array(
  15. 'functions.php' => __( 'Theme Functions' ),
  16. 'header.php' => __( 'Theme Header' ),
  17. 'footer.php' => __( 'Theme Footer' ),
  18. 'sidebar.php' => __( 'Sidebar' ),
  19. 'comments.php' => __( 'Comments' ),
  20. 'searchform.php' => __( 'Search Form' ),
  21. '404.php' => __( '404 Template' ),
  22. 'link.php' => __( 'Links Template' ),
  23. // Archives.
  24. 'index.php' => __( 'Main Index Template' ),
  25. 'archive.php' => __( 'Archives' ),
  26. 'author.php' => __( 'Author Template' ),
  27. 'taxonomy.php' => __( 'Taxonomy Template' ),
  28. 'category.php' => __( 'Category Template' ),
  29. 'tag.php' => __( 'Tag Template' ),
  30. 'home.php' => __( 'Posts Page' ),
  31. 'search.php' => __( 'Search Results' ),
  32. 'date.php' => __( 'Date Template' ),
  33. // Content.
  34. 'singular.php' => __( 'Singular Template' ),
  35. 'single.php' => __( 'Single Post' ),
  36. 'page.php' => __( 'Single Page' ),
  37. 'front-page.php' => __( 'Homepage' ),
  38. 'privacy-policy.php' => __( 'Privacy Policy 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. * Gets the description for standard WordPress theme files.
  67. *
  68. * @since 1.5.0
  69. *
  70. * @global array $wp_file_descriptions Theme file descriptions.
  71. * @global array $allowed_files List of allowed files.
  72. *
  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. $dirname = pathinfo( $file, PATHINFO_DIRNAME );
  80. $file_path = $allowed_files[ $file ];
  81. if ( isset( $wp_file_descriptions[ basename( $file ) ] ) && '.' === $dirname ) {
  82. return $wp_file_descriptions[ basename( $file ) ];
  83. } elseif ( file_exists( $file_path ) && is_file( $file_path ) ) {
  84. $template_data = implode( '', file( $file_path ) );
  85. if ( preg_match( '|Template Name:(.*)$|mi', $template_data, $name ) ) {
  86. /* translators: %s: Template name. */
  87. return sprintf( __( '%s Page Template' ), _cleanup_header_comment( $name[1] ) );
  88. }
  89. }
  90. return trim( basename( $file ) );
  91. }
  92. /**
  93. * Gets 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. *
  115. * The depth of the recursiveness can be controlled by the $levels param.
  116. *
  117. * @since 2.6.0
  118. * @since 4.9.0 Added the `$exclusions` parameter.
  119. *
  120. * @param string $folder Optional. Full path to folder. Default empty.
  121. * @param int $levels Optional. Levels of folders to follow, Default 100 (PHP Loop limit).
  122. * @param string[] $exclusions Optional. List of folders and files to skip.
  123. * @return string[]|false Array of files on success, false on failure.
  124. */
  125. function list_files( $folder = '', $levels = 100, $exclusions = array() ) {
  126. if ( empty( $folder ) ) {
  127. return false;
  128. }
  129. $folder = trailingslashit( $folder );
  130. if ( ! $levels ) {
  131. return false;
  132. }
  133. $files = array();
  134. $dir = @opendir( $folder );
  135. if ( $dir ) {
  136. while ( ( $file = readdir( $dir ) ) !== false ) {
  137. // Skip current and parent folder links.
  138. if ( in_array( $file, array( '.', '..' ), true ) ) {
  139. continue;
  140. }
  141. // Skip hidden and excluded files.
  142. if ( '.' === $file[0] || in_array( $file, $exclusions, true ) ) {
  143. continue;
  144. }
  145. if ( is_dir( $folder . $file ) ) {
  146. $files2 = list_files( $folder . $file, $levels - 1 );
  147. if ( $files2 ) {
  148. $files = array_merge( $files, $files2 );
  149. } else {
  150. $files[] = $folder . $file . '/';
  151. }
  152. } else {
  153. $files[] = $folder . $file;
  154. }
  155. }
  156. closedir( $dir );
  157. }
  158. return $files;
  159. }
  160. /**
  161. * Gets the list of file extensions that are editable in plugins.
  162. *
  163. * @since 4.9.0
  164. *
  165. * @param string $plugin Path to the plugin file relative to the plugins directory.
  166. * @return string[] Array of editable file extensions.
  167. */
  168. function wp_get_plugin_file_editable_extensions( $plugin ) {
  169. $default_types = array(
  170. 'bash',
  171. 'conf',
  172. 'css',
  173. 'diff',
  174. 'htm',
  175. 'html',
  176. 'http',
  177. 'inc',
  178. 'include',
  179. 'js',
  180. 'json',
  181. 'jsx',
  182. 'less',
  183. 'md',
  184. 'patch',
  185. 'php',
  186. 'php3',
  187. 'php4',
  188. 'php5',
  189. 'php7',
  190. 'phps',
  191. 'phtml',
  192. 'sass',
  193. 'scss',
  194. 'sh',
  195. 'sql',
  196. 'svg',
  197. 'text',
  198. 'txt',
  199. 'xml',
  200. 'yaml',
  201. 'yml',
  202. );
  203. /**
  204. * Filters the list of file types allowed for editing in the plugin file editor.
  205. *
  206. * @since 2.8.0
  207. * @since 4.9.0 Added the `$plugin` parameter.
  208. *
  209. * @param string[] $default_types An array of editable plugin file extensions.
  210. * @param string $plugin Path to the plugin file relative to the plugins directory.
  211. */
  212. $file_types = (array) apply_filters( 'editable_extensions', $default_types, $plugin );
  213. return $file_types;
  214. }
  215. /**
  216. * Gets the list of file extensions that are editable for a given theme.
  217. *
  218. * @since 4.9.0
  219. *
  220. * @param WP_Theme $theme Theme object.
  221. * @return string[] Array of editable file extensions.
  222. */
  223. function wp_get_theme_file_editable_extensions( $theme ) {
  224. $default_types = array(
  225. 'bash',
  226. 'conf',
  227. 'css',
  228. 'diff',
  229. 'htm',
  230. 'html',
  231. 'http',
  232. 'inc',
  233. 'include',
  234. 'js',
  235. 'json',
  236. 'jsx',
  237. 'less',
  238. 'md',
  239. 'patch',
  240. 'php',
  241. 'php3',
  242. 'php4',
  243. 'php5',
  244. 'php7',
  245. 'phps',
  246. 'phtml',
  247. 'sass',
  248. 'scss',
  249. 'sh',
  250. 'sql',
  251. 'svg',
  252. 'text',
  253. 'txt',
  254. 'xml',
  255. 'yaml',
  256. 'yml',
  257. );
  258. /**
  259. * Filters the list of file types allowed for editing in the theme file editor.
  260. *
  261. * @since 4.4.0
  262. *
  263. * @param string[] $default_types An array of editable theme file extensions.
  264. * @param WP_Theme $theme The active theme object.
  265. */
  266. $file_types = apply_filters( 'wp_theme_editor_filetypes', $default_types, $theme );
  267. // Ensure that default types are still there.
  268. return array_unique( array_merge( $file_types, $default_types ) );
  269. }
  270. /**
  271. * Prints file editor templates (for plugins and themes).
  272. *
  273. * @since 4.9.0
  274. */
  275. function wp_print_file_editor_templates() {
  276. ?>
  277. <script type="text/html" id="tmpl-wp-file-editor-notice">
  278. <div class="notice inline notice-{{ data.type || 'info' }} {{ data.alt ? 'notice-alt' : '' }} {{ data.dismissible ? 'is-dismissible' : '' }} {{ data.classes || '' }}">
  279. <# if ( 'php_error' === data.code ) { #>
  280. <p>
  281. <?php
  282. printf(
  283. /* translators: 1: Line number, 2: File path. */
  284. __( 'Your PHP code changes were rolled back due to an error on line %1$s of file %2$s. Please fix and try saving again.' ),
  285. '{{ data.line }}',
  286. '{{ data.file }}'
  287. );
  288. ?>
  289. </p>
  290. <pre>{{ data.message }}</pre>
  291. <# } else if ( 'file_not_writable' === data.code ) { #>
  292. <p>
  293. <?php
  294. printf(
  295. /* translators: %s: Documentation URL. */
  296. __( 'You need to make this file writable before you can save your changes. See <a href="%s">Changing File Permissions</a> for more information.' ),
  297. __( 'https://wordpress.org/support/article/changing-file-permissions/' )
  298. );
  299. ?>
  300. </p>
  301. <# } else { #>
  302. <p>{{ data.message || data.code }}</p>
  303. <# if ( 'lint_errors' === data.code ) { #>
  304. <p>
  305. <# var elementId = 'el-' + String( Math.random() ); #>
  306. <input id="{{ elementId }}" type="checkbox">
  307. <label for="{{ elementId }}"><?php _e( 'Update anyway, even though it might break your site?' ); ?></label>
  308. </p>
  309. <# } #>
  310. <# } #>
  311. <# if ( data.dismissible ) { #>
  312. <button type="button" class="notice-dismiss"><span class="screen-reader-text"><?php _e( 'Dismiss' ); ?></span></button>
  313. <# } #>
  314. </div>
  315. </script>
  316. <?php
  317. }
  318. /**
  319. * Attempts to edit a file for a theme or plugin.
  320. *
  321. * When editing a PHP file, loopback requests will be made to the admin and the homepage
  322. * to attempt to see if there is a fatal error introduced. If so, the PHP change will be
  323. * reverted.
  324. *
  325. * @since 4.9.0
  326. *
  327. * @param string[] $args {
  328. * Args. Note that all of the arg values are already unslashed. They are, however,
  329. * coming straight from `$_POST` and are not validated or sanitized in any way.
  330. *
  331. * @type string $file Relative path to file.
  332. * @type string $plugin Path to the plugin file relative to the plugins directory.
  333. * @type string $theme Theme being edited.
  334. * @type string $newcontent New content for the file.
  335. * @type string $nonce Nonce.
  336. * }
  337. * @return true|WP_Error True on success or `WP_Error` on failure.
  338. */
  339. function wp_edit_theme_plugin_file( $args ) {
  340. if ( empty( $args['file'] ) ) {
  341. return new WP_Error( 'missing_file' );
  342. }
  343. if ( 0 !== validate_file( $args['file'] ) ) {
  344. return new WP_Error( 'bad_file' );
  345. }
  346. if ( ! isset( $args['newcontent'] ) ) {
  347. return new WP_Error( 'missing_content' );
  348. }
  349. if ( ! isset( $args['nonce'] ) ) {
  350. return new WP_Error( 'missing_nonce' );
  351. }
  352. $file = $args['file'];
  353. $content = $args['newcontent'];
  354. $plugin = null;
  355. $theme = null;
  356. $real_file = null;
  357. if ( ! empty( $args['plugin'] ) ) {
  358. $plugin = $args['plugin'];
  359. if ( ! current_user_can( 'edit_plugins' ) ) {
  360. return new WP_Error( 'unauthorized', __( 'Sorry, you are not allowed to edit plugins for this site.' ) );
  361. }
  362. if ( ! wp_verify_nonce( $args['nonce'], 'edit-plugin_' . $file ) ) {
  363. return new WP_Error( 'nonce_failure' );
  364. }
  365. if ( ! array_key_exists( $plugin, get_plugins() ) ) {
  366. return new WP_Error( 'invalid_plugin' );
  367. }
  368. if ( 0 !== validate_file( $file, get_plugin_files( $plugin ) ) ) {
  369. return new WP_Error( 'bad_plugin_file_path', __( 'Sorry, that file cannot be edited.' ) );
  370. }
  371. $editable_extensions = wp_get_plugin_file_editable_extensions( $plugin );
  372. $real_file = WP_PLUGIN_DIR . '/' . $file;
  373. $is_active = in_array(
  374. $plugin,
  375. (array) get_option( 'active_plugins', array() ),
  376. true
  377. );
  378. } elseif ( ! empty( $args['theme'] ) ) {
  379. $stylesheet = $args['theme'];
  380. if ( 0 !== validate_file( $stylesheet ) ) {
  381. return new WP_Error( 'bad_theme_path' );
  382. }
  383. if ( ! current_user_can( 'edit_themes' ) ) {
  384. return new WP_Error( 'unauthorized', __( 'Sorry, you are not allowed to edit templates for this site.' ) );
  385. }
  386. $theme = wp_get_theme( $stylesheet );
  387. if ( ! $theme->exists() ) {
  388. return new WP_Error( 'non_existent_theme', __( 'The requested theme does not exist.' ) );
  389. }
  390. if ( ! wp_verify_nonce( $args['nonce'], 'edit-theme_' . $stylesheet . '_' . $file ) ) {
  391. return new WP_Error( 'nonce_failure' );
  392. }
  393. if ( $theme->errors() && 'theme_no_stylesheet' === $theme->errors()->get_error_code() ) {
  394. return new WP_Error(
  395. 'theme_no_stylesheet',
  396. __( 'The requested theme does not exist.' ) . ' ' . $theme->errors()->get_error_message()
  397. );
  398. }
  399. $editable_extensions = wp_get_theme_file_editable_extensions( $theme );
  400. $allowed_files = array();
  401. foreach ( $editable_extensions as $type ) {
  402. switch ( $type ) {
  403. case 'php':
  404. $allowed_files = array_merge( $allowed_files, $theme->get_files( 'php', -1 ) );
  405. break;
  406. case 'css':
  407. $style_files = $theme->get_files( 'css', -1 );
  408. $allowed_files['style.css'] = $style_files['style.css'];
  409. $allowed_files = array_merge( $allowed_files, $style_files );
  410. break;
  411. default:
  412. $allowed_files = array_merge( $allowed_files, $theme->get_files( $type, -1 ) );
  413. break;
  414. }
  415. }
  416. // Compare based on relative paths.
  417. if ( 0 !== validate_file( $file, array_keys( $allowed_files ) ) ) {
  418. return new WP_Error( 'disallowed_theme_file', __( 'Sorry, that file cannot be edited.' ) );
  419. }
  420. $real_file = $theme->get_stylesheet_directory() . '/' . $file;
  421. $is_active = ( get_stylesheet() === $stylesheet || get_template() === $stylesheet );
  422. } else {
  423. return new WP_Error( 'missing_theme_or_plugin' );
  424. }
  425. // Ensure file is real.
  426. if ( ! is_file( $real_file ) ) {
  427. return new WP_Error( 'file_does_not_exist', __( 'File does not exist! Please double check the name and try again.' ) );
  428. }
  429. // Ensure file extension is allowed.
  430. $extension = null;
  431. if ( preg_match( '/\.([^.]+)$/', $real_file, $matches ) ) {
  432. $extension = strtolower( $matches[1] );
  433. if ( ! in_array( $extension, $editable_extensions, true ) ) {
  434. return new WP_Error( 'illegal_file_type', __( 'Files of this type are not editable.' ) );
  435. }
  436. }
  437. $previous_content = file_get_contents( $real_file );
  438. if ( ! is_writable( $real_file ) ) {
  439. return new WP_Error( 'file_not_writable' );
  440. }
  441. $f = fopen( $real_file, 'w+' );
  442. if ( false === $f ) {
  443. return new WP_Error( 'file_not_writable' );
  444. }
  445. $written = fwrite( $f, $content );
  446. fclose( $f );
  447. if ( false === $written ) {
  448. return new WP_Error( 'unable_to_write', __( 'Unable to write to file.' ) );
  449. }
  450. wp_opcache_invalidate( $real_file, true );
  451. if ( $is_active && 'php' === $extension ) {
  452. $scrape_key = md5( rand() );
  453. $transient = 'scrape_key_' . $scrape_key;
  454. $scrape_nonce = (string) rand();
  455. // It shouldn't take more than 60 seconds to make the two loopback requests.
  456. set_transient( $transient, $scrape_nonce, 60 );
  457. $cookies = wp_unslash( $_COOKIE );
  458. $scrape_params = array(
  459. 'wp_scrape_key' => $scrape_key,
  460. 'wp_scrape_nonce' => $scrape_nonce,
  461. );
  462. $headers = array(
  463. 'Cache-Control' => 'no-cache',
  464. );
  465. /** This filter is documented in wp-includes/class-wp-http-streams.php */
  466. $sslverify = apply_filters( 'https_local_ssl_verify', false );
  467. // Include Basic auth in loopback requests.
  468. if ( isset( $_SERVER['PHP_AUTH_USER'] ) && isset( $_SERVER['PHP_AUTH_PW'] ) ) {
  469. $headers['Authorization'] = 'Basic ' . base64_encode( wp_unslash( $_SERVER['PHP_AUTH_USER'] ) . ':' . wp_unslash( $_SERVER['PHP_AUTH_PW'] ) );
  470. }
  471. // Make sure PHP process doesn't die before loopback requests complete.
  472. set_time_limit( 300 );
  473. // Time to wait for loopback requests to finish.
  474. $timeout = 100;
  475. $needle_start = "###### wp_scraping_result_start:$scrape_key ######";
  476. $needle_end = "###### wp_scraping_result_end:$scrape_key ######";
  477. // Attempt loopback request to editor to see if user just whitescreened themselves.
  478. if ( $plugin ) {
  479. $url = add_query_arg( compact( 'plugin', 'file' ), admin_url( 'plugin-editor.php' ) );
  480. } elseif ( isset( $stylesheet ) ) {
  481. $url = add_query_arg(
  482. array(
  483. 'theme' => $stylesheet,
  484. 'file' => $file,
  485. ),
  486. admin_url( 'theme-editor.php' )
  487. );
  488. } else {
  489. $url = admin_url();
  490. }
  491. if ( function_exists( 'session_status' ) && PHP_SESSION_ACTIVE === session_status() ) {
  492. // Close any active session to prevent HTTP requests from timing out
  493. // when attempting to connect back to the site.
  494. session_write_close();
  495. }
  496. $url = add_query_arg( $scrape_params, $url );
  497. $r = wp_remote_get( $url, compact( 'cookies', 'headers', 'timeout', 'sslverify' ) );
  498. $body = wp_remote_retrieve_body( $r );
  499. $scrape_result_position = strpos( $body, $needle_start );
  500. $loopback_request_failure = array(
  501. 'code' => 'loopback_request_failed',
  502. 'message' => __( 'Unable to communicate back with site to check for fatal errors, so the PHP change was reverted. You will need to upload your PHP file change by some other means, such as by using SFTP.' ),
  503. );
  504. $json_parse_failure = array(
  505. 'code' => 'json_parse_error',
  506. );
  507. $result = null;
  508. if ( false === $scrape_result_position ) {
  509. $result = $loopback_request_failure;
  510. } else {
  511. $error_output = substr( $body, $scrape_result_position + strlen( $needle_start ) );
  512. $error_output = substr( $error_output, 0, strpos( $error_output, $needle_end ) );
  513. $result = json_decode( trim( $error_output ), true );
  514. if ( empty( $result ) ) {
  515. $result = $json_parse_failure;
  516. }
  517. }
  518. // Try making request to homepage as well to see if visitors have been whitescreened.
  519. if ( true === $result ) {
  520. $url = home_url( '/' );
  521. $url = add_query_arg( $scrape_params, $url );
  522. $r = wp_remote_get( $url, compact( 'cookies', 'headers', 'timeout', 'sslverify' ) );
  523. $body = wp_remote_retrieve_body( $r );
  524. $scrape_result_position = strpos( $body, $needle_start );
  525. if ( false === $scrape_result_position ) {
  526. $result = $loopback_request_failure;
  527. } else {
  528. $error_output = substr( $body, $scrape_result_position + strlen( $needle_start ) );
  529. $error_output = substr( $error_output, 0, strpos( $error_output, $needle_end ) );
  530. $result = json_decode( trim( $error_output ), true );
  531. if ( empty( $result ) ) {
  532. $result = $json_parse_failure;
  533. }
  534. }
  535. }
  536. delete_transient( $transient );
  537. if ( true !== $result ) {
  538. // Roll-back file change.
  539. file_put_contents( $real_file, $previous_content );
  540. wp_opcache_invalidate( $real_file, true );
  541. if ( ! isset( $result['message'] ) ) {
  542. $message = __( 'Something went wrong.' );
  543. } else {
  544. $message = $result['message'];
  545. unset( $result['message'] );
  546. }
  547. return new WP_Error( 'php_error', $message, $result );
  548. }
  549. }
  550. if ( $theme instanceof WP_Theme ) {
  551. $theme->cache_delete();
  552. }
  553. return true;
  554. }
  555. /**
  556. * Returns a filename of a temporary unique file.
  557. *
  558. * Please note that the calling function must unlink() this itself.
  559. *
  560. * The filename is based off the passed parameter or defaults to the current unix timestamp,
  561. * while the directory can either be passed as well, or by leaving it blank, default to a writable
  562. * temporary directory.
  563. *
  564. * @since 2.6.0
  565. *
  566. * @param string $filename Optional. Filename to base the Unique file off. Default empty.
  567. * @param string $dir Optional. Directory to store the file in. Default empty.
  568. * @return string A writable filename.
  569. */
  570. function wp_tempnam( $filename = '', $dir = '' ) {
  571. if ( empty( $dir ) ) {
  572. $dir = get_temp_dir();
  573. }
  574. if ( empty( $filename ) || in_array( $filename, array( '.', '/', '\\' ), true ) ) {
  575. $filename = uniqid();
  576. }
  577. // Use the basename of the given file without the extension as the name for the temporary directory.
  578. $temp_filename = basename( $filename );
  579. $temp_filename = preg_replace( '|\.[^.]*$|', '', $temp_filename );
  580. // If the folder is falsey, use its parent directory name instead.
  581. if ( ! $temp_filename ) {
  582. return wp_tempnam( dirname( $filename ), $dir );
  583. }
  584. // Suffix some random data to avoid filename conflicts.
  585. $temp_filename .= '-' . wp_generate_password( 6, false );
  586. $temp_filename .= '.tmp';
  587. $temp_filename = $dir . wp_unique_filename( $dir, $temp_filename );
  588. $fp = @fopen( $temp_filename, 'x' );
  589. if ( ! $fp && is_writable( $dir ) && file_exists( $temp_filename ) ) {
  590. return wp_tempnam( $filename, $dir );
  591. }
  592. if ( $fp ) {
  593. fclose( $fp );
  594. }
  595. return $temp_filename;
  596. }
  597. /**
  598. * Makes sure that the file that was requested to be edited is allowed to be edited.
  599. *
  600. * Function will die if you are not allowed to edit the file.
  601. *
  602. * @since 1.5.0
  603. *
  604. * @param string $file File the user is attempting to edit.
  605. * @param string[] $allowed_files Optional. Array of allowed files to edit.
  606. * `$file` must match an entry exactly.
  607. * @return string|void Returns the file name on success, dies on failure.
  608. */
  609. function validate_file_to_edit( $file, $allowed_files = array() ) {
  610. $code = validate_file( $file, $allowed_files );
  611. if ( ! $code ) {
  612. return $file;
  613. }
  614. switch ( $code ) {
  615. case 1:
  616. wp_die( __( 'Sorry, that file cannot be edited.' ) );
  617. // case 2 :
  618. // wp_die( __('Sorry, can&#8217;t call files with their real path.' ));
  619. case 3:
  620. wp_die( __( 'Sorry, that file cannot be edited.' ) );
  621. }
  622. }
  623. /**
  624. * Handles PHP uploads in WordPress.
  625. *
  626. * Sanitizes file names, checks extensions for mime type, and moves the file
  627. * to the appropriate directory within the uploads directory.
  628. *
  629. * @access private
  630. * @since 4.0.0
  631. *
  632. * @see wp_handle_upload_error
  633. *
  634. * @param array $file {
  635. * Reference to a single element from `$_FILES`. Call the function once for each uploaded file.
  636. *
  637. * @type string $name The original name of the file on the client machine.
  638. * @type string $type The mime type of the file, if the browser provided this information.
  639. * @type string $tmp_name The temporary filename of the file in which the uploaded file was stored on the server.
  640. * @type int $size The size, in bytes, of the uploaded file.
  641. * @type int $error The error code associated with this file upload.
  642. * }
  643. * @param array|false $overrides {
  644. * An array of override parameters for this file, or boolean false if none are provided.
  645. *
  646. * @type callable $upload_error_handler Function to call when there is an error during the upload process.
  647. * @see wp_handle_upload_error().
  648. * @type callable $unique_filename_callback Function to call when determining a unique file name for the file.
  649. * @see wp_unique_filename().
  650. * @type string[] $upload_error_strings The strings that describe the error indicated in
  651. * `$_FILES[{form field}]['error']`.
  652. * @type bool $test_form Whether to test that the `$_POST['action']` parameter is as expected.
  653. * @type bool $test_size Whether to test that the file size is greater than zero bytes.
  654. * @type bool $test_type Whether to test that the mime type of the file is as expected.
  655. * @type string[] $mimes Array of allowed mime types keyed by their file extension regex.
  656. * }
  657. * @param string $time Time formatted in 'yyyy/mm'.
  658. * @param string $action Expected value for `$_POST['action']`.
  659. * @return array {
  660. * On success, returns an associative array of file attributes.
  661. * On failure, returns `$overrides['upload_error_handler']( &$file, $message )`
  662. * or `array( 'error' => $message )`.
  663. *
  664. * @type string $file Filename of the newly-uploaded file.
  665. * @type string $url URL of the newly-uploaded file.
  666. * @type string $type Mime type of the newly-uploaded file.
  667. * }
  668. */
  669. function _wp_handle_upload( &$file, $overrides, $time, $action ) {
  670. // The default error handler.
  671. if ( ! function_exists( 'wp_handle_upload_error' ) ) {
  672. function wp_handle_upload_error( &$file, $message ) {
  673. return array( 'error' => $message );
  674. }
  675. }
  676. /**
  677. * Filters the data for a file before it is uploaded to WordPress.
  678. *
  679. * The dynamic portion of the hook name, `$action`, refers to the post action.
  680. *
  681. * Possible hook names include:
  682. *
  683. * - `wp_handle_sideload_prefilter`
  684. * - `wp_handle_upload_prefilter`
  685. *
  686. * @since 2.9.0 as 'wp_handle_upload_prefilter'.
  687. * @since 4.0.0 Converted to a dynamic hook with `$action`.
  688. *
  689. * @param array $file {
  690. * Reference to a single element from `$_FILES`.
  691. *
  692. * @type string $name The original name of the file on the client machine.
  693. * @type string $type The mime type of the file, if the browser provided this information.
  694. * @type string $tmp_name The temporary filename of the file in which the uploaded file was stored on the server.
  695. * @type int $size The size, in bytes, of the uploaded file.
  696. * @type int $error The error code associated with this file upload.
  697. * }
  698. */
  699. $file = apply_filters( "{$action}_prefilter", $file );
  700. /**
  701. * Filters the override parameters for a file before it is uploaded to WordPress.
  702. *
  703. * The dynamic portion of the hook name, `$action`, refers to the post action.
  704. *
  705. * Possible hook names include:
  706. *
  707. * - `wp_handle_sideload_overrides`
  708. * - `wp_handle_upload_overrides`
  709. *
  710. * @since 5.7.0
  711. *
  712. * @param array|false $overrides An array of override parameters for this file. Boolean false if none are
  713. * provided. @see _wp_handle_upload().
  714. * @param array $file {
  715. * Reference to a single element from `$_FILES`.
  716. *
  717. * @type string $name The original name of the file on the client machine.
  718. * @type string $type The mime type of the file, if the browser provided this information.
  719. * @type string $tmp_name The temporary filename of the file in which the uploaded file was stored on the server.
  720. * @type int $size The size, in bytes, of the uploaded file.
  721. * @type int $error The error code associated with this file upload.
  722. * }
  723. */
  724. $overrides = apply_filters( "{$action}_overrides", $overrides, $file );
  725. // You may define your own function and pass the name in $overrides['upload_error_handler'].
  726. $upload_error_handler = 'wp_handle_upload_error';
  727. if ( isset( $overrides['upload_error_handler'] ) ) {
  728. $upload_error_handler = $overrides['upload_error_handler'];
  729. }
  730. // You may have had one or more 'wp_handle_upload_prefilter' functions error out the file. Handle that gracefully.
  731. if ( isset( $file['error'] ) && ! is_numeric( $file['error'] ) && $file['error'] ) {
  732. return call_user_func_array( $upload_error_handler, array( &$file, $file['error'] ) );
  733. }
  734. // Install user overrides. Did we mention that this voids your warranty?
  735. // You may define your own function and pass the name in $overrides['unique_filename_callback'].
  736. $unique_filename_callback = null;
  737. if ( isset( $overrides['unique_filename_callback'] ) ) {
  738. $unique_filename_callback = $overrides['unique_filename_callback'];
  739. }
  740. /*
  741. * This may not have originally been intended to be overridable,
  742. * but historically has been.
  743. */
  744. if ( isset( $overrides['upload_error_strings'] ) ) {
  745. $upload_error_strings = $overrides['upload_error_strings'];
  746. } else {
  747. // Courtesy of php.net, the strings that describe the error indicated in $_FILES[{form field}]['error'].
  748. $upload_error_strings = array(
  749. false,
  750. sprintf(
  751. /* translators: 1: upload_max_filesize, 2: php.ini */
  752. __( 'The uploaded file exceeds the %1$s directive in %2$s.' ),
  753. 'upload_max_filesize',
  754. 'php.ini'
  755. ),
  756. sprintf(
  757. /* translators: %s: MAX_FILE_SIZE */
  758. __( 'The uploaded file exceeds the %s directive that was specified in the HTML form.' ),
  759. 'MAX_FILE_SIZE'
  760. ),
  761. __( 'The uploaded file was only partially uploaded.' ),
  762. __( 'No file was uploaded.' ),
  763. '',
  764. __( 'Missing a temporary folder.' ),
  765. __( 'Failed to write file to disk.' ),
  766. __( 'File upload stopped by extension.' ),
  767. );
  768. }
  769. // All tests are on by default. Most can be turned off by $overrides[{test_name}] = false;
  770. $test_form = isset( $overrides['test_form'] ) ? $overrides['test_form'] : true;
  771. $test_size = isset( $overrides['test_size'] ) ? $overrides['test_size'] : true;
  772. // If you override this, you must provide $ext and $type!!
  773. $test_type = isset( $overrides['test_type'] ) ? $overrides['test_type'] : true;
  774. $mimes = isset( $overrides['mimes'] ) ? $overrides['mimes'] : false;
  775. // A correct form post will pass this test.
  776. if ( $test_form && ( ! isset( $_POST['action'] ) || $_POST['action'] !== $action ) ) {
  777. return call_user_func_array( $upload_error_handler, array( &$file, __( 'Invalid form submission.' ) ) );
  778. }
  779. // A successful upload will pass this test. It makes no sense to override this one.
  780. if ( isset( $file['error'] ) && $file['error'] > 0 ) {
  781. return call_user_func_array( $upload_error_handler, array( &$file, $upload_error_strings[ $file['error'] ] ) );
  782. }
  783. // A properly uploaded file will pass this test. There should be no reason to override this one.
  784. $test_uploaded_file = 'wp_handle_upload' === $action ? is_uploaded_file( $file['tmp_name'] ) : @is_readable( $file['tmp_name'] );
  785. if ( ! $test_uploaded_file ) {
  786. return call_user_func_array( $upload_error_handler, array( &$file, __( 'Specified file failed upload test.' ) ) );
  787. }
  788. $test_file_size = 'wp_handle_upload' === $action ? $file['size'] : filesize( $file['tmp_name'] );
  789. // A non-empty file will pass this test.
  790. if ( $test_size && ! ( $test_file_size > 0 ) ) {
  791. if ( is_multisite() ) {
  792. $error_msg = __( 'File is empty. Please upload something more substantial.' );
  793. } else {
  794. $error_msg = sprintf(
  795. /* translators: 1: php.ini, 2: post_max_size, 3: upload_max_filesize */
  796. __( 'File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your %1$s file or by %2$s being defined as smaller than %3$s in %1$s.' ),
  797. 'php.ini',
  798. 'post_max_size',
  799. 'upload_max_filesize'
  800. );
  801. }
  802. return call_user_func_array( $upload_error_handler, array( &$file, $error_msg ) );
  803. }
  804. // A correct MIME type will pass this test. Override $mimes or use the upload_mimes filter.
  805. if ( $test_type ) {
  806. $wp_filetype = wp_check_filetype_and_ext( $file['tmp_name'], $file['name'], $mimes );
  807. $ext = empty( $wp_filetype['ext'] ) ? '' : $wp_filetype['ext'];
  808. $type = empty( $wp_filetype['type'] ) ? '' : $wp_filetype['type'];
  809. $proper_filename = empty( $wp_filetype['proper_filename'] ) ? '' : $wp_filetype['proper_filename'];
  810. // Check to see if wp_check_filetype_and_ext() determined the filename was incorrect.
  811. if ( $proper_filename ) {
  812. $file['name'] = $proper_filename;
  813. }
  814. if ( ( ! $type || ! $ext ) && ! current_user_can( 'unfiltered_upload' ) ) {
  815. return call_user_func_array( $upload_error_handler, array( &$file, __( 'Sorry, you are not allowed to upload this file type.' ) ) );
  816. }
  817. if ( ! $type ) {
  818. $type = $file['type'];
  819. }
  820. } else {
  821. $type = '';
  822. }
  823. /*
  824. * A writable uploads dir will pass this test. Again, there's no point
  825. * overriding this one.
  826. */
  827. $uploads = wp_upload_dir( $time );
  828. if ( ! ( $uploads && false === $uploads['error'] ) ) {
  829. return call_user_func_array( $upload_error_handler, array( &$file, $uploads['error'] ) );
  830. }
  831. $filename = wp_unique_filename( $uploads['path'], $file['name'], $unique_filename_callback );
  832. // Move the file to the uploads dir.
  833. $new_file = $uploads['path'] . "/$filename";
  834. /**
  835. * Filters whether to short-circuit moving the uploaded file after passing all checks.
  836. *
  837. * If a non-null value is returned from the filter, moving the file and any related
  838. * error reporting will be completely skipped.
  839. *
  840. * @since 4.9.0
  841. *
  842. * @param mixed $move_new_file If null (default) move the file after the upload.
  843. * @param array $file {
  844. * Reference to a single element from `$_FILES`.
  845. *
  846. * @type string $name The original name of the file on the client machine.
  847. * @type string $type The mime type of the file, if the browser provided this information.
  848. * @type string $tmp_name The temporary filename of the file in which the uploaded file was stored on the server.
  849. * @type int $size The size, in bytes, of the uploaded file.
  850. * @type int $error The error code associated with this file upload.
  851. * }
  852. * @param string $new_file Filename of the newly-uploaded file.
  853. * @param string $type Mime type of the newly-uploaded file.
  854. */
  855. $move_new_file = apply_filters( 'pre_move_uploaded_file', null, $file, $new_file, $type );
  856. if ( null === $move_new_file ) {
  857. if ( 'wp_handle_upload' === $action ) {
  858. $move_new_file = @move_uploaded_file( $file['tmp_name'], $new_file );
  859. } else {
  860. // Use copy and unlink because rename breaks streams.
  861. // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
  862. $move_new_file = @copy( $file['tmp_name'], $new_file );
  863. unlink( $file['tmp_name'] );
  864. }
  865. if ( false === $move_new_file ) {
  866. if ( 0 === strpos( $uploads['basedir'], ABSPATH ) ) {
  867. $error_path = str_replace( ABSPATH, '', $uploads['basedir'] ) . $uploads['subdir'];
  868. } else {
  869. $error_path = basename( $uploads['basedir'] ) . $uploads['subdir'];
  870. }
  871. return $upload_error_handler(
  872. $file,
  873. sprintf(
  874. /* translators: %s: Destination file path. */
  875. __( 'The uploaded file could not be moved to %s.' ),
  876. $error_path
  877. )
  878. );
  879. }
  880. }
  881. // Set correct file permissions.
  882. $stat = stat( dirname( $new_file ) );
  883. $perms = $stat['mode'] & 0000666;
  884. chmod( $new_file, $perms );
  885. // Compute the URL.
  886. $url = $uploads['url'] . "/$filename";
  887. if ( is_multisite() ) {
  888. clean_dirsize_cache( $new_file );
  889. }
  890. /**
  891. * Filters the data array for the uploaded file.
  892. *
  893. * @since 2.1.0
  894. *
  895. * @param array $upload {
  896. * Array of upload data.
  897. *
  898. * @type string $file Filename of the newly-uploaded file.
  899. * @type string $url URL of the newly-uploaded file.
  900. * @type string $type Mime type of the newly-uploaded file.
  901. * }
  902. * @param string $context The type of upload action. Values include 'upload' or 'sideload'.
  903. */
  904. return apply_filters(
  905. 'wp_handle_upload',
  906. array(
  907. 'file' => $new_file,
  908. 'url' => $url,
  909. 'type' => $type,
  910. ),
  911. 'wp_handle_sideload' === $action ? 'sideload' : 'upload'
  912. );
  913. }
  914. /**
  915. * Wrapper for _wp_handle_upload().
  916. *
  917. * Passes the {@see 'wp_handle_upload'} action.
  918. *
  919. * @since 2.0.0
  920. *
  921. * @see _wp_handle_upload()
  922. *
  923. * @param array $file Reference to a single element of `$_FILES`.
  924. * Call the function once for each uploaded file.
  925. * See _wp_handle_upload() for accepted values.
  926. * @param array|false $overrides Optional. An associative array of names => values
  927. * to override default variables. Default false.
  928. * See _wp_handle_upload() for accepted values.
  929. * @param string $time Optional. Time formatted in 'yyyy/mm'. Default null.
  930. * @return array See _wp_handle_upload() for return value.
  931. */
  932. function wp_handle_upload( &$file, $overrides = false, $time = null ) {
  933. /*
  934. * $_POST['action'] must be set and its value must equal $overrides['action']
  935. * or this:
  936. */
  937. $action = 'wp_handle_upload';
  938. if ( isset( $overrides['action'] ) ) {
  939. $action = $overrides['action'];
  940. }
  941. return _wp_handle_upload( $file, $overrides, $time, $action );
  942. }
  943. /**
  944. * Wrapper for _wp_handle_upload().
  945. *
  946. * Passes the {@see 'wp_handle_sideload'} action.
  947. *
  948. * @since 2.6.0
  949. *
  950. * @see _wp_handle_upload()
  951. *
  952. * @param array $file Reference to a single element of `$_FILES`.
  953. * Call the function once for each uploaded file.
  954. * See _wp_handle_upload() for accepted values.
  955. * @param array|false $overrides Optional. An associative array of names => values
  956. * to override default variables. Default false.
  957. * See _wp_handle_upload() for accepted values.
  958. * @param string $time Optional. Time formatted in 'yyyy/mm'. Default null.
  959. * @return array See _wp_handle_upload() for return value.
  960. */
  961. function wp_handle_sideload( &$file, $overrides = false, $time = null ) {
  962. /*
  963. * $_POST['action'] must be set and its value must equal $overrides['action']
  964. * or this:
  965. */
  966. $action = 'wp_handle_sideload';
  967. if ( isset( $overrides['action'] ) ) {
  968. $action = $overrides['action'];
  969. }
  970. return _wp_handle_upload( $file, $overrides, $time, $action );
  971. }
  972. /**
  973. * Downloads a URL to a local temporary file using the WordPress HTTP API.
  974. *
  975. * Please note that the calling function must unlink() the file.
  976. *
  977. * @since 2.5.0
  978. * @since 5.2.0 Signature Verification with SoftFail was added.
  979. * @since 5.9.0 Support for Content-Disposition filename was added.
  980. *
  981. * @param string $url The URL of the file to download.
  982. * @param int $timeout The timeout for the request to download the file.
  983. * Default 300 seconds.
  984. * @param bool $signature_verification Whether to perform Signature Verification.
  985. * Default false.
  986. * @return string|WP_Error Filename on success, WP_Error on failure.
  987. */
  988. function download_url( $url, $timeout = 300, $signature_verification = false ) {
  989. // WARNING: The file is not automatically deleted, the script must unlink() the file.
  990. if ( ! $url ) {
  991. return new WP_Error( 'http_no_url', __( 'Invalid URL Provided.' ) );
  992. }
  993. $url_path = parse_url( $url, PHP_URL_PATH );
  994. $url_filename = '';
  995. if ( is_string( $url_path ) && '' !== $url_path ) {
  996. $url_filename = basename( $url_path );
  997. }
  998. $tmpfname = wp_tempnam( $url_filename );
  999. if ( ! $tmpfname ) {
  1000. return new WP_Error( 'http_no_file', __( 'Could not create temporary file.' ) );
  1001. }
  1002. $response = wp_safe_remote_get(
  1003. $url,
  1004. array(
  1005. 'timeout' => $timeout,
  1006. 'stream' => true,
  1007. 'filename' => $tmpfname,
  1008. )
  1009. );
  1010. if ( is_wp_error( $response ) ) {
  1011. unlink( $tmpfname );
  1012. return $response;
  1013. }
  1014. $response_code = wp_remote_retrieve_response_code( $response );
  1015. if ( 200 !== $response_code ) {
  1016. $data = array(
  1017. 'code' => $response_code,
  1018. );
  1019. // Retrieve a sample of the response body for debugging purposes.
  1020. $tmpf = fopen( $tmpfname, 'rb' );
  1021. if ( $tmpf ) {
  1022. /**
  1023. * Filters the maximum error response body size in `download_url()`.
  1024. *
  1025. * @since 5.1.0
  1026. *
  1027. * @see download_url()
  1028. *
  1029. * @param int $size The maximum error response body size. Default 1 KB.
  1030. */
  1031. $response_size = apply_filters( 'download_url_error_max_body_size', KB_IN_BYTES );
  1032. $data['body'] = fread( $tmpf, $response_size );
  1033. fclose( $tmpf );
  1034. }
  1035. unlink( $tmpfname );
  1036. return new WP_Error( 'http_404', trim( wp_remote_retrieve_response_message( $response ) ), $data );
  1037. }
  1038. $content_disposition = wp_remote_retrieve_header( $response, 'content-disposition' );
  1039. if ( $content_disposition ) {
  1040. $content_disposition = strtolower( $content_disposition );
  1041. if ( 0 === strpos( $content_disposition, 'attachment; filename=' ) ) {
  1042. $tmpfname_disposition = sanitize_file_name( substr( $content_disposition, 21 ) );
  1043. } else {
  1044. $tmpfname_disposition = '';
  1045. }
  1046. // Potential file name must be valid string.
  1047. if ( $tmpfname_disposition && is_string( $tmpfname_disposition )
  1048. && ( 0 === validate_file( $tmpfname_disposition ) )
  1049. ) {
  1050. $tmpfname_disposition = dirname( $tmpfname ) . '/' . $tmpfname_disposition;
  1051. if ( rename( $tmpfname, $tmpfname_disposition ) ) {
  1052. $tmpfname = $tmpfname_disposition;
  1053. }
  1054. if ( ( $tmpfname !== $tmpfname_disposition ) && file_exists( $tmpfname_disposition ) ) {
  1055. unlink( $tmpfname_disposition );
  1056. }
  1057. }
  1058. }
  1059. $content_md5 = wp_remote_retrieve_header( $response, 'content-md5' );
  1060. if ( $content_md5 ) {
  1061. $md5_check = verify_file_md5( $tmpfname, $content_md5 );
  1062. if ( is_wp_error( $md5_check ) ) {
  1063. unlink( $tmpfname );
  1064. return $md5_check;
  1065. }
  1066. }
  1067. // If the caller expects signature verification to occur, check to see if this URL supports it.
  1068. if ( $signature_verification ) {
  1069. /**
  1070. * Filters the list of hosts which should have Signature Verification attempted on.
  1071. *
  1072. * @since 5.2.0
  1073. *
  1074. * @param string[] $hostnames List of hostnames.
  1075. */
  1076. $signed_hostnames = apply_filters( 'wp_signature_hosts', array( 'wordpress.org', 'downloads.wordpress.org', 's.w.org' ) );
  1077. $signature_verification = in_array( parse_url( $url, PHP_URL_HOST ), $signed_hostnames, true );
  1078. }
  1079. // Perform signature valiation if supported.
  1080. if ( $signature_verification ) {
  1081. $signature = wp_remote_retrieve_header( $response, 'x-content-signature' );
  1082. if ( ! $signature ) {
  1083. // Retrieve signatures from a file if the header wasn't included.
  1084. // WordPress.org stores signatures at $package_url.sig.
  1085. $signature_url = false;
  1086. if ( is_string( $url_path ) && ( '.zip' === substr( $url_path, -4 ) || '.tar.gz' === substr( $url_path, -7 ) ) ) {
  1087. $signature_url = str_replace( $url_path, $url_path . '.sig', $url );
  1088. }
  1089. /**
  1090. * Filters the URL where the signature for a file is located.
  1091. *
  1092. * @since 5.2.0
  1093. *
  1094. * @param false|string $signature_url The URL where signatures can be found for a file, or false if none are known.
  1095. * @param string $url The URL being verified.
  1096. */
  1097. $signature_url = apply_filters( 'wp_signature_url', $signature_url, $url );
  1098. if ( $signature_url ) {
  1099. $signature_request = wp_safe_remote_get(
  1100. $signature_url,
  1101. array(
  1102. 'limit_response_size' => 10 * KB_IN_BYTES, // 10KB should be large enough for quite a few signatures.
  1103. )
  1104. );
  1105. if ( ! is_wp_error( $signature_request ) && 200 === wp_remote_retrieve_response_code( $signature_request ) ) {
  1106. $signature = explode( "\n", wp_remote_retrieve_body( $signature_request ) );
  1107. }
  1108. }
  1109. }
  1110. // Perform the checks.
  1111. $signature_verification = verify_file_signature( $tmpfname, $signature, $url_filename );
  1112. }
  1113. if ( is_wp_error( $signature_verification ) ) {
  1114. if (
  1115. /**
  1116. * Filters whether Signature Verification failures should be allowed to soft fail.
  1117. *
  1118. * WARNING: This may be removed from a future release.
  1119. *
  1120. * @since 5.2.0
  1121. *
  1122. * @param bool $signature_softfail If a softfail is allowed.
  1123. * @param string $url The url being accessed.
  1124. */
  1125. apply_filters( 'wp_signature_softfail', true, $url )
  1126. ) {
  1127. $signature_verification->add_data( $tmpfname, 'softfail-filename' );
  1128. } else {
  1129. // Hard-fail.
  1130. unlink( $tmpfname );
  1131. }
  1132. return $signature_verification;
  1133. }
  1134. return $tmpfname;
  1135. }
  1136. /**
  1137. * Calculates and compares the MD5 of a file to its expected value.
  1138. *
  1139. * @since 3.7.0
  1140. *
  1141. * @param string $filename The filename to check the MD5 of.
  1142. * @param string $expected_md5 The expected MD5 of the file, either a base64-encoded raw md5,
  1143. * or a hex-encoded md5.
  1144. * @return bool|WP_Error True on success, false when the MD5 format is unknown/unexpected,
  1145. * WP_Error on failure.
  1146. */
  1147. function verify_file_md5( $filename, $expected_md5 ) {
  1148. if ( 32 === strlen( $expected_md5 ) ) {
  1149. $expected_raw_md5 = pack( 'H*', $expected_md5 );
  1150. } elseif ( 24 === strlen( $expected_md5 ) ) {
  1151. $expected_raw_md5 = base64_decode( $expected_md5 );
  1152. } else {
  1153. return false; // Unknown format.
  1154. }
  1155. $file_md5 = md5_file( $filename, true );
  1156. if ( $file_md5 === $expected_raw_md5 ) {
  1157. return true;
  1158. }
  1159. return new WP_Error(
  1160. 'md5_mismatch',
  1161. sprintf(
  1162. /* translators: 1: File checksum, 2: Expected checksum value. */
  1163. __( 'The checksum of the file (%1$s) does not match the expected checksum value (%2$s).' ),
  1164. bin2hex( $file_md5 ),
  1165. bin2hex( $expected_raw_md5 )
  1166. )
  1167. );
  1168. }
  1169. /**
  1170. * Verifies the contents of a file against its ED25519 signature.
  1171. *
  1172. * @since 5.2.0
  1173. *
  1174. * @param string $filename The file to validate.
  1175. * @param string|array $signatures A Signature provided for the file.
  1176. * @param string|false $filename_for_errors Optional. A friendly filename for errors.
  1177. * @return bool|WP_Error True on success, false if verification not attempted,
  1178. * or WP_Error describing an error condition.
  1179. */
  1180. function verify_file_signature( $filename, $signatures, $filename_for_errors = false ) {
  1181. if ( ! $filename_for_errors ) {
  1182. $filename_for_errors = wp_basename( $filename );
  1183. }
  1184. // Check we can process signatures.
  1185. if ( ! function_exists( 'sodium_crypto_sign_verify_detached' ) || ! in_array( 'sha384', array_map( 'strtolower', hash_algos() ), true ) ) {
  1186. return new WP_Error(
  1187. 'signature_verification_unsupported',
  1188. sprintf(
  1189. /* translators: %s: The filename of the package. */
  1190. __( 'The authenticity of %s could not be verified as signature verification is unavailable on this system.' ),
  1191. '<span class="code">' . esc_html( $filename_for_errors ) . '</span>'
  1192. ),
  1193. ( ! function_exists( 'sodium_crypto_sign_verify_detached' ) ? 'sodium_crypto_sign_verify_detached' : 'sha384' )
  1194. );
  1195. }
  1196. // Check for a edge-case affecting PHP Maths abilities.
  1197. if (
  1198. ! extension_loaded( 'sodium' ) &&
  1199. in_array( PHP_VERSION_ID, array( 70200, 70201, 70202 ), true ) &&
  1200. extension_loaded( 'opcache' )
  1201. ) {
  1202. // Sodium_Compat isn't compatible with PHP 7.2.0~7.2.2 due to a bug in the PHP Opcache extension, bail early as it'll fail.
  1203. // https://bugs.php.net/bug.php?id=75938
  1204. return new WP_Error(
  1205. 'signature_verification_unsupported',
  1206. sprintf(
  1207. /* translators: %s: The filename of the package. */
  1208. __( 'The authenticity of %s could not be verified as signature verification is unavailable on this system.' ),
  1209. '<span class="code">' . esc_html( $filename_for_errors ) . '</span>'
  1210. ),
  1211. array(
  1212. 'php' => phpversion(),
  1213. 'sodium' => defined( 'SODIUM_LIBRARY_VERSION' ) ? SODIUM_LIBRARY_VERSION : ( defined( 'ParagonIE_Sodium_Compat::VERSION_STRING' ) ? ParagonIE_Sodium_Compat::VERSION_STRING : false ),
  1214. )
  1215. );
  1216. }
  1217. // Verify runtime speed of Sodium_Compat is acceptable.
  1218. if ( ! extension_loaded( 'sodium' ) && ! ParagonIE_Sodium_Compat::polyfill_is_fast() ) {
  1219. $sodium_compat_is_fast = false;
  1220. // Allow for an old version of Sodium_Compat being loaded before the bundled WordPress one.
  1221. if ( method_exists( 'ParagonIE_Sodium_Compat', 'runtime_speed_test' ) ) {
  1222. /*
  1223. * Run `ParagonIE_Sodium_Compat::runtime_speed_test()` in optimized integer mode,
  1224. * as that's what WordPress utilizes during signing verifications.
  1225. */
  1226. // phpcs:disable WordPress.NamingConventions.ValidVariableName
  1227. $old_fastMult = ParagonIE_Sodium_Compat::$fastMult;
  1228. ParagonIE_Sodium_Compat::$fastMult = true;
  1229. $sodium_compat_is_fast = ParagonIE_Sodium_Compat::runtime_speed_test( 100, 10 );
  1230. ParagonIE_Sodium_Compat::$fastMult = $old_fastMult;
  1231. // phpcs:enable
  1232. }
  1233. // This cannot be performed in a reasonable amount of time.
  1234. // https://github.com/paragonie/sodium_compat#help-sodium_compat-is-slow-how-can-i-make-it-fast
  1235. if ( ! $sodium_compat_is_fast ) {
  1236. return new WP_Error(
  1237. 'signature_verification_unsupported',
  1238. sprintf(
  1239. /* translators: %s: The filename of the package. */
  1240. __( 'The authenticity of %s could not be verified as signature verification is unavailable on this system.' ),
  1241. '<span class="code">' . esc_html( $filename_for_errors ) . '</span>'
  1242. ),
  1243. array(
  1244. 'php' => phpversion(),
  1245. 'sodium' => defined( 'SODIUM_LIBRARY_VERSION' ) ? SODIUM_LIBRARY_VERSION : ( defined( 'ParagonIE_Sodium_Compat::VERSION_STRING' ) ? ParagonIE_Sodium_Compat::VERSION_STRING : false ),
  1246. 'polyfill_is_fast' => false,
  1247. 'max_execution_time' => ini_get( 'max_execution_time' ),
  1248. )
  1249. );
  1250. }
  1251. }
  1252. if ( ! $signatures ) {
  1253. return new WP_Error(
  1254. 'signature_verification_no_signature',
  1255. sprintf(
  1256. /* translators: %s: The filename of the package. */
  1257. __( 'The authenticity of %s could not be verified as no signature was found.' ),
  1258. '<span class="code">' . esc_html( $filename_for_errors ) . '</span>'
  1259. ),
  1260. array(
  1261. 'filename' => $filename_for_errors,
  1262. )
  1263. );
  1264. }
  1265. $trusted_keys = wp_trusted_keys();
  1266. $file_hash = hash_file( 'sha384', $filename, true );
  1267. mbstring_binary_safe_encoding();
  1268. $skipped_key = 0;
  1269. $skipped_signature = 0;
  1270. foreach ( (array) $signatures as $signature ) {
  1271. $signature_raw = base64_decode( $signature );
  1272. // Ensure only valid-length signatures are considered.
  1273. if ( SODIUM_CRYPTO_SIGN_BYTES !== strlen( $signature_raw ) ) {
  1274. $skipped_signature++;
  1275. continue;
  1276. }
  1277. foreach ( (array) $trusted_keys as $key ) {
  1278. $key_raw = base64_decode( $key );
  1279. // Only pass valid public keys through.
  1280. if ( SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES !== strlen( $key_raw ) ) {
  1281. $skipped_key++;
  1282. continue;
  1283. }
  1284. if ( sodium_crypto_sign_verify_detached( $signature_raw, $file_hash, $key_raw ) ) {
  1285. reset_mbstring_encoding

Large files files are truncated, but you can click here to view the full file