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.
25 * @see got_url_rewrite()
28 * @param bool $got_rewrite Whether Apache and mod_rewrite are present.
30 return apply_filters( 'got_rewrite', $got_rewrite );
34 * Returns whether the server supports URL rewriting.
36 * Detects Apache's mod_rewrite, IIS 7.0+ permalink support, and nginx.
40 * @return bool Whether the server supports URL rewriting.
42 function got_url_rewrite() {
43 $got_url_rewrite = ( got_mod_rewrite() || $GLOBALS['is_nginx'] || iis7_supports_permalinks() );
46 * Filter whether URL rewriting is available.
49 * @param bool $got_url_rewrite Whether URL rewriting is available.
51 return apply_filters( 'got_url_rewrite', $got_url_rewrite );
55 * {@internal Missing Short Description}}
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.
63 function extract_from_markers( $filename, $marker ) {
66 if (!file_exists( $filename ) ) {
70 if ( $markerdata = explode( "\n", implode( '', file( $filename ) ) ));
73 foreach ( $markerdata as $markerline ) {
74 if (strpos($markerline, '# END ' . $marker) !== false)
77 $result[] = $markerline;
78 if (strpos($markerline, '# BEGIN ' . $marker) !== false)
87 * {@internal Missing Short Description}}
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.
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.
100 function insert_with_markers( $filename, $marker, $insertion ) {
101 if (!file_exists( $filename ) || is_writeable( $filename ) ) {
102 if (!file_exists( $filename ) ) {
105 $markerdata = explode( "\n", implode( '', file( $filename ) ) );
108 if ( !$f = @fopen( $filename, 'w' ) )
114 foreach ( $markerdata as $n => $markerline ) {
115 if (strpos($markerline, '# BEGIN ' . $marker) !== false)
118 if ( $n + 1 < count( $markerdata ) )
119 fwrite( $f, "{$markerline}\n" );
121 fwrite( $f, "{$markerline}" );
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" );
135 fwrite( $f, "\n# BEGIN {$marker}\n" );
136 foreach ( $insertion as $insertline )
137 fwrite( $f, "{$insertline}\n" );
138 fwrite( $f, "# END {$marker}\n" );
148 * Updates the htaccess file with the current rules if it is writable.
150 * Always writes to the file if it exists and is writable to ensure that we
151 * blank out old rules.
155 function save_mod_rewrite_rules() {
156 if ( is_multisite() )
161 $home_path = get_home_path();
162 $htaccess_file = $home_path.'.htaccess';
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 );
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.
182 * @return bool True if web.config was updated successfully
184 function iis7_save_url_rewrite_rules(){
185 if ( is_multisite() )
190 $home_path = get_home_path();
191 $web_config_file = $home_path . 'web.config';
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);
199 return iis7_delete_rewrite_rule($web_config_file);
206 * {@internal Missing Short Description}}
210 * @param unknown_type $file
212 function update_recently_edited( $file ) {
213 $oldfiles = (array ) get_option( 'recently_edited' );
215 $oldfiles = array_reverse( $oldfiles );
217 $oldfiles = array_reverse( $oldfiles );
218 $oldfiles = array_unique( $oldfiles );
219 if ( 5 < count( $oldfiles ))
220 array_pop( $oldfiles );
224 update_option( 'recently_edited', $oldfiles );
228 * If siteurl, home or page_on_front changed, flush rewrite rules.
232 * @param string $old_value
233 * @param string $value
235 function update_home_siteurl( $old_value, $value ) {
236 if ( defined( "WP_INSTALLING" ) )
239 // If home changed, write rewrite rules to new location.
240 flush_rewrite_rules();
243 add_action( 'update_option_home', 'update_home_siteurl', 10, 2 );
244 add_action( 'update_option_siteurl', 'update_home_siteurl', 10, 2 );
245 add_action( 'update_option_page_on_front', 'update_home_siteurl', 10, 2 );
248 * Shorten an URL, to be used as link text
255 function 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 ) . '…';
264 * Resets global variables based on $_GET and $_POST
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.
272 * @param array $vars An array of globals to reset.
274 function wp_reset_vars( $vars ) {
275 for ( $i=0; $i<count( $vars ); $i += 1 ) {
279 if ( empty( $_POST[$var] ) ) {
280 if ( empty( $_GET[$var] ) )
285 $$var = $_POST[$var];
291 * {@internal Missing Short Description}}
295 * @param unknown_type $message
297 function 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();
302 $message = $message->get_error_message();
304 echo "<p>$message</p>\n";
305 wp_ob_end_flush_all();
309 function wp_doc_link_parse( $content ) {
310 if ( !is_string( $content ) || empty( $content ) )
313 if ( !function_exists('token_get_all') )
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 ] ) ) {
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];
330 // Add this to our stack of unique references
331 $functions[] = $tokens[$t][1];
335 $functions = array_unique( $functions );
339 * Filter the list of functions/classes to be ignored from the documentation lookup.
343 * @param array $ignore_functions Functions/Classes to be ignored.
345 $ignore_functions = apply_filters( 'documentation_ignore_functions', $ignore_functions );
347 $ignore_functions = array_unique( $ignore_functions );
350 foreach ( $functions as $function ) {
351 if ( in_array( $function, $ignore_functions ) )
360 * Saves option for number of rows when listing posts, pages, comments, etc.
364 function set_screen_options() {
366 if ( isset($_POST['wp_screen_options']) && is_array($_POST['wp_screen_options']) ) {
367 check_admin_referer( 'screen-options-nonce', 'screenoptionnonce' );
369 if ( !$user = wp_get_current_user() )
371 $option = $_POST['wp_screen_options']['option'];
372 $value = $_POST['wp_screen_options']['value'];
374 if ( $option != sanitize_key( $option ) )
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';
385 $option = str_replace('-', '_', $option);
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':
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 )
408 * Filter a screen option value before it is set.
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.
413 * Returning false to the filter will skip saving the current option.
417 * @see set_screen_options()
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.
423 $value = apply_filters( 'set-screen-option', false, $option, $value );
425 if ( false === $value )
430 update_user_meta($user->ID, $option, $value);
431 wp_safe_redirect( remove_query_arg( array('pagenum', 'apage', 'paged'), wp_get_referer() ) );
437 * Check if rewrite rule for WordPress already exists in the IIS 7+ configuration file
442 * @param string $filename The file path to the configuration file
444 function iis7_rewrite_rule_exists($filename) {
445 if ( ! file_exists($filename) )
447 if ( ! class_exists('DOMDocument') )
450 $doc = new DOMDocument();
451 if ( $doc->load($filename) === 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 )
462 * Delete WordPress rewrite rule from web.config file if it exists there
466 * @param string $filename Name of the configuration file
469 function 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) )
474 if ( ! class_exists('DOMDocument') )
477 $doc = new DOMDocument();
478 $doc->preserveWhiteSpace = false;
480 if ( $doc -> load($filename) === 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);
495 * Add WordPress rewrite rule to the IIS 7+ configuration file.
499 * @param string $filename The file path to the configuration file
500 * @param string $rewrite_rule The XML fragment with URL Rewrite rule
503 function iis7_add_rewrite_rule($filename, $rewrite_rule) {
504 if ( ! class_exists('DOMDocument') )
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/>');
514 $doc = new DOMDocument();
515 $doc->preserveWhiteSpace = false;
517 if ( $doc->load($filename) === false )
520 $xpath = new DOMXPath($doc);
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 )
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);
532 $rules_node = $doc->createElement('rules');
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);
539 $rewrite_node = $doc->createElement('rewrite');
540 $rewrite_node->appendChild($rules_node);
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);
547 $system_webServer_node = $doc->createElement('system.webServer');
548 $system_webServer_node->appendChild($rewrite_node);
550 $xmlnodes = $xpath->query('/configuration');
551 if ( $xmlnodes->length > 0 ) {
552 $config_node = $xmlnodes->item(0);
553 $config_node->appendChild($system_webServer_node);
555 $config_node = $doc->createElement('configuration');
556 $doc->appendChild($config_node);
557 $config_node->appendChild($system_webServer_node);
563 $rule_fragment = $doc->createDocumentFragment();
564 $rule_fragment->appendXML($rewrite_rule);
565 $rules_node->appendChild($rule_fragment);
567 $doc->encoding = "UTF-8";
568 $doc->formatOutput = true;
569 saveDomDocument($doc, $filename);
575 * Saves the XML document into a file
579 * @param DOMDocument $doc
580 * @param string $filename
582 function 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);
591 * Display the default admin color scheme picker (Used in user-edit.php)
595 function admin_color_scheme_picker( $user_id ) {
596 global $_wp_admin_css_colors;
598 ksort( $_wp_admin_css_colors );
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 ) );
605 $current_color = get_user_option( 'admin_color', $user_id );
607 if ( empty( $current_color ) || ! isset( $_wp_admin_css_colors[ $current_color ] ) ) {
608 $current_color = 'fresh';
612 <fieldset id="color-picker" class="scheme-list">
613 <legend class="screen-reader-text"><span><?php _e( 'Admin Color Scheme' ); ?></span></legend>
615 wp_nonce_field( 'save-color-scheme', 'color-nonce', false );
616 foreach ( $_wp_admin_css_colors as $color => $color_info ) :
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">
628 foreach ( $color_info->colors as $html_color ) {
630 <td style="background-color: <?php echo esc_attr( $html_color ); ?>"> </td>
647 function wp_color_scheme_settings() {
648 global $_wp_admin_css_colors;
650 $color_scheme = get_user_option( 'admin_color' );
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';
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;
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' );
666 echo '<script type="text/javascript">var _wpColorScheme = ' . json_encode( array( 'icons' => $icon_colors ) ) . ";</script>\n";
668 add_action( 'admin_head', 'wp_color_scheme_settings' );
670 function _ipad_meta() {
671 if ( wp_is_mobile() ) {
673 <meta name="viewport" id="viewport-meta" content="width=device-width, initial-scale=1">
677 add_action('admin_head', '_ipad_meta');
680 * Check lock status for posts displayed on the Posts screen
684 function wp_check_locked_posts( $response, $data, $screen_id ) {
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 ) ) )
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 ) );
695 if ( ( $avatar = get_avatar( $user->ID, 18 ) ) && preg_match( "|src='([^']+)'|", $avatar, $matches ) )
696 $send['avatar_src'] = $matches[1];
698 $checked[$key] = $send;
703 if ( ! empty( $checked ) )
704 $response['wp-check-locked-posts'] = $checked;
708 add_filter( 'heartbeat_received', 'wp_check_locked_posts', 10, 3 );
711 * Check lock status on the New/Edit Post screen and refresh the lock
715 function 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'];
720 if ( ! $post_id = absint( $received['post_id'] ) )
723 if ( ! current_user_can('edit_post', $post_id) )
726 if ( ( $user_id = wp_check_post_lock( $post_id ) ) && ( $user = get_userdata( $user_id ) ) ) {
728 'text' => sprintf( __( '%s has taken over and is currently editing.' ), $user->display_name )
731 if ( $avatar = get_avatar( $user->ID, 64 ) ) {
732 if ( preg_match( "|src='([^']+)'|", $avatar, $matches ) )
733 $error['avatar_src'] = $matches[1];
736 $send['lock_error'] = $error;
738 if ( $new_lock = wp_set_post_lock( $post_id ) )
739 $send['new_lock'] = implode( ':', $new_lock );
742 $response['wp-refresh-post-lock'] = $send;
747 add_filter( 'heartbeat_received', 'wp_refresh_post_lock', 10, 3 );
750 * Check nonce expiration on the New/Edit Post screen and refresh if needed
754 function 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 );
759 if ( ! $post_id = absint( $received['post_id'] ) )
762 if ( ! current_user_can( 'edit_post', $post_id ) || empty( $received['post_nonce'] ) )
765 if ( 2 === wp_verify_nonce( $received['post_nonce'], 'update-post_' . $post_id ) ) {
766 $response['wp-refresh-post-nonces'] = 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 ),
774 'heartbeatNonce' => wp_create_nonce( 'heartbeat-nonce' ),
781 add_filter( 'heartbeat_received', 'wp_refresh_post_nonces', 10, 3 );
784 * Disable suspension of Heartbeat on the Add/Edit Post screens.
788 * @param array $settings An array of Heartbeat settings.
789 * @return array Filtered Heartbeat settings.
791 function wp_heartbeat_set_suspension( $settings ) {
794 if ( 'post.php' === $pagenow || 'post-new.php' === $pagenow ) {
795 $settings['suspension'] = 'disable';
800 add_filter( 'heartbeat_settings', 'wp_heartbeat_set_suspension' );
803 * Autosave with heartbeat
807 function heartbeat_autosave( $response, $data ) {
808 if ( ! empty( $data['wp_autosave'] ) ) {
809 $saved = wp_autosave( $data['wp_autosave'] );
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.' ) );
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 ) ) );
825 // Run later as we have to set DOING_AUTOSAVE for back-compat
826 add_filter( 'heartbeat_received', 'heartbeat_autosave', 500, 2 );