home *** CD-ROM | disk | FTP | other *** search
/ HTML Examples / WP.iso / wordpress / wp-admin / includes / misc.php < prev    next >
Encoding:
PHP Script  |  2017-11-20  |  34.8 KB  |  1,214 lines

  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.      * Filters 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 {@see '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.      * Filters 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.  * Extracts strings from between the BEGIN and END markers in the .htaccess file.
  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.     $markerdata = explode( "\n", implode( '', file( $filename ) ) );
  75.  
  76.     $state = false;
  77.     foreach ( $markerdata as $markerline ) {
  78.         if ( false !== strpos( $markerline, '# END ' . $marker ) ) {
  79.             $state = false;
  80.         }
  81.         if ( $state ) {
  82.             $result[] = $markerline;
  83.         }
  84.         if ( false !== strpos( $markerline, '# BEGIN ' . $marker ) ) {
  85.             $state = true;
  86.         }
  87.     }
  88.  
  89.     return $result;
  90. }
  91.  
  92. /**
  93.  * Inserts an array of strings into a file (.htaccess ), placing it between
  94.  * BEGIN and END markers.
  95.  *
  96.  * Replaces existing marked info. Retains surrounding
  97.  * data. Creates file if none exists.
  98.  *
  99.  * @since 1.5.0
  100.  *
  101.  * @param string       $filename  Filename to alter.
  102.  * @param string       $marker    The marker to alter.
  103.  * @param array|string $insertion The new content to insert.
  104.  * @return bool True on write success, false on failure.
  105.  */
  106. function insert_with_markers( $filename, $marker, $insertion ) {
  107.     if ( ! file_exists( $filename ) ) {
  108.         if ( ! is_writable( dirname( $filename ) ) ) {
  109.             return false;
  110.         }
  111.         if ( ! touch( $filename ) ) {
  112.             return false;
  113.         }
  114.     } elseif ( ! is_writeable( $filename ) ) {
  115.         return false;
  116.     }
  117.  
  118.     if ( ! is_array( $insertion ) ) {
  119.         $insertion = explode( "\n", $insertion );
  120.     }
  121.  
  122.     $start_marker = "# BEGIN {$marker}";
  123.     $end_marker   = "# END {$marker}";
  124.  
  125.     $fp = fopen( $filename, 'r+' );
  126.     if ( ! $fp ) {
  127.         return false;
  128.     }
  129.  
  130.     // Attempt to get a lock. If the filesystem supports locking, this will block until the lock is acquired.
  131.     flock( $fp, LOCK_EX );
  132.  
  133.     $lines = array();
  134.     while ( ! feof( $fp ) ) {
  135.         $lines[] = rtrim( fgets( $fp ), "\r\n" );
  136.     }
  137.  
  138.     // Split out the existing file into the preceding lines, and those that appear after the marker
  139.     $pre_lines = $post_lines = $existing_lines = array();
  140.     $found_marker = $found_end_marker = false;
  141.     foreach ( $lines as $line ) {
  142.         if ( ! $found_marker && false !== strpos( $line, $start_marker ) ) {
  143.             $found_marker = true;
  144.             continue;
  145.         } elseif ( ! $found_end_marker && false !== strpos( $line, $end_marker ) ) {
  146.             $found_end_marker = true;
  147.             continue;
  148.         }
  149.         if ( ! $found_marker ) {
  150.             $pre_lines[] = $line;
  151.         } elseif ( $found_marker && $found_end_marker ) {
  152.             $post_lines[] = $line;
  153.         } else {
  154.             $existing_lines[] = $line;
  155.         }
  156.     }
  157.  
  158.     // Check to see if there was a change
  159.     if ( $existing_lines === $insertion ) {
  160.         flock( $fp, LOCK_UN );
  161.         fclose( $fp );
  162.  
  163.         return true;
  164.     }
  165.  
  166.     // Generate the new file data
  167.     $new_file_data = implode( "\n", array_merge(
  168.         $pre_lines,
  169.         array( $start_marker ),
  170.         $insertion,
  171.         array( $end_marker ),
  172.         $post_lines
  173.     ) );
  174.  
  175.     // Write to the start of the file, and truncate it to that length
  176.     fseek( $fp, 0 );
  177.     $bytes = fwrite( $fp, $new_file_data );
  178.     if ( $bytes ) {
  179.         ftruncate( $fp, ftell( $fp ) );
  180.     }
  181.     fflush( $fp );
  182.     flock( $fp, LOCK_UN );
  183.     fclose( $fp );
  184.  
  185.     return (bool) $bytes;
  186. }
  187.  
  188. /**
  189.  * Updates the htaccess file with the current rules if it is writable.
  190.  *
  191.  * Always writes to the file if it exists and is writable to ensure that we
  192.  * blank out old rules.
  193.  *
  194.  * @since 1.5.0
  195.  *
  196.  * @global WP_Rewrite $wp_rewrite
  197.  */
  198. function save_mod_rewrite_rules() {
  199.     if ( is_multisite() )
  200.         return;
  201.  
  202.     global $wp_rewrite;
  203.  
  204.     $home_path = get_home_path();
  205.     $htaccess_file = $home_path.'.htaccess';
  206.  
  207.     /*
  208.      * If the file doesn't already exist check for write access to the directory
  209.      * and whether we have some rules. Else check for write access to the file.
  210.      */
  211.     if ((!file_exists($htaccess_file) && is_writable($home_path) && $wp_rewrite->using_mod_rewrite_permalinks()) || is_writable($htaccess_file)) {
  212.         if ( got_mod_rewrite() ) {
  213.             $rules = explode( "\n", $wp_rewrite->mod_rewrite_rules() );
  214.             return insert_with_markers( $htaccess_file, 'WordPress', $rules );
  215.         }
  216.     }
  217.  
  218.     return false;
  219. }
  220.  
  221. /**
  222.  * Updates the IIS web.config file with the current rules if it is writable.
  223.  * If the permalinks do not require rewrite rules then the rules are deleted from the web.config file.
  224.  *
  225.  * @since 2.8.0
  226.  *
  227.  * @global WP_Rewrite $wp_rewrite
  228.  *
  229.  * @return bool True if web.config was updated successfully
  230.  */
  231. function iis7_save_url_rewrite_rules(){
  232.     if ( is_multisite() )
  233.         return;
  234.  
  235.     global $wp_rewrite;
  236.  
  237.     $home_path = get_home_path();
  238.     $web_config_file = $home_path . 'web.config';
  239.  
  240.     // Using win_is_writable() instead of is_writable() because of a bug in Windows PHP
  241.     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) ) ) {
  242.         $rule = $wp_rewrite->iis7_url_rewrite_rules(false, '', '');
  243.         if ( ! empty($rule) ) {
  244.             return iis7_add_rewrite_rule($web_config_file, $rule);
  245.         } else {
  246.             return iis7_delete_rewrite_rule($web_config_file);
  247.         }
  248.     }
  249.     return false;
  250. }
  251.  
  252. /**
  253.  * Update the "recently-edited" file for the plugin or theme editor.
  254.  *
  255.  * @since 1.5.0
  256.  *
  257.  * @param string $file
  258.  */
  259. function update_recently_edited( $file ) {
  260.     $oldfiles = (array ) get_option( 'recently_edited' );
  261.     if ( $oldfiles ) {
  262.         $oldfiles = array_reverse( $oldfiles );
  263.         $oldfiles[] = $file;
  264.         $oldfiles = array_reverse( $oldfiles );
  265.         $oldfiles = array_unique( $oldfiles );
  266.         if ( 5 < count( $oldfiles ))
  267.             array_pop( $oldfiles );
  268.     } else {
  269.         $oldfiles[] = $file;
  270.     }
  271.     update_option( 'recently_edited', $oldfiles );
  272. }
  273.  
  274. /**
  275.  * Makes a tree structure for the Theme Editor's file list.
  276.  *
  277.  * @since 4.9.0
  278.  * @access private
  279.  *
  280.  * @param array $allowed_files List of theme file paths.
  281.  * @return array Tree structure for listing theme files.
  282.  */
  283. function wp_make_theme_file_tree( $allowed_files ) {
  284.     $tree_list = array();
  285.     foreach ( $allowed_files as $file_name => $absolute_filename ) {
  286.         $list = explode( '/', $file_name );
  287.         $last_dir = &$tree_list;
  288.         foreach ( $list as $dir ) {
  289.             $last_dir =& $last_dir[ $dir ];
  290.         }
  291.         $last_dir = $file_name;
  292.     }
  293.     return $tree_list;
  294. }
  295.  
  296. /**
  297.  * Outputs the formatted file list for the Theme Editor.
  298.  *
  299.  * @since 4.9.0
  300.  * @access private
  301.  *
  302.  * @param array|string $tree  List of file/folder paths, or filename.
  303.  * @param int          $level The aria-level for the current iteration.
  304.  * @param int          $size  The aria-setsize for the current iteration.
  305.  * @param int          $index The aria-posinset for the current iteration.
  306.  */
  307. function wp_print_theme_file_tree( $tree, $level = 2, $size = 1, $index = 1 ) {
  308.     global $relative_file, $stylesheet;
  309.  
  310.     if ( is_array( $tree ) ) {
  311.         $index = 0;
  312.         $size = count( $tree );
  313.         foreach ( $tree as $label => $theme_file ) :
  314.             $index++;
  315.             if ( ! is_array( $theme_file ) ) {
  316.                 wp_print_theme_file_tree( $theme_file, $level, $index, $size );
  317.                 continue;
  318.             }
  319.             ?>
  320.             <li role="treeitem" aria-expanded="true" tabindex="-1"
  321.                 aria-level="<?php echo esc_attr( $level ); ?>"
  322.                 aria-setsize="<?php echo esc_attr( $size ); ?>"
  323.                 aria-posinset="<?php echo esc_attr( $index ); ?>">
  324.                 <span class="folder-label"><?php echo esc_html( $label ); ?> <span class="screen-reader-text"><?php _e( 'folder' ); ?></span><span aria-hidden="true" class="icon"></span></span>
  325.                 <ul role="group" class="tree-folder"><?php wp_print_theme_file_tree( $theme_file, $level + 1, $index, $size ); ?></ul>
  326.             </li>
  327.             <?php
  328.         endforeach;
  329.     } else {
  330.         $filename = $tree;
  331.         $url = add_query_arg(
  332.             array(
  333.                 'file' => rawurlencode( $tree ),
  334.                 'theme' => rawurlencode( $stylesheet ),
  335.             ),
  336.             self_admin_url( 'theme-editor.php' )
  337.         );
  338.         ?>
  339.         <li role="none" class="<?php echo esc_attr( $relative_file === $filename ? 'current-file' : '' ); ?>">
  340.             <a role="treeitem" tabindex="<?php echo esc_attr( $relative_file === $filename ? '0' : '-1' ); ?>"
  341.                 href="<?php echo esc_url( $url ); ?>"
  342.                 aria-level="<?php echo esc_attr( $level ); ?>"
  343.                 aria-setsize="<?php echo esc_attr( $size ); ?>"
  344.                 aria-posinset="<?php echo esc_attr( $index ); ?>">
  345.                 <?php
  346.                 $file_description = esc_html( get_file_description( $filename ) );
  347.                 if ( $file_description !== $filename && basename( $filename ) !== $file_description ) {
  348.                     $file_description .= '<br /><span class="nonessential">(' . esc_html( $filename ) . ')</span>';
  349.                 }
  350.  
  351.                 if ( $relative_file === $filename ) {
  352.                     echo '<span class="notice notice-info">' . $file_description . '</span>';
  353.                 } else {
  354.                     echo $file_description;
  355.                 }
  356.                 ?>
  357.             </a>
  358.         </li>
  359.         <?php
  360.     }
  361. }
  362.  
  363. /**
  364.  * Makes a tree structure for the Plugin Editor's file list.
  365.  *
  366.  * @since 4.9.0
  367.  * @access private
  368.  *
  369.  * @param string $plugin_editable_files List of plugin file paths.
  370.  * @return array Tree structure for listing plugin files.
  371.  */
  372. function wp_make_plugin_file_tree( $plugin_editable_files ) {
  373.     $tree_list = array();
  374.     foreach ( $plugin_editable_files as $plugin_file ) {
  375.         $list = explode( '/', preg_replace( '#^.+?/#', '', $plugin_file ) );
  376.         $last_dir = &$tree_list;
  377.         foreach ( $list as $dir ) {
  378.             $last_dir =& $last_dir[ $dir ];
  379.         }
  380.         $last_dir = $plugin_file;
  381.     }
  382.     return $tree_list;
  383. }
  384.  
  385. /**
  386.  * Outputs the formatted file list for the Plugin Editor.
  387.  *
  388.  * @since 4.9.0
  389.  * @access private
  390.  *
  391.  * @param array|string $tree  List of file/folder paths, or filename.
  392.  * @param string       $label Name of file or folder to print.
  393.  * @param int          $level The aria-level for the current iteration.
  394.  * @param int          $size  The aria-setsize for the current iteration.
  395.  * @param int          $index The aria-posinset for the current iteration.
  396.  */
  397. function wp_print_plugin_file_tree( $tree, $label = '', $level = 2, $size = 1, $index = 1 ) {
  398.     global $file, $plugin;
  399.     if ( is_array( $tree ) ) {
  400.         $index = 0;
  401.         $size = count( $tree );
  402.         foreach ( $tree as $label => $plugin_file ) :
  403.             $index++;
  404.             if ( ! is_array( $plugin_file ) ) {
  405.                 wp_print_plugin_file_tree( $plugin_file, $label, $level, $index, $size );
  406.                 continue;
  407.             }
  408.             ?>
  409.             <li role="treeitem" aria-expanded="true" tabindex="-1"
  410.                 aria-level="<?php echo esc_attr( $level ); ?>"
  411.                 aria-setsize="<?php echo esc_attr( $size ); ?>"
  412.                 aria-posinset="<?php echo esc_attr( $index ); ?>">
  413.                 <span class="folder-label"><?php echo esc_html( $label ); ?> <span class="screen-reader-text"><?php _e( 'folder' ); ?></span><span aria-hidden="true" class="icon"></span></span>
  414.                 <ul role="group" class="tree-folder"><?php wp_print_plugin_file_tree( $plugin_file, '', $level + 1, $index, $size ); ?></ul>
  415.             </li>
  416.             <?php
  417.         endforeach;
  418.     } else {
  419.         $url = add_query_arg(
  420.             array(
  421.                 'file' => rawurlencode( $tree ),
  422.                 'plugin' => rawurlencode( $plugin ),
  423.             ),
  424.             self_admin_url( 'plugin-editor.php' )
  425.         );
  426.         ?>
  427.         <li role="none" class="<?php echo esc_attr( $file === $tree ? 'current-file' : '' ); ?>">
  428.             <a role="treeitem" tabindex="<?php echo esc_attr( $file === $tree ? '0' : '-1' ); ?>"
  429.                 href="<?php echo esc_url( $url ); ?>"
  430.                 aria-level="<?php echo esc_attr( $level ); ?>"
  431.                 aria-setsize="<?php echo esc_attr( $size ); ?>"
  432.                 aria-posinset="<?php echo esc_attr( $index ); ?>">
  433.                 <?php
  434.                 if ( $file === $tree ) {
  435.                     echo '<span class="notice notice-info">' . esc_html( $label ) . '</span>';
  436.                 } else {
  437.                     echo esc_html( $label );
  438.                 }
  439.                 ?>
  440.             </a>
  441.         </li>
  442.         <?php
  443.     }
  444. }
  445.  
  446. /**
  447.  * Flushes rewrite rules if siteurl, home or page_on_front changed.
  448.  *
  449.  * @since 2.1.0
  450.  *
  451.  * @param string $old_value
  452.  * @param string $value
  453.  */
  454. function update_home_siteurl( $old_value, $value ) {
  455.     if ( wp_installing() )
  456.         return;
  457.  
  458.     if ( is_multisite() && ms_is_switched() ) {
  459.         delete_option( 'rewrite_rules' );
  460.     } else {
  461.         flush_rewrite_rules();
  462.     }
  463. }
  464.  
  465.  
  466. /**
  467.  * Resets global variables based on $_GET and $_POST
  468.  *
  469.  * This function resets global variables based on the names passed
  470.  * in the $vars array to the value of $_POST[$var] or $_GET[$var] or ''
  471.  * if neither is defined.
  472.  *
  473.  * @since 2.0.0
  474.  *
  475.  * @param array $vars An array of globals to reset.
  476.  */
  477. function wp_reset_vars( $vars ) {
  478.     foreach ( $vars as $var ) {
  479.         if ( empty( $_POST[ $var ] ) ) {
  480.             if ( empty( $_GET[ $var ] ) ) {
  481.                 $GLOBALS[ $var ] = '';
  482.             } else {
  483.                 $GLOBALS[ $var ] = $_GET[ $var ];
  484.             }
  485.         } else {
  486.             $GLOBALS[ $var ] = $_POST[ $var ];
  487.         }
  488.     }
  489. }
  490.  
  491. /**
  492.  * Displays the given administration message.
  493.  *
  494.  * @since 2.1.0
  495.  *
  496.  * @param string|WP_Error $message
  497.  */
  498. function show_message($message) {
  499.     if ( is_wp_error($message) ){
  500.         if ( $message->get_error_data() && is_string( $message->get_error_data() ) )
  501.             $message = $message->get_error_message() . ': ' . $message->get_error_data();
  502.         else
  503.             $message = $message->get_error_message();
  504.     }
  505.     echo "<p>$message</p>\n";
  506.     wp_ob_end_flush_all();
  507.     flush();
  508. }
  509.  
  510. /**
  511.  * @since 2.8.0
  512.  *
  513.  * @param string $content
  514.  * @return array
  515.  */
  516. function wp_doc_link_parse( $content ) {
  517.     if ( !is_string( $content ) || empty( $content ) )
  518.         return array();
  519.  
  520.     if ( !function_exists('token_get_all') )
  521.         return array();
  522.  
  523.     $tokens = token_get_all( $content );
  524.     $count = count( $tokens );
  525.     $functions = array();
  526.     $ignore_functions = array();
  527.     for ( $t = 0; $t < $count - 2; $t++ ) {
  528.         if ( ! is_array( $tokens[ $t ] ) ) {
  529.             continue;
  530.         }
  531.  
  532.         if ( T_STRING == $tokens[ $t ][0] && ( '(' == $tokens[ $t + 1 ] || '(' == $tokens[ $t + 2 ] ) ) {
  533.             // If it's a function or class defined locally, there's not going to be any docs available
  534.             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] ) ) {
  535.                 $ignore_functions[] = $tokens[$t][1];
  536.             }
  537.             // Add this to our stack of unique references
  538.             $functions[] = $tokens[$t][1];
  539.         }
  540.     }
  541.  
  542.     $functions = array_unique( $functions );
  543.     sort( $functions );
  544.  
  545.     /**
  546.      * Filters the list of functions and classes to be ignored from the documentation lookup.
  547.      *
  548.      * @since 2.8.0
  549.      *
  550.      * @param array $ignore_functions Functions and classes to be ignored.
  551.      */
  552.     $ignore_functions = apply_filters( 'documentation_ignore_functions', $ignore_functions );
  553.  
  554.     $ignore_functions = array_unique( $ignore_functions );
  555.  
  556.     $out = array();
  557.     foreach ( $functions as $function ) {
  558.         if ( in_array( $function, $ignore_functions ) )
  559.             continue;
  560.         $out[] = $function;
  561.     }
  562.  
  563.     return $out;
  564. }
  565.  
  566. /**
  567.  * Saves option for number of rows when listing posts, pages, comments, etc.
  568.  *
  569.  * @since 2.8.0
  570.  */
  571. function set_screen_options() {
  572.  
  573.     if ( isset($_POST['wp_screen_options']) && is_array($_POST['wp_screen_options']) ) {
  574.         check_admin_referer( 'screen-options-nonce', 'screenoptionnonce' );
  575.  
  576.         if ( !$user = wp_get_current_user() )
  577.             return;
  578.         $option = $_POST['wp_screen_options']['option'];
  579.         $value = $_POST['wp_screen_options']['value'];
  580.  
  581.         if ( $option != sanitize_key( $option ) )
  582.             return;
  583.  
  584.         $map_option = $option;
  585.         $type = str_replace('edit_', '', $map_option);
  586.         $type = str_replace('_per_page', '', $type);
  587.         if ( in_array( $type, get_taxonomies() ) )
  588.             $map_option = 'edit_tags_per_page';
  589.         elseif ( in_array( $type, get_post_types() ) )
  590.             $map_option = 'edit_per_page';
  591.         else
  592.             $option = str_replace('-', '_', $option);
  593.  
  594.         switch ( $map_option ) {
  595.             case 'edit_per_page':
  596.             case 'users_per_page':
  597.             case 'edit_comments_per_page':
  598.             case 'upload_per_page':
  599.             case 'edit_tags_per_page':
  600.             case 'plugins_per_page':
  601.             // Network admin
  602.             case 'sites_network_per_page':
  603.             case 'users_network_per_page':
  604.             case 'site_users_network_per_page':
  605.             case 'plugins_network_per_page':
  606.             case 'themes_network_per_page':
  607.             case 'site_themes_network_per_page':
  608.                 $value = (int) $value;
  609.                 if ( $value < 1 || $value > 999 )
  610.                     return;
  611.                 break;
  612.             default:
  613.  
  614.                 /**
  615.                  * Filters a screen option value before it is set.
  616.                  *
  617.                  * The filter can also be used to modify non-standard [items]_per_page
  618.                  * settings. See the parent function for a full list of standard options.
  619.                  *
  620.                  * Returning false to the filter will skip saving the current option.
  621.                  *
  622.                  * @since 2.8.0
  623.                  *
  624.                  * @see set_screen_options()
  625.                  *
  626.                  * @param bool|int $value  Screen option value. Default false to skip.
  627.                  * @param string   $option The option name.
  628.                  * @param int      $value  The number of rows to use.
  629.                  */
  630.                 $value = apply_filters( 'set-screen-option', false, $option, $value );
  631.  
  632.                 if ( false === $value )
  633.                     return;
  634.                 break;
  635.         }
  636.  
  637.         update_user_meta($user->ID, $option, $value);
  638.  
  639.         $url = remove_query_arg( array( 'pagenum', 'apage', 'paged' ), wp_get_referer() );
  640.         if ( isset( $_POST['mode'] ) ) {
  641.             $url = add_query_arg( array( 'mode' => $_POST['mode'] ), $url );
  642.         }
  643.  
  644.         wp_safe_redirect( $url );
  645.         exit;
  646.     }
  647. }
  648.  
  649. /**
  650.  * Check if rewrite rule for WordPress already exists in the IIS 7+ configuration file
  651.  *
  652.  * @since 2.8.0
  653.  *
  654.  * @return bool
  655.  * @param string $filename The file path to the configuration file
  656.  */
  657. function iis7_rewrite_rule_exists($filename) {
  658.     if ( ! file_exists($filename) )
  659.         return false;
  660.     if ( ! class_exists( 'DOMDocument', false ) ) {
  661.         return false;
  662.     }
  663.  
  664.     $doc = new DOMDocument();
  665.     if ( $doc->load($filename) === false )
  666.         return false;
  667.     $xpath = new DOMXPath($doc);
  668.     $rules = $xpath->query('/configuration/system.webServer/rewrite/rules/rule[starts-with(@name,\'wordpress\')] | /configuration/system.webServer/rewrite/rules/rule[starts-with(@name,\'WordPress\')]');
  669.     if ( $rules->length == 0 )
  670.         return false;
  671.     else
  672.         return true;
  673. }
  674.  
  675. /**
  676.  * Delete WordPress rewrite rule from web.config file if it exists there
  677.  *
  678.  * @since 2.8.0
  679.  *
  680.  * @param string $filename Name of the configuration file
  681.  * @return bool
  682.  */
  683. function iis7_delete_rewrite_rule($filename) {
  684.     // If configuration file does not exist then rules also do not exist so there is nothing to delete
  685.     if ( ! file_exists($filename) )
  686.         return true;
  687.  
  688.     if ( ! class_exists( 'DOMDocument', false ) ) {
  689.         return false;
  690.     }
  691.  
  692.     $doc = new DOMDocument();
  693.     $doc->preserveWhiteSpace = false;
  694.  
  695.     if ( $doc -> load($filename) === false )
  696.         return false;
  697.     $xpath = new DOMXPath($doc);
  698.     $rules = $xpath->query('/configuration/system.webServer/rewrite/rules/rule[starts-with(@name,\'wordpress\')] | /configuration/system.webServer/rewrite/rules/rule[starts-with(@name,\'WordPress\')]');
  699.     if ( $rules->length > 0 ) {
  700.         $child = $rules->item(0);
  701.         $parent = $child->parentNode;
  702.         $parent->removeChild($child);
  703.         $doc->formatOutput = true;
  704.         saveDomDocument($doc, $filename);
  705.     }
  706.     return true;
  707. }
  708.  
  709. /**
  710.  * Add WordPress rewrite rule to the IIS 7+ configuration file.
  711.  *
  712.  * @since 2.8.0
  713.  *
  714.  * @param string $filename The file path to the configuration file
  715.  * @param string $rewrite_rule The XML fragment with URL Rewrite rule
  716.  * @return bool
  717.  */
  718. function iis7_add_rewrite_rule($filename, $rewrite_rule) {
  719.     if ( ! class_exists( 'DOMDocument', false ) ) {
  720.         return false;
  721.     }
  722.  
  723.     // If configuration file does not exist then we create one.
  724.     if ( ! file_exists($filename) ) {
  725.         $fp = fopen( $filename, 'w');
  726.         fwrite($fp, '<configuration/>');
  727.         fclose($fp);
  728.     }
  729.  
  730.     $doc = new DOMDocument();
  731.     $doc->preserveWhiteSpace = false;
  732.  
  733.     if ( $doc->load($filename) === false )
  734.         return false;
  735.  
  736.     $xpath = new DOMXPath($doc);
  737.  
  738.     // First check if the rule already exists as in that case there is no need to re-add it
  739.     $wordpress_rules = $xpath->query('/configuration/system.webServer/rewrite/rules/rule[starts-with(@name,\'wordpress\')] | /configuration/system.webServer/rewrite/rules/rule[starts-with(@name,\'WordPress\')]');
  740.     if ( $wordpress_rules->length > 0 )
  741.         return true;
  742.  
  743.     // Check the XPath to the rewrite rule and create XML nodes if they do not exist
  744.     $xmlnodes = $xpath->query('/configuration/system.webServer/rewrite/rules');
  745.     if ( $xmlnodes->length > 0 ) {
  746.         $rules_node = $xmlnodes->item(0);
  747.     } else {
  748.         $rules_node = $doc->createElement('rules');
  749.  
  750.         $xmlnodes = $xpath->query('/configuration/system.webServer/rewrite');
  751.         if ( $xmlnodes->length > 0 ) {
  752.             $rewrite_node = $xmlnodes->item(0);
  753.             $rewrite_node->appendChild($rules_node);
  754.         } else {
  755.             $rewrite_node = $doc->createElement('rewrite');
  756.             $rewrite_node->appendChild($rules_node);
  757.  
  758.             $xmlnodes = $xpath->query('/configuration/system.webServer');
  759.             if ( $xmlnodes->length > 0 ) {
  760.                 $system_webServer_node = $xmlnodes->item(0);
  761.                 $system_webServer_node->appendChild($rewrite_node);
  762.             } else {
  763.                 $system_webServer_node = $doc->createElement('system.webServer');
  764.                 $system_webServer_node->appendChild($rewrite_node);
  765.  
  766.                 $xmlnodes = $xpath->query('/configuration');
  767.                 if ( $xmlnodes->length > 0 ) {
  768.                     $config_node = $xmlnodes->item(0);
  769.                     $config_node->appendChild($system_webServer_node);
  770.                 } else {
  771.                     $config_node = $doc->createElement('configuration');
  772.                     $doc->appendChild($config_node);
  773.                     $config_node->appendChild($system_webServer_node);
  774.                 }
  775.             }
  776.         }
  777.     }
  778.  
  779.     $rule_fragment = $doc->createDocumentFragment();
  780.     $rule_fragment->appendXML($rewrite_rule);
  781.     $rules_node->appendChild($rule_fragment);
  782.  
  783.     $doc->encoding = "UTF-8";
  784.     $doc->formatOutput = true;
  785.     saveDomDocument($doc, $filename);
  786.  
  787.     return true;
  788. }
  789.  
  790. /**
  791.  * Saves the XML document into a file
  792.  *
  793.  * @since 2.8.0
  794.  *
  795.  * @param DOMDocument $doc
  796.  * @param string $filename
  797.  */
  798. function saveDomDocument($doc, $filename) {
  799.     $config = $doc->saveXML();
  800.     $config = preg_replace("/([^\r])\n/", "$1\r\n", $config);
  801.     $fp = fopen($filename, 'w');
  802.     fwrite($fp, $config);
  803.     fclose($fp);
  804. }
  805.  
  806. /**
  807.  * Display the default admin color scheme picker (Used in user-edit.php)
  808.  *
  809.  * @since 3.0.0
  810.  *
  811.  * @global array $_wp_admin_css_colors
  812.  *
  813.  * @param int $user_id User ID.
  814.  */
  815. function admin_color_scheme_picker( $user_id ) {
  816.     global $_wp_admin_css_colors;
  817.  
  818.     ksort( $_wp_admin_css_colors );
  819.  
  820.     if ( isset( $_wp_admin_css_colors['fresh'] ) ) {
  821.         // Set Default ('fresh') and Light should go first.
  822.         $_wp_admin_css_colors = array_filter( array_merge( array( 'fresh' => '', 'light' => '' ), $_wp_admin_css_colors ) );
  823.     }
  824.  
  825.     $current_color = get_user_option( 'admin_color', $user_id );
  826.  
  827.     if ( empty( $current_color ) || ! isset( $_wp_admin_css_colors[ $current_color ] ) ) {
  828.         $current_color = 'fresh';
  829.     }
  830.  
  831.     ?>
  832.     <fieldset id="color-picker" class="scheme-list">
  833.         <legend class="screen-reader-text"><span><?php _e( 'Admin Color Scheme' ); ?></span></legend>
  834.         <?php
  835.         wp_nonce_field( 'save-color-scheme', 'color-nonce', false );
  836.         foreach ( $_wp_admin_css_colors as $color => $color_info ) :
  837.  
  838.             ?>
  839.             <div class="color-option <?php echo ( $color == $current_color ) ? 'selected' : ''; ?>">
  840.                 <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 ); ?> />
  841.                 <input type="hidden" class="css_url" value="<?php echo esc_url( $color_info->url ); ?>" />
  842.                 <input type="hidden" class="icon_colors" value="<?php echo esc_attr( wp_json_encode( array( 'icons' => $color_info->icon_colors ) ) ); ?>" />
  843.                 <label for="admin_color_<?php echo esc_attr( $color ); ?>"><?php echo esc_html( $color_info->name ); ?></label>
  844.                 <table class="color-palette">
  845.                     <tr>
  846.                     <?php
  847.  
  848.                     foreach ( $color_info->colors as $html_color ) {
  849.                         ?>
  850.                         <td style="background-color: <?php echo esc_attr( $html_color ); ?>"> </td>
  851.                         <?php
  852.                     }
  853.  
  854.                     ?>
  855.                     </tr>
  856.                 </table>
  857.             </div>
  858.             <?php
  859.  
  860.         endforeach;
  861.  
  862.     ?>
  863.     </fieldset>
  864.     <?php
  865. }
  866.  
  867. /**
  868.  *
  869.  * @global array $_wp_admin_css_colors
  870.  */
  871. function wp_color_scheme_settings() {
  872.     global $_wp_admin_css_colors;
  873.  
  874.     $color_scheme = get_user_option( 'admin_color' );
  875.  
  876.     // It's possible to have a color scheme set that is no longer registered.
  877.     if ( empty( $_wp_admin_css_colors[ $color_scheme ] ) ) {
  878.         $color_scheme = 'fresh';
  879.     }
  880.  
  881.     if ( ! empty( $_wp_admin_css_colors[ $color_scheme ]->icon_colors ) ) {
  882.         $icon_colors = $_wp_admin_css_colors[ $color_scheme ]->icon_colors;
  883.     } elseif ( ! empty( $_wp_admin_css_colors['fresh']->icon_colors ) ) {
  884.         $icon_colors = $_wp_admin_css_colors['fresh']->icon_colors;
  885.     } else {
  886.         // Fall back to the default set of icon colors if the default scheme is missing.
  887.         $icon_colors = array( 'base' => '#82878c', 'focus' => '#00a0d2', 'current' => '#fff' );
  888.     }
  889.  
  890.     echo '<script type="text/javascript">var _wpColorScheme = ' . wp_json_encode( array( 'icons' => $icon_colors ) ) . ";</script>\n";
  891. }
  892.  
  893. /**
  894.  * @since 3.3.0
  895.  */
  896. function _ipad_meta() {
  897.     if ( wp_is_mobile() ) {
  898.         ?>
  899.         <meta name="viewport" id="viewport-meta" content="width=device-width, initial-scale=1">
  900.         <?php
  901.     }
  902. }
  903.  
  904. /**
  905.  * Check lock status for posts displayed on the Posts screen
  906.  *
  907.  * @since 3.6.0
  908.  *
  909.  * @param array  $response  The Heartbeat response.
  910.  * @param array  $data      The $_POST data sent.
  911.  * @param string $screen_id The screen id.
  912.  * @return array The Heartbeat response.
  913.  */
  914. function wp_check_locked_posts( $response, $data, $screen_id ) {
  915.     $checked = array();
  916.  
  917.     if ( array_key_exists( 'wp-check-locked-posts', $data ) && is_array( $data['wp-check-locked-posts'] ) ) {
  918.         foreach ( $data['wp-check-locked-posts'] as $key ) {
  919.             if ( ! $post_id = absint( substr( $key, 5 ) ) )
  920.                 continue;
  921.  
  922.             if ( ( $user_id = wp_check_post_lock( $post_id ) ) && ( $user = get_userdata( $user_id ) ) && current_user_can( 'edit_post', $post_id ) ) {
  923.                 $send = array( 'text' => sprintf( __( '%s is currently editing' ), $user->display_name ) );
  924.  
  925.                 if ( ( $avatar = get_avatar( $user->ID, 18 ) ) && preg_match( "|src='([^']+)'|", $avatar, $matches ) )
  926.                     $send['avatar_src'] = $matches[1];
  927.  
  928.                 $checked[$key] = $send;
  929.             }
  930.         }
  931.     }
  932.  
  933.     if ( ! empty( $checked ) )
  934.         $response['wp-check-locked-posts'] = $checked;
  935.  
  936.     return $response;
  937. }
  938.  
  939. /**
  940.  * Check lock status on the New/Edit Post screen and refresh the lock
  941.  *
  942.  * @since 3.6.0
  943.  *
  944.  * @param array  $response  The Heartbeat response.
  945.  * @param array  $data      The $_POST data sent.
  946.  * @param string $screen_id The screen id.
  947.  * @return array The Heartbeat response.
  948.  */
  949. function wp_refresh_post_lock( $response, $data, $screen_id ) {
  950.     if ( array_key_exists( 'wp-refresh-post-lock', $data ) ) {
  951.         $received = $data['wp-refresh-post-lock'];
  952.         $send = array();
  953.  
  954.         if ( ! $post_id = absint( $received['post_id'] ) )
  955.             return $response;
  956.  
  957.         if ( ! current_user_can('edit_post', $post_id) )
  958.             return $response;
  959.  
  960.         if ( ( $user_id = wp_check_post_lock( $post_id ) ) && ( $user = get_userdata( $user_id ) ) ) {
  961.             $error = array(
  962.                 'text' => sprintf( __( '%s has taken over and is currently editing.' ), $user->display_name )
  963.             );
  964.  
  965.             if ( $avatar = get_avatar( $user->ID, 64 ) ) {
  966.                 if ( preg_match( "|src='([^']+)'|", $avatar, $matches ) )
  967.                     $error['avatar_src'] = $matches[1];
  968.             }
  969.  
  970.             $send['lock_error'] = $error;
  971.         } else {
  972.             if ( $new_lock = wp_set_post_lock( $post_id ) )
  973.                 $send['new_lock'] = implode( ':', $new_lock );
  974.         }
  975.  
  976.         $response['wp-refresh-post-lock'] = $send;
  977.     }
  978.  
  979.     return $response;
  980. }
  981.  
  982. /**
  983.  * Check nonce expiration on the New/Edit Post screen and refresh if needed
  984.  *
  985.  * @since 3.6.0
  986.  *
  987.  * @param array  $response  The Heartbeat response.
  988.  * @param array  $data      The $_POST data sent.
  989.  * @param string $screen_id The screen id.
  990.  * @return array The Heartbeat response.
  991.  */
  992. function wp_refresh_post_nonces( $response, $data, $screen_id ) {
  993.     if ( array_key_exists( 'wp-refresh-post-nonces', $data ) ) {
  994.         $received = $data['wp-refresh-post-nonces'];
  995.         $response['wp-refresh-post-nonces'] = array( 'check' => 1 );
  996.  
  997.         if ( ! $post_id = absint( $received['post_id'] ) ) {
  998.             return $response;
  999.         }
  1000.  
  1001.         if ( ! current_user_can( 'edit_post', $post_id ) ) {
  1002.             return $response;
  1003.         }
  1004.  
  1005.         $response['wp-refresh-post-nonces'] = array(
  1006.             'replace' => array(
  1007.                 'getpermalinknonce' => wp_create_nonce('getpermalink'),
  1008.                 'samplepermalinknonce' => wp_create_nonce('samplepermalink'),
  1009.                 'closedpostboxesnonce' => wp_create_nonce('closedpostboxes'),
  1010.                 '_ajax_linking_nonce' => wp_create_nonce( 'internal-linking' ),
  1011.                 '_wpnonce' => wp_create_nonce( 'update-post_' . $post_id ),
  1012.             ),
  1013.             'heartbeatNonce' => wp_create_nonce( 'heartbeat-nonce' ),
  1014.         );
  1015.     }
  1016.  
  1017.     return $response;
  1018. }
  1019.  
  1020. /**
  1021.  * Disable suspension of Heartbeat on the Add/Edit Post screens.
  1022.  *
  1023.  * @since 3.8.0
  1024.  *
  1025.  * @global string $pagenow
  1026.  *
  1027.  * @param array $settings An array of Heartbeat settings.
  1028.  * @return array Filtered Heartbeat settings.
  1029.  */
  1030. function wp_heartbeat_set_suspension( $settings ) {
  1031.     global $pagenow;
  1032.  
  1033.     if ( 'post.php' === $pagenow || 'post-new.php' === $pagenow ) {
  1034.         $settings['suspension'] = 'disable';
  1035.     }
  1036.  
  1037.     return $settings;
  1038. }
  1039.  
  1040. /**
  1041.  * Autosave with heartbeat
  1042.  *
  1043.  * @since 3.9.0
  1044.  *
  1045.  * @param array $response The Heartbeat response.
  1046.  * @param array $data     The $_POST data sent.
  1047.  * @return array The Heartbeat response.
  1048.  */
  1049. function heartbeat_autosave( $response, $data ) {
  1050.     if ( ! empty( $data['wp_autosave'] ) ) {
  1051.         $saved = wp_autosave( $data['wp_autosave'] );
  1052.  
  1053.         if ( is_wp_error( $saved ) ) {
  1054.             $response['wp_autosave'] = array( 'success' => false, 'message' => $saved->get_error_message() );
  1055.         } elseif ( empty( $saved ) ) {
  1056.             $response['wp_autosave'] = array( 'success' => false, 'message' => __( 'Error while saving.' ) );
  1057.         } else {
  1058.             /* translators: draft saved date format, see https://secure.php.net/date */
  1059.             $draft_saved_date_format = __( 'g:i:s a' );
  1060.             /* translators: %s: date and time */
  1061.             $response['wp_autosave'] = array( 'success' => true, 'message' => sprintf( __( 'Draft saved at %s.' ), date_i18n( $draft_saved_date_format ) ) );
  1062.         }
  1063.     }
  1064.  
  1065.     return $response;
  1066. }
  1067.  
  1068. /**
  1069.  * Remove single-use URL parameters and create canonical link based on new URL.
  1070.  *
  1071.  * Remove specific query string parameters from a URL, create the canonical link,
  1072.  * put it in the admin header, and change the current URL to match.
  1073.  *
  1074.  * @since 4.2.0
  1075.  */
  1076. function wp_admin_canonical_url() {
  1077.     $removable_query_args = wp_removable_query_args();
  1078.  
  1079.     if ( empty( $removable_query_args ) ) {
  1080.         return;
  1081.     }
  1082.  
  1083.     // Ensure we're using an absolute URL.
  1084.     $current_url  = set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
  1085.     $filtered_url = remove_query_arg( $removable_query_args, $current_url );
  1086.     ?>
  1087.     <link id="wp-admin-canonical" rel="canonical" href="<?php echo esc_url( $filtered_url ); ?>" />
  1088.     <script>
  1089.         if ( window.history.replaceState ) {
  1090.             window.history.replaceState( null, null, document.getElementById( 'wp-admin-canonical' ).href + window.location.hash );
  1091.         }
  1092.     </script>
  1093. <?php
  1094. }
  1095.  
  1096. /**
  1097.  * Send a referrer policy header so referrers are not sent externally from administration screens.
  1098.  *
  1099.  * @since 4.9.0
  1100.  */
  1101. function wp_admin_headers() {
  1102.     $policy = 'same-origin';
  1103.  
  1104.     /**
  1105.      * Filters the admin referrer policy header value. Default 'same-origin'.
  1106.      *
  1107.      * @since 4.9.0
  1108.      * @link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy
  1109.      *
  1110.      * @param string $policy The referrer policy header value.
  1111.      */
  1112.     $policy = apply_filters( 'admin_referrer_policy', $policy );
  1113.  
  1114.     header( sprintf( 'Referrer-Policy: %s', $policy ) );
  1115. }
  1116.  
  1117. /**
  1118.  * Outputs JS that reloads the page if the user navigated to it with the Back or Forward button.
  1119.  *
  1120.  * Used on the Edit Post and Add New Post screens. Needed to ensure the page is not loaded from browser cache,
  1121.  * so the post title and editor content are the last saved versions. Ideally this script should run first in the head.
  1122.  *
  1123.  * @since 4.6.0
  1124.  */
  1125. function wp_page_reload_on_back_button_js() {
  1126.     ?>
  1127.     <script>
  1128.         if ( typeof performance !== 'undefined' && performance.navigation && performance.navigation.type === 2 ) {
  1129.             document.location.reload( true );
  1130.         }
  1131.     </script>
  1132.     <?php
  1133. }
  1134.  
  1135. /**
  1136.  * Send a confirmation request email when a change of site admin email address is attempted.
  1137.  *
  1138.  * The new site admin address will not become active until confirmed.
  1139.  *
  1140.  * @since 3.0.0
  1141.  * @since 4.9.0 This function was moved from wp-admin/includes/ms.php so it's no longer Multisite specific.
  1142.  *
  1143.  * @param string $old_value The old site admin email address.
  1144.  * @param string $value     The proposed new site admin email address.
  1145.  */
  1146. function update_option_new_admin_email( $old_value, $value ) {
  1147.     if ( $value == get_option( 'admin_email' ) || ! is_email( $value ) ) {
  1148.         return;
  1149.     }
  1150.  
  1151.     $hash = md5( $value . time() . mt_rand() );
  1152.     $new_admin_email = array(
  1153.         'hash'     => $hash,
  1154.         'newemail' => $value,
  1155.     );
  1156.     update_option( 'adminhash', $new_admin_email );
  1157.  
  1158.     $switched_locale = switch_to_locale( get_user_locale() );
  1159.  
  1160.     /* translators: Do not translate USERNAME, ADMIN_URL, EMAIL, SITENAME, SITEURL: those are placeholders. */
  1161.     $email_text = __( 'Howdy ###USERNAME###,
  1162.  
  1163. You recently requested to have the administration email address on
  1164. your site changed.
  1165.  
  1166. If this is correct, please click on the following link to change it:
  1167. ###ADMIN_URL###
  1168.  
  1169. You can safely ignore and delete this email if you do not want to
  1170. take this action.
  1171.  
  1172. This email has been sent to ###EMAIL###
  1173.  
  1174. Regards,
  1175. All at ###SITENAME###
  1176. ###SITEURL###' );
  1177.  
  1178.     /**
  1179.      * Filters the text of the email sent when a change of site admin email address is attempted.
  1180.      *
  1181.      * The following strings have a special meaning and will get replaced dynamically:
  1182.      * ###USERNAME###  The current user's username.
  1183.      * ###ADMIN_URL### The link to click on to confirm the email change.
  1184.      * ###EMAIL###     The proposed new site admin email address.
  1185.      * ###SITENAME###  The name of the site.
  1186.      * ###SITEURL###   The URL to the site.
  1187.      *
  1188.      * @since MU (3.0.0)
  1189.      * @since 4.9.0 This filter is no longer Multisite specific.
  1190.      *
  1191.      * @param string $email_text      Text in the email.
  1192.      * @param array  $new_admin_email {
  1193.      *     Data relating to the new site admin email address.
  1194.      *
  1195.      *     @type string $hash     The secure hash used in the confirmation link URL.
  1196.      *     @type string $newemail The proposed new site admin email address.
  1197.      * }
  1198.      */
  1199.     $content = apply_filters( 'new_admin_email_content', $email_text, $new_admin_email );
  1200.  
  1201.     $current_user = wp_get_current_user();
  1202.     $content = str_replace( '###USERNAME###', $current_user->user_login, $content );
  1203.     $content = str_replace( '###ADMIN_URL###', esc_url( self_admin_url( 'options.php?adminhash=' . $hash ) ), $content );
  1204.     $content = str_replace( '###EMAIL###', $value, $content );
  1205.     $content = str_replace( '###SITENAME###', wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ), $content );
  1206.     $content = str_replace( '###SITEURL###', home_url(), $content );
  1207.  
  1208.     wp_mail( $value, sprintf( __( '[%s] New Admin Email Address' ), wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ) ), $content );
  1209.  
  1210.     if ( $switched_locale ) {
  1211.         restore_previous_locale();
  1212.     }
  1213. }
  1214.