PageRenderTime 210ms CodeModel.GetById 100ms app.highlight 57ms RepoModel.GetById 44ms app.codeStats 0ms

/APP/wp-admin/includes/misc.php

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