3 * Misc WordPress Administration API.
6 * @subpackage Administration
10 * Returns whether the server is running Apache with the mod_rewrite module loaded.
16 function got_mod_rewrite() {
17 $got_rewrite = apache_mod_loaded('mod_rewrite', true);
20 * Filter whether Apache and mod_rewrite are present.
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.
27 * @see got_url_rewrite()
29 * @param bool $got_rewrite Whether Apache and mod_rewrite are present.
31 return apply_filters( 'got_rewrite', $got_rewrite );
35 * Returns whether the server supports URL rewriting.
37 * Detects Apache's mod_rewrite, IIS 7.0+ permalink support, and nginx.
41 * @global bool $is_nginx
43 * @return bool Whether the server supports URL rewriting.
45 function got_url_rewrite() {
46 $got_url_rewrite = ( got_mod_rewrite() || $GLOBALS['is_nginx'] || iis7_supports_permalinks() );
49 * Filter whether URL rewriting is available.
53 * @param bool $got_url_rewrite Whether URL rewriting is available.
55 return apply_filters( 'got_url_rewrite', $got_url_rewrite );
59 * {@internal Missing Short Description}}
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.
67 function extract_from_markers( $filename, $marker ) {
70 if (!file_exists( $filename ) ) {
74 if ( $markerdata = explode( "\n", implode( '', file( $filename ) ) ));
77 foreach ( $markerdata as $markerline ) {
78 if (strpos($markerline, '# END ' . $marker) !== false)
81 $result[] = $markerline;
82 if (strpos($markerline, '# BEGIN ' . $marker) !== false)
91 * {@internal Missing Short Description}}
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.
99 * @param string $filename
100 * @param string $marker
101 * @param array $insertion
102 * @return bool True on write success, false on failure.
104 function insert_with_markers( $filename, $marker, $insertion ) {
105 if (!file_exists( $filename ) || is_writeable( $filename ) ) {
106 if (!file_exists( $filename ) ) {
109 $markerdata = explode( "\n", implode( '', file( $filename ) ) );
112 if ( !$f = @fopen( $filename, 'w' ) )
118 foreach ( $markerdata as $n => $markerline ) {
119 if (strpos($markerline, '# BEGIN ' . $marker) !== false)
122 if ( $n + 1 < count( $markerdata ) )
123 fwrite( $f, "{$markerline}\n" );
125 fwrite( $f, "{$markerline}" );
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" );
139 fwrite( $f, "\n# BEGIN {$marker}\n" );
140 foreach ( $insertion as $insertline )
141 fwrite( $f, "{$insertline}\n" );
142 fwrite( $f, "# END {$marker}\n" );
152 * Updates the htaccess file with the current rules if it is writable.
154 * Always writes to the file if it exists and is writable to ensure that we
155 * blank out old rules.
159 * @global WP_Rewrite $wp_rewrite
161 function save_mod_rewrite_rules() {
162 if ( is_multisite() )
167 $home_path = get_home_path();
168 $htaccess_file = $home_path.'.htaccess';
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.
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 );
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.
190 * @global WP_Rewrite $wp_rewrite
192 * @return bool True if web.config was updated successfully
194 function iis7_save_url_rewrite_rules(){
195 if ( is_multisite() )
200 $home_path = get_home_path();
201 $web_config_file = $home_path . 'web.config';
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);
209 return iis7_delete_rewrite_rule($web_config_file);
216 * {@internal Missing Short Description}}
220 * @param string $file
222 function update_recently_edited( $file ) {
223 $oldfiles = (array ) get_option( 'recently_edited' );
225 $oldfiles = array_reverse( $oldfiles );
227 $oldfiles = array_reverse( $oldfiles );
228 $oldfiles = array_unique( $oldfiles );
229 if ( 5 < count( $oldfiles ))
230 array_pop( $oldfiles );
234 update_option( 'recently_edited', $oldfiles );
238 * If siteurl, home or page_on_front changed, flush rewrite rules.
242 * @param string $old_value
243 * @param string $value
245 function update_home_siteurl( $old_value, $value ) {
246 if ( defined( "WP_INSTALLING" ) )
249 // If home changed, write rewrite rules to new location.
250 flush_rewrite_rules();
254 * Shorten an URL, to be used as link text
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 ) . '…';
270 * Resets global variables based on $_GET and $_POST
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.
278 * @param array $vars An array of globals to reset.
280 function wp_reset_vars( $vars ) {
281 foreach ( $vars as $var ) {
282 if ( empty( $_POST[ $var ] ) ) {
283 if ( empty( $_GET[ $var ] ) ) {
284 $GLOBALS[ $var ] = '';
286 $GLOBALS[ $var ] = $_GET[ $var ];
289 $GLOBALS[ $var ] = $_POST[ $var ];
295 * {@internal Missing Short Description}}
299 * @param string|WP_Error $message
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();
306 $message = $message->get_error_message();
308 echo "<p>$message</p>\n";
309 wp_ob_end_flush_all();
316 * @param string $content
319 function wp_doc_link_parse( $content ) {
320 if ( !is_string( $content ) || empty( $content ) )
323 if ( !function_exists('token_get_all') )
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 ] ) ) {
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];
340 // Add this to our stack of unique references
341 $functions[] = $tokens[$t][1];
345 $functions = array_unique( $functions );
349 * Filter the list of functions and classes to be ignored from the documentation lookup.
353 * @param array $ignore_functions Functions and classes to be ignored.
355 $ignore_functions = apply_filters( 'documentation_ignore_functions', $ignore_functions );
357 $ignore_functions = array_unique( $ignore_functions );
360 foreach ( $functions as $function ) {
361 if ( in_array( $function, $ignore_functions ) )
370 * Saves option for number of rows when listing posts, pages, comments, etc.
374 function set_screen_options() {
376 if ( isset($_POST['wp_screen_options']) && is_array($_POST['wp_screen_options']) ) {
377 check_admin_referer( 'screen-options-nonce', 'screenoptionnonce' );
379 if ( !$user = wp_get_current_user() )
381 $option = $_POST['wp_screen_options']['option'];
382 $value = $_POST['wp_screen_options']['value'];
384 if ( $option != sanitize_key( $option ) )
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';
395 $option = str_replace('-', '_', $option);
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':
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 )
418 * Filter a screen option value before it is set.
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.
423 * Returning false to the filter will skip saving the current option.
427 * @see set_screen_options()
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.
433 $value = apply_filters( 'set-screen-option', false, $option, $value );
435 if ( false === $value )
440 update_user_meta($user->ID, $option, $value);
441 wp_safe_redirect( remove_query_arg( array('pagenum', 'apage', 'paged'), wp_get_referer() ) );
447 * Check if rewrite rule for WordPress already exists in the IIS 7+ configuration file
452 * @param string $filename The file path to the configuration file
454 function iis7_rewrite_rule_exists($filename) {
455 if ( ! file_exists($filename) )
457 if ( ! class_exists('DOMDocument') )
460 $doc = new DOMDocument();
461 if ( $doc->load($filename) === 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 )
472 * Delete WordPress rewrite rule from web.config file if it exists there
476 * @param string $filename Name of the configuration file
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) )
484 if ( ! class_exists('DOMDocument') )
487 $doc = new DOMDocument();
488 $doc->preserveWhiteSpace = false;
490 if ( $doc -> load($filename) === 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);
505 * Add WordPress rewrite rule to the IIS 7+ configuration file.
509 * @param string $filename The file path to the configuration file
510 * @param string $rewrite_rule The XML fragment with URL Rewrite rule
513 function iis7_add_rewrite_rule($filename, $rewrite_rule) {
514 if ( ! class_exists('DOMDocument') )
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/>');
524 $doc = new DOMDocument();
525 $doc->preserveWhiteSpace = false;
527 if ( $doc->load($filename) === false )
530 $xpath = new DOMXPath($doc);
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 )
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);
542 $rules_node = $doc->createElement('rules');
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);
549 $rewrite_node = $doc->createElement('rewrite');
550 $rewrite_node->appendChild($rules_node);
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);
557 $system_webServer_node = $doc->createElement('system.webServer');
558 $system_webServer_node->appendChild($rewrite_node);
560 $xmlnodes = $xpath->query('/configuration');
561 if ( $xmlnodes->length > 0 ) {
562 $config_node = $xmlnodes->item(0);
563 $config_node->appendChild($system_webServer_node);
565 $config_node = $doc->createElement('configuration');
566 $doc->appendChild($config_node);
567 $config_node->appendChild($system_webServer_node);
573 $rule_fragment = $doc->createDocumentFragment();
574 $rule_fragment->appendXML($rewrite_rule);
575 $rules_node->appendChild($rule_fragment);
577 $doc->encoding = "UTF-8";
578 $doc->formatOutput = true;
579 saveDomDocument($doc, $filename);
585 * Saves the XML document into a file
589 * @param DOMDocument $doc
590 * @param string $filename
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);
601 * Display the default admin color scheme picker (Used in user-edit.php)
605 * @global array $_wp_admin_css_colors
607 function admin_color_scheme_picker( $user_id ) {
608 global $_wp_admin_css_colors;
610 ksort( $_wp_admin_css_colors );
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 ) );
617 $current_color = get_user_option( 'admin_color', $user_id );
619 if ( empty( $current_color ) || ! isset( $_wp_admin_css_colors[ $current_color ] ) ) {
620 $current_color = 'fresh';
624 <fieldset id="color-picker" class="scheme-list">
625 <legend class="screen-reader-text"><span><?php _e( 'Admin Color Scheme' ); ?></span></legend>
627 wp_nonce_field( 'save-color-scheme', 'color-nonce', false );
628 foreach ( $_wp_admin_css_colors as $color => $color_info ) :
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">
640 foreach ( $color_info->colors as $html_color ) {
642 <td style="background-color: <?php echo esc_attr( $html_color ); ?>"> </td>
661 * @global array $_wp_admin_css_colors
663 function wp_color_scheme_settings() {
664 global $_wp_admin_css_colors;
666 $color_scheme = get_user_option( 'admin_color' );
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';
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;
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' );
682 echo '<script type="text/javascript">var _wpColorScheme = ' . wp_json_encode( array( 'icons' => $icon_colors ) ) . ";</script>\n";
688 function _ipad_meta() {
689 if ( wp_is_mobile() ) {
691 <meta name="viewport" id="viewport-meta" content="width=device-width, initial-scale=1">
697 * Check lock status for posts displayed on the Posts screen
701 function wp_check_locked_posts( $response, $data, $screen_id ) {
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 ) ) )
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 ) );
712 if ( ( $avatar = get_avatar( $user->ID, 18 ) ) && preg_match( "|src='([^']+)'|", $avatar, $matches ) )
713 $send['avatar_src'] = $matches[1];
715 $checked[$key] = $send;
720 if ( ! empty( $checked ) )
721 $response['wp-check-locked-posts'] = $checked;
727 * Check lock status on the New/Edit Post screen and refresh the lock
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'];
736 if ( ! $post_id = absint( $received['post_id'] ) )
739 if ( ! current_user_can('edit_post', $post_id) )
742 if ( ( $user_id = wp_check_post_lock( $post_id ) ) && ( $user = get_userdata( $user_id ) ) ) {
744 'text' => sprintf( __( '%s has taken over and is currently editing.' ), $user->display_name )
747 if ( $avatar = get_avatar( $user->ID, 64 ) ) {
748 if ( preg_match( "|src='([^']+)'|", $avatar, $matches ) )
749 $error['avatar_src'] = $matches[1];
752 $send['lock_error'] = $error;
754 if ( $new_lock = wp_set_post_lock( $post_id ) )
755 $send['new_lock'] = implode( ':', $new_lock );
758 $response['wp-refresh-post-lock'] = $send;
765 * Check nonce expiration on the New/Edit Post screen and refresh if needed
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 );
774 if ( ! $post_id = absint( $received['post_id'] ) ) {
778 if ( ! current_user_can( 'edit_post', $post_id ) ) {
782 $response['wp-refresh-post-nonces'] = 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 ),
790 'heartbeatNonce' => wp_create_nonce( 'heartbeat-nonce' ),
798 * Disable suspension of Heartbeat on the Add/Edit Post screens.
802 * @global string $pagenow
804 * @param array $settings An array of Heartbeat settings.
805 * @return array Filtered Heartbeat settings.
807 function wp_heartbeat_set_suspension( $settings ) {
810 if ( 'post.php' === $pagenow || 'post-new.php' === $pagenow ) {
811 $settings['suspension'] = 'disable';
818 * Autosave with heartbeat
822 function heartbeat_autosave( $response, $data ) {
823 if ( ! empty( $data['wp_autosave'] ) ) {
824 $saved = wp_autosave( $data['wp_autosave'] );
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.' ) );
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 ) ) );
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
848 * @global bool $is_safari
849 * @global bool $is_chrome
851 function post_form_autocomplete_off() {
852 global $is_safari, $is_chrome;
854 if ( $is_safari || $is_chrome ) {
855 echo ' autocomplete="off"';
860 * Remove single-use URL parameters and create canonical link based on new URL.
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.
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',
878 * Filter the list of URL parameters to remove.
882 * @param array $removable_query_args An array of parameters to remove from the URL.
884 $removable_query_args = apply_filters( 'removable_query_args', $removable_query_args );
886 if ( empty( $removable_query_args ) ) {
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 );
894 <link id="wp-admin-canonical" rel="canonical" href="<?php echo esc_url( $filtered_url ); ?>" />
896 if ( window.history.replaceState ) {
897 window.history.replaceState( null, null, document.getElementById( 'wp-admin-canonical' ).href + window.location.hash );