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