PageRenderTime 51ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-admin/includes/misc.php

https://github.com/bbt123/WordPress
PHP | 826 lines | 499 code | 100 blank | 227 comment | 122 complexity | 69c2fa170093cb1a8919a0166c9f292c MD5 | raw file
Possible License(s): AGPL-1.0, LGPL-2.1, GPL-2.0
  1. <?php
  2. /**
  3. * Misc WordPress Administration API.
  4. *
  5. * @package WordPress
  6. * @subpackage Administration
  7. */
  8. /**
  9. * Returns whether the server is running Apache with the mod_rewrite module loaded.
  10. *
  11. * @since 2.0.0
  12. *
  13. * @return bool
  14. */
  15. function got_mod_rewrite() {
  16. $got_rewrite = apache_mod_loaded('mod_rewrite', true);
  17. /**
  18. * Filter whether Apache and mod_rewrite are present.
  19. *
  20. * This filter was previously used to force URL rewriting for other servers,
  21. * like nginx. Use the got_url_rewrite filter in got_url_rewrite() instead.
  22. *
  23. * @since 2.5.0
  24. *
  25. * @see got_url_rewrite()
  26. *
  27. * @param bool $got_rewrite Whether Apache and mod_rewrite are present.
  28. */
  29. return apply_filters( 'got_rewrite', $got_rewrite );
  30. }
  31. /**
  32. * Returns whether the server supports URL rewriting.
  33. *
  34. * Detects Apache's mod_rewrite, IIS 7.0+ permalink support, and nginx.
  35. *
  36. * @since 3.7.0
  37. *
  38. * @return bool Whether the server supports URL rewriting.
  39. */
  40. function got_url_rewrite() {
  41. $got_url_rewrite = ( got_mod_rewrite() || $GLOBALS['is_nginx'] || iis7_supports_permalinks() );
  42. /**
  43. * Filter whether URL rewriting is available.
  44. *
  45. * @since 3.7.0
  46. *
  47. * @param bool $got_url_rewrite Whether URL rewriting is available.
  48. */
  49. return apply_filters( 'got_url_rewrite', $got_url_rewrite );
  50. }
  51. /**
  52. * {@internal Missing Short Description}}
  53. *
  54. * @since 1.5.0
  55. *
  56. * @param unknown_type $filename
  57. * @param unknown_type $marker
  58. * @return array An array of strings from a file (.htaccess ) from between BEGIN and END markers.
  59. */
  60. function extract_from_markers( $filename, $marker ) {
  61. $result = array ();
  62. if (!file_exists( $filename ) ) {
  63. return $result;
  64. }
  65. if ( $markerdata = explode( "\n", implode( '', file( $filename ) ) ));
  66. {
  67. $state = false;
  68. foreach ( $markerdata as $markerline ) {
  69. if (strpos($markerline, '# END ' . $marker) !== false)
  70. $state = false;
  71. if ( $state )
  72. $result[] = $markerline;
  73. if (strpos($markerline, '# BEGIN ' . $marker) !== false)
  74. $state = true;
  75. }
  76. }
  77. return $result;
  78. }
  79. /**
  80. * {@internal Missing Short Description}}
  81. *
  82. * Inserts an array of strings into a file (.htaccess ), placing it between
  83. * BEGIN and END markers. Replaces existing marked info. Retains surrounding
  84. * data. Creates file if none exists.
  85. *
  86. * @since 1.5.0
  87. *
  88. * @param unknown_type $filename
  89. * @param unknown_type $marker
  90. * @param unknown_type $insertion
  91. * @return bool True on write success, false on failure.
  92. */
  93. function insert_with_markers( $filename, $marker, $insertion ) {
  94. if (!file_exists( $filename ) || is_writeable( $filename ) ) {
  95. if (!file_exists( $filename ) ) {
  96. $markerdata = '';
  97. } else {
  98. $markerdata = explode( "\n", implode( '', file( $filename ) ) );
  99. }
  100. if ( !$f = @fopen( $filename, 'w' ) )
  101. return false;
  102. $foundit = false;
  103. if ( $markerdata ) {
  104. $state = true;
  105. foreach ( $markerdata as $n => $markerline ) {
  106. if (strpos($markerline, '# BEGIN ' . $marker) !== false)
  107. $state = false;
  108. if ( $state ) {
  109. if ( $n + 1 < count( $markerdata ) )
  110. fwrite( $f, "{$markerline}\n" );
  111. else
  112. fwrite( $f, "{$markerline}" );
  113. }
  114. if (strpos($markerline, '# END ' . $marker) !== false) {
  115. fwrite( $f, "# BEGIN {$marker}\n" );
  116. if ( is_array( $insertion ))
  117. foreach ( $insertion as $insertline )
  118. fwrite( $f, "{$insertline}\n" );
  119. fwrite( $f, "# END {$marker}\n" );
  120. $state = true;
  121. $foundit = true;
  122. }
  123. }
  124. }
  125. if (!$foundit) {
  126. fwrite( $f, "\n# BEGIN {$marker}\n" );
  127. foreach ( $insertion as $insertline )
  128. fwrite( $f, "{$insertline}\n" );
  129. fwrite( $f, "# END {$marker}\n" );
  130. }
  131. fclose( $f );
  132. return true;
  133. } else {
  134. return false;
  135. }
  136. }
  137. /**
  138. * Updates the htaccess file with the current rules if it is writable.
  139. *
  140. * Always writes to the file if it exists and is writable to ensure that we
  141. * blank out old rules.
  142. *
  143. * @since 1.5.0
  144. */
  145. function save_mod_rewrite_rules() {
  146. if ( is_multisite() )
  147. return;
  148. global $wp_rewrite;
  149. $home_path = get_home_path();
  150. $htaccess_file = $home_path.'.htaccess';
  151. // If the file doesn't already exist check for write access to the directory and whether we have some rules.
  152. // else check for write access to the file.
  153. if ((!file_exists($htaccess_file) && is_writable($home_path) && $wp_rewrite->using_mod_rewrite_permalinks()) || is_writable($htaccess_file)) {
  154. if ( got_mod_rewrite() ) {
  155. $rules = explode( "\n", $wp_rewrite->mod_rewrite_rules() );
  156. return insert_with_markers( $htaccess_file, 'WordPress', $rules );
  157. }
  158. }
  159. return false;
  160. }
  161. /**
  162. * Updates the IIS web.config file with the current rules if it is writable.
  163. * If the permalinks do not require rewrite rules then the rules are deleted from the web.config file.
  164. *
  165. * @since 2.8.0
  166. *
  167. * @return bool True if web.config was updated successfully
  168. */
  169. function iis7_save_url_rewrite_rules(){
  170. if ( is_multisite() )
  171. return;
  172. global $wp_rewrite;
  173. $home_path = get_home_path();
  174. $web_config_file = $home_path . 'web.config';
  175. // Using win_is_writable() instead of is_writable() because of a bug in Windows PHP
  176. if ( iis7_supports_permalinks() && ( ( ! file_exists($web_config_file) && win_is_writable($home_path) && $wp_rewrite->using_mod_rewrite_permalinks() ) || win_is_writable($web_config_file) ) ) {
  177. $rule = $wp_rewrite->iis7_url_rewrite_rules(false, '', '');
  178. if ( ! empty($rule) ) {
  179. return iis7_add_rewrite_rule($web_config_file, $rule);
  180. } else {
  181. return iis7_delete_rewrite_rule($web_config_file);
  182. }
  183. }
  184. return false;
  185. }
  186. /**
  187. * {@internal Missing Short Description}}
  188. *
  189. * @since 1.5.0
  190. *
  191. * @param unknown_type $file
  192. */
  193. function update_recently_edited( $file ) {
  194. $oldfiles = (array ) get_option( 'recently_edited' );
  195. if ( $oldfiles ) {
  196. $oldfiles = array_reverse( $oldfiles );
  197. $oldfiles[] = $file;
  198. $oldfiles = array_reverse( $oldfiles );
  199. $oldfiles = array_unique( $oldfiles );
  200. if ( 5 < count( $oldfiles ))
  201. array_pop( $oldfiles );
  202. } else {
  203. $oldfiles[] = $file;
  204. }
  205. update_option( 'recently_edited', $oldfiles );
  206. }
  207. /**
  208. * If siteurl, home or page_on_front changed, flush rewrite rules.
  209. *
  210. * @since 2.1.0
  211. *
  212. * @param string $old_value
  213. * @param string $value
  214. */
  215. function update_home_siteurl( $old_value, $value ) {
  216. if ( defined( "WP_INSTALLING" ) )
  217. return;
  218. // If home changed, write rewrite rules to new location.
  219. flush_rewrite_rules();
  220. }
  221. add_action( 'update_option_home', 'update_home_siteurl', 10, 2 );
  222. add_action( 'update_option_siteurl', 'update_home_siteurl', 10, 2 );
  223. add_action( 'update_option_page_on_front', 'update_home_siteurl', 10, 2 );
  224. /**
  225. * Shorten an URL, to be used as link text
  226. *
  227. * @since 1.2.0
  228. *
  229. * @param string $url
  230. * @return string
  231. */
  232. function url_shorten( $url ) {
  233. $short_url = str_replace( array( 'http://', 'www.' ), '', $url );
  234. $short_url = untrailingslashit( $short_url );
  235. if ( strlen( $short_url ) > 35 )
  236. $short_url = substr( $short_url, 0, 32 ) . '&hellip;';
  237. return $short_url;
  238. }
  239. /**
  240. * Resets global variables based on $_GET and $_POST
  241. *
  242. * This function resets global variables based on the names passed
  243. * in the $vars array to the value of $_POST[$var] or $_GET[$var] or ''
  244. * if neither is defined.
  245. *
  246. * @since 2.0.0
  247. *
  248. * @param array $vars An array of globals to reset.
  249. */
  250. function wp_reset_vars( $vars ) {
  251. foreach ( $vars as $var ) {
  252. if ( empty( $_POST[ $var ] ) ) {
  253. if ( empty( $_GET[ $var ] ) ) {
  254. $GLOBALS[ $var ] = '';
  255. } else {
  256. $GLOBALS[ $var ] = $_GET[ $var ];
  257. }
  258. } else {
  259. $GLOBALS[ $var ] = $_POST[ $var ];
  260. }
  261. }
  262. }
  263. /**
  264. * {@internal Missing Short Description}}
  265. *
  266. * @since 2.1.0
  267. *
  268. * @param unknown_type $message
  269. */
  270. function show_message($message) {
  271. if ( is_wp_error($message) ){
  272. if ( $message->get_error_data() && is_string( $message->get_error_data() ) )
  273. $message = $message->get_error_message() . ': ' . $message->get_error_data();
  274. else
  275. $message = $message->get_error_message();
  276. }
  277. echo "<p>$message</p>\n";
  278. wp_ob_end_flush_all();
  279. flush();
  280. }
  281. function wp_doc_link_parse( $content ) {
  282. if ( !is_string( $content ) || empty( $content ) )
  283. return array();
  284. if ( !function_exists('token_get_all') )
  285. return array();
  286. $tokens = token_get_all( $content );
  287. $count = count( $tokens );
  288. $functions = array();
  289. $ignore_functions = array();
  290. for ( $t = 0; $t < $count - 2; $t++ ) {
  291. if ( ! is_array( $tokens[ $t ] ) ) {
  292. continue;
  293. }
  294. if ( T_STRING == $tokens[ $t ][0] && ( '(' == $tokens[ $t + 1 ] || '(' == $tokens[ $t + 2 ] ) ) {
  295. // If it's a function or class defined locally, there's not going to be any docs available
  296. if ( ( isset( $tokens[ $t - 2 ][1] ) && in_array( $tokens[ $t - 2 ][1], array( 'function', 'class' ) ) ) || ( isset( $tokens[ $t - 2 ][0] ) && T_OBJECT_OPERATOR == $tokens[ $t - 1 ][0] ) ) {
  297. $ignore_functions[] = $tokens[$t][1];
  298. }
  299. // Add this to our stack of unique references
  300. $functions[] = $tokens[$t][1];
  301. }
  302. }
  303. $functions = array_unique( $functions );
  304. sort( $functions );
  305. /**
  306. * Filter the list of functions and classes to be ignored from the documentation lookup.
  307. *
  308. * @since 2.8.0
  309. *
  310. * @param array $ignore_functions Functions and classes to be ignored.
  311. */
  312. $ignore_functions = apply_filters( 'documentation_ignore_functions', $ignore_functions );
  313. $ignore_functions = array_unique( $ignore_functions );
  314. $out = array();
  315. foreach ( $functions as $function ) {
  316. if ( in_array( $function, $ignore_functions ) )
  317. continue;
  318. $out[] = $function;
  319. }
  320. return $out;
  321. }
  322. /**
  323. * Saves option for number of rows when listing posts, pages, comments, etc.
  324. *
  325. * @since 2.8.0
  326. */
  327. function set_screen_options() {
  328. if ( isset($_POST['wp_screen_options']) && is_array($_POST['wp_screen_options']) ) {
  329. check_admin_referer( 'screen-options-nonce', 'screenoptionnonce' );
  330. if ( !$user = wp_get_current_user() )
  331. return;
  332. $option = $_POST['wp_screen_options']['option'];
  333. $value = $_POST['wp_screen_options']['value'];
  334. if ( $option != sanitize_key( $option ) )
  335. return;
  336. $map_option = $option;
  337. $type = str_replace('edit_', '', $map_option);
  338. $type = str_replace('_per_page', '', $type);
  339. if ( in_array( $type, get_taxonomies() ) )
  340. $map_option = 'edit_tags_per_page';
  341. elseif ( in_array( $type, get_post_types() ) )
  342. $map_option = 'edit_per_page';
  343. else
  344. $option = str_replace('-', '_', $option);
  345. switch ( $map_option ) {
  346. case 'edit_per_page':
  347. case 'users_per_page':
  348. case 'edit_comments_per_page':
  349. case 'upload_per_page':
  350. case 'edit_tags_per_page':
  351. case 'plugins_per_page':
  352. // Network admin
  353. case 'sites_network_per_page':
  354. case 'users_network_per_page':
  355. case 'site_users_network_per_page':
  356. case 'plugins_network_per_page':
  357. case 'themes_network_per_page':
  358. case 'site_themes_network_per_page':
  359. $value = (int) $value;
  360. if ( $value < 1 || $value > 999 )
  361. return;
  362. break;
  363. default:
  364. /**
  365. * Filter a screen option value before it is set.
  366. *
  367. * The filter can also be used to modify non-standard [items]_per_page
  368. * settings. See the parent function for a full list of standard options.
  369. *
  370. * Returning false to the filter will skip saving the current option.
  371. *
  372. * @since 2.8.0
  373. *
  374. * @see set_screen_options()
  375. *
  376. * @param bool|int $value Screen option value. Default false to skip.
  377. * @param string $option The option name.
  378. * @param int $value The number of rows to use.
  379. */
  380. $value = apply_filters( 'set-screen-option', false, $option, $value );
  381. if ( false === $value )
  382. return;
  383. break;
  384. }
  385. update_user_meta($user->ID, $option, $value);
  386. wp_safe_redirect( remove_query_arg( array('pagenum', 'apage', 'paged'), wp_get_referer() ) );
  387. exit;
  388. }
  389. }
  390. /**
  391. * Check if rewrite rule for WordPress already exists in the IIS 7+ configuration file
  392. *
  393. * @since 2.8.0
  394. *
  395. * @return bool
  396. * @param string $filename The file path to the configuration file
  397. */
  398. function iis7_rewrite_rule_exists($filename) {
  399. if ( ! file_exists($filename) )
  400. return false;
  401. if ( ! class_exists('DOMDocument') )
  402. return false;
  403. $doc = new DOMDocument();
  404. if ( $doc->load($filename) === false )
  405. return false;
  406. $xpath = new DOMXPath($doc);
  407. $rules = $xpath->query('/configuration/system.webServer/rewrite/rules/rule[starts-with(@name,\'wordpress\')]');
  408. if ( $rules->length == 0 )
  409. return false;
  410. else
  411. return true;
  412. }
  413. /**
  414. * Delete WordPress rewrite rule from web.config file if it exists there
  415. *
  416. * @since 2.8.0
  417. *
  418. * @param string $filename Name of the configuration file
  419. * @return bool
  420. */
  421. function iis7_delete_rewrite_rule($filename) {
  422. // If configuration file does not exist then rules also do not exist so there is nothing to delete
  423. if ( ! file_exists($filename) )
  424. return true;
  425. if ( ! class_exists('DOMDocument') )
  426. return false;
  427. $doc = new DOMDocument();
  428. $doc->preserveWhiteSpace = false;
  429. if ( $doc -> load($filename) === false )
  430. return false;
  431. $xpath = new DOMXPath($doc);
  432. $rules = $xpath->query('/configuration/system.webServer/rewrite/rules/rule[starts-with(@name,\'wordpress\')]');
  433. if ( $rules->length > 0 ) {
  434. $child = $rules->item(0);
  435. $parent = $child->parentNode;
  436. $parent->removeChild($child);
  437. $doc->formatOutput = true;
  438. saveDomDocument($doc, $filename);
  439. }
  440. return true;
  441. }
  442. /**
  443. * Add WordPress rewrite rule to the IIS 7+ configuration file.
  444. *
  445. * @since 2.8.0
  446. *
  447. * @param string $filename The file path to the configuration file
  448. * @param string $rewrite_rule The XML fragment with URL Rewrite rule
  449. * @return bool
  450. */
  451. function iis7_add_rewrite_rule($filename, $rewrite_rule) {
  452. if ( ! class_exists('DOMDocument') )
  453. return false;
  454. // If configuration file does not exist then we create one.
  455. if ( ! file_exists($filename) ) {
  456. $fp = fopen( $filename, 'w');
  457. fwrite($fp, '<configuration/>');
  458. fclose($fp);
  459. }
  460. $doc = new DOMDocument();
  461. $doc->preserveWhiteSpace = false;
  462. if ( $doc->load($filename) === false )
  463. return false;
  464. $xpath = new DOMXPath($doc);
  465. // First check if the rule already exists as in that case there is no need to re-add it
  466. $wordpress_rules = $xpath->query('/configuration/system.webServer/rewrite/rules/rule[starts-with(@name,\'wordpress\')]');
  467. if ( $wordpress_rules->length > 0 )
  468. return true;
  469. // Check the XPath to the rewrite rule and create XML nodes if they do not exist
  470. $xmlnodes = $xpath->query('/configuration/system.webServer/rewrite/rules');
  471. if ( $xmlnodes->length > 0 ) {
  472. $rules_node = $xmlnodes->item(0);
  473. } else {
  474. $rules_node = $doc->createElement('rules');
  475. $xmlnodes = $xpath->query('/configuration/system.webServer/rewrite');
  476. if ( $xmlnodes->length > 0 ) {
  477. $rewrite_node = $xmlnodes->item(0);
  478. $rewrite_node->appendChild($rules_node);
  479. } else {
  480. $rewrite_node = $doc->createElement('rewrite');
  481. $rewrite_node->appendChild($rules_node);
  482. $xmlnodes = $xpath->query('/configuration/system.webServer');
  483. if ( $xmlnodes->length > 0 ) {
  484. $system_webServer_node = $xmlnodes->item(0);
  485. $system_webServer_node->appendChild($rewrite_node);
  486. } else {
  487. $system_webServer_node = $doc->createElement('system.webServer');
  488. $system_webServer_node->appendChild($rewrite_node);
  489. $xmlnodes = $xpath->query('/configuration');
  490. if ( $xmlnodes->length > 0 ) {
  491. $config_node = $xmlnodes->item(0);
  492. $config_node->appendChild($system_webServer_node);
  493. } else {
  494. $config_node = $doc->createElement('configuration');
  495. $doc->appendChild($config_node);
  496. $config_node->appendChild($system_webServer_node);
  497. }
  498. }
  499. }
  500. }
  501. $rule_fragment = $doc->createDocumentFragment();
  502. $rule_fragment->appendXML($rewrite_rule);
  503. $rules_node->appendChild($rule_fragment);
  504. $doc->encoding = "UTF-8";
  505. $doc->formatOutput = true;
  506. saveDomDocument($doc, $filename);
  507. return true;
  508. }
  509. /**
  510. * Saves the XML document into a file
  511. *
  512. * @since 2.8.0
  513. *
  514. * @param DOMDocument $doc
  515. * @param string $filename
  516. */
  517. function saveDomDocument($doc, $filename) {
  518. $config = $doc->saveXML();
  519. $config = preg_replace("/([^\r])\n/", "$1\r\n", $config);
  520. $fp = fopen($filename, 'w');
  521. fwrite($fp, $config);
  522. fclose($fp);
  523. }
  524. /**
  525. * Display the default admin color scheme picker (Used in user-edit.php)
  526. *
  527. * @since 3.0.0
  528. */
  529. function admin_color_scheme_picker( $user_id ) {
  530. global $_wp_admin_css_colors;
  531. ksort( $_wp_admin_css_colors );
  532. if ( isset( $_wp_admin_css_colors['fresh'] ) ) {
  533. // Set Default ('fresh') and Light should go first.
  534. $_wp_admin_css_colors = array_filter( array_merge( array( 'fresh' => '', 'light' => '' ), $_wp_admin_css_colors ) );
  535. }
  536. $current_color = get_user_option( 'admin_color', $user_id );
  537. if ( empty( $current_color ) || ! isset( $_wp_admin_css_colors[ $current_color ] ) ) {
  538. $current_color = 'fresh';
  539. }
  540. ?>
  541. <fieldset id="color-picker" class="scheme-list">
  542. <legend class="screen-reader-text"><span><?php _e( 'Admin Color Scheme' ); ?></span></legend>
  543. <?php
  544. wp_nonce_field( 'save-color-scheme', 'color-nonce', false );
  545. foreach ( $_wp_admin_css_colors as $color => $color_info ) :
  546. ?>
  547. <div class="color-option <?php echo ( $color == $current_color ) ? 'selected' : ''; ?>">
  548. <input name="admin_color" id="admin_color_<?php echo esc_attr( $color ); ?>" type="radio" value="<?php echo esc_attr( $color ); ?>" class="tog" <?php checked( $color, $current_color ); ?> />
  549. <input type="hidden" class="css_url" value="<?php echo esc_url( $color_info->url ); ?>" />
  550. <input type="hidden" class="icon_colors" value="<?php echo esc_attr( json_encode( array( 'icons' => $color_info->icon_colors ) ) ); ?>" />
  551. <label for="admin_color_<?php echo esc_attr( $color ); ?>"><?php echo esc_html( $color_info->name ); ?></label>
  552. <table class="color-palette">
  553. <tr>
  554. <?php
  555. foreach ( $color_info->colors as $html_color ) {
  556. ?>
  557. <td style="background-color: <?php echo esc_attr( $html_color ); ?>">&nbsp;</td>
  558. <?php
  559. }
  560. ?>
  561. </tr>
  562. </table>
  563. </div>
  564. <?php
  565. endforeach;
  566. ?>
  567. </fieldset>
  568. <?php
  569. }
  570. function wp_color_scheme_settings() {
  571. global $_wp_admin_css_colors;
  572. $color_scheme = get_user_option( 'admin_color' );
  573. // It's possible to have a color scheme set that is no longer registered.
  574. if ( empty( $_wp_admin_css_colors[ $color_scheme ] ) ) {
  575. $color_scheme = 'fresh';
  576. }
  577. if ( ! empty( $_wp_admin_css_colors[ $color_scheme ]->icon_colors ) ) {
  578. $icon_colors = $_wp_admin_css_colors[ $color_scheme ]->icon_colors;
  579. } elseif ( ! empty( $_wp_admin_css_colors['fresh']->icon_colors ) ) {
  580. $icon_colors = $_wp_admin_css_colors['fresh']->icon_colors;
  581. } else {
  582. // Fall back to the default set of icon colors if the default scheme is missing.
  583. $icon_colors = array( 'base' => '#999', 'focus' => '#2ea2cc', 'current' => '#fff' );
  584. }
  585. echo '<script type="text/javascript">var _wpColorScheme = ' . json_encode( array( 'icons' => $icon_colors ) ) . ";</script>\n";
  586. }
  587. add_action( 'admin_head', 'wp_color_scheme_settings' );
  588. function _ipad_meta() {
  589. if ( wp_is_mobile() ) {
  590. ?>
  591. <meta name="viewport" id="viewport-meta" content="width=device-width, initial-scale=1">
  592. <?php
  593. }
  594. }
  595. add_action('admin_head', '_ipad_meta');
  596. /**
  597. * Check lock status for posts displayed on the Posts screen
  598. *
  599. * @since 3.6.0
  600. */
  601. function wp_check_locked_posts( $response, $data, $screen_id ) {
  602. $checked = array();
  603. if ( array_key_exists( 'wp-check-locked-posts', $data ) && is_array( $data['wp-check-locked-posts'] ) ) {
  604. foreach ( $data['wp-check-locked-posts'] as $key ) {
  605. if ( ! $post_id = absint( substr( $key, 5 ) ) )
  606. continue;
  607. if ( ( $user_id = wp_check_post_lock( $post_id ) ) && ( $user = get_userdata( $user_id ) ) && current_user_can( 'edit_post', $post_id ) ) {
  608. $send = array( 'text' => sprintf( __( '%s is currently editing' ), $user->display_name ) );
  609. if ( ( $avatar = get_avatar( $user->ID, 18 ) ) && preg_match( "|src='([^']+)'|", $avatar, $matches ) )
  610. $send['avatar_src'] = $matches[1];
  611. $checked[$key] = $send;
  612. }
  613. }
  614. }
  615. if ( ! empty( $checked ) )
  616. $response['wp-check-locked-posts'] = $checked;
  617. return $response;
  618. }
  619. add_filter( 'heartbeat_received', 'wp_check_locked_posts', 10, 3 );
  620. /**
  621. * Check lock status on the New/Edit Post screen and refresh the lock
  622. *
  623. * @since 3.6.0
  624. */
  625. function wp_refresh_post_lock( $response, $data, $screen_id ) {
  626. if ( array_key_exists( 'wp-refresh-post-lock', $data ) ) {
  627. $received = $data['wp-refresh-post-lock'];
  628. $send = array();
  629. if ( ! $post_id = absint( $received['post_id'] ) )
  630. return $response;
  631. if ( ! current_user_can('edit_post', $post_id) )
  632. return $response;
  633. if ( ( $user_id = wp_check_post_lock( $post_id ) ) && ( $user = get_userdata( $user_id ) ) ) {
  634. $error = array(
  635. 'text' => sprintf( __( '%s has taken over and is currently editing.' ), $user->display_name )
  636. );
  637. if ( $avatar = get_avatar( $user->ID, 64 ) ) {
  638. if ( preg_match( "|src='([^']+)'|", $avatar, $matches ) )
  639. $error['avatar_src'] = $matches[1];
  640. }
  641. $send['lock_error'] = $error;
  642. } else {
  643. if ( $new_lock = wp_set_post_lock( $post_id ) )
  644. $send['new_lock'] = implode( ':', $new_lock );
  645. }
  646. $response['wp-refresh-post-lock'] = $send;
  647. }
  648. return $response;
  649. }
  650. add_filter( 'heartbeat_received', 'wp_refresh_post_lock', 10, 3 );
  651. /**
  652. * Check nonce expiration on the New/Edit Post screen and refresh if needed
  653. *
  654. * @since 3.6.0
  655. */
  656. function wp_refresh_post_nonces( $response, $data, $screen_id ) {
  657. if ( array_key_exists( 'wp-refresh-post-nonces', $data ) ) {
  658. $received = $data['wp-refresh-post-nonces'];
  659. $response['wp-refresh-post-nonces'] = array( 'check' => 1 );
  660. if ( ! $post_id = absint( $received['post_id'] ) )
  661. return $response;
  662. if ( ! current_user_can( 'edit_post', $post_id ) || empty( $received['post_nonce'] ) )
  663. return $response;
  664. if ( 2 === wp_verify_nonce( $received['post_nonce'], 'update-post_' . $post_id ) ) {
  665. $response['wp-refresh-post-nonces'] = array(
  666. 'replace' => array(
  667. 'getpermalinknonce' => wp_create_nonce('getpermalink'),
  668. 'samplepermalinknonce' => wp_create_nonce('samplepermalink'),
  669. 'closedpostboxesnonce' => wp_create_nonce('closedpostboxes'),
  670. '_ajax_linking_nonce' => wp_create_nonce( 'internal-linking' ),
  671. '_wpnonce' => wp_create_nonce( 'update-post_' . $post_id ),
  672. ),
  673. 'heartbeatNonce' => wp_create_nonce( 'heartbeat-nonce' ),
  674. );
  675. }
  676. }
  677. return $response;
  678. }
  679. add_filter( 'heartbeat_received', 'wp_refresh_post_nonces', 10, 3 );
  680. /**
  681. * Disable suspension of Heartbeat on the Add/Edit Post screens.
  682. *
  683. * @since 3.8.0
  684. *
  685. * @param array $settings An array of Heartbeat settings.
  686. * @return array Filtered Heartbeat settings.
  687. */
  688. function wp_heartbeat_set_suspension( $settings ) {
  689. global $pagenow;
  690. if ( 'post.php' === $pagenow || 'post-new.php' === $pagenow ) {
  691. $settings['suspension'] = 'disable';
  692. }
  693. return $settings;
  694. }
  695. add_filter( 'heartbeat_settings', 'wp_heartbeat_set_suspension' );
  696. /**
  697. * Autosave with heartbeat
  698. *
  699. * @since 3.9.0
  700. */
  701. function heartbeat_autosave( $response, $data ) {
  702. if ( ! empty( $data['wp_autosave'] ) ) {
  703. $saved = wp_autosave( $data['wp_autosave'] );
  704. if ( is_wp_error( $saved ) ) {
  705. $response['wp_autosave'] = array( 'success' => false, 'message' => $saved->get_error_message() );
  706. } elseif ( empty( $saved ) ) {
  707. $response['wp_autosave'] = array( 'success' => false, 'message' => __( 'Error while saving.' ) );
  708. } else {
  709. /* translators: draft saved date format, see http://php.net/date */
  710. $draft_saved_date_format = __( 'g:i:s a' );
  711. /* translators: %s: date and time */
  712. $response['wp_autosave'] = array( 'success' => true, 'message' => sprintf( __( 'Draft saved at %s.' ), date_i18n( $draft_saved_date_format ) ) );
  713. }
  714. }
  715. return $response;
  716. }
  717. // Run later as we have to set DOING_AUTOSAVE for back-compat
  718. add_filter( 'heartbeat_received', 'heartbeat_autosave', 500, 2 );