Advertisement
Guest User

đây_function.php

a guest
Oct 24th, 2014
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 145.39 KB | None | 0 0
  1. <?php
  2. /**
  3.  * Main WordPress API
  4.  *
  5.  * @package WordPress
  6.  */
  7.  
  8. require( ABSPATH . WPINC . '/option.php' );
  9.  
  10. /*
  11. * Thay doi trang dang nhap
  12. *
  13. *
  14. */
  15. /* Chuyển về trang đăng nhập nếu vào file wp-login.php */
  16. function redirect_login_page() {  
  17.     $login_page  = home_url();  
  18.     $page_viewed = basename($_SERVER['REQUEST_URI']);  
  19.  
  20.     if( $page_viewed == "wp-login.php" && $_SERVER['REQUEST_METHOD'] == 'GET') {  
  21.         wp_redirect($login_page);  
  22.         exit;  
  23.     }  
  24.     add_action('init','redirect_login_page');
  25. }  
  26.  
  27. /* Tự động chuyển đến một trang khác sau khi login */
  28. function my_login_redirect( $redirect_to, $request, $user ) {
  29.         //is there a user to check?
  30.         global $user;
  31.         if ( isset( $user->roles ) && is_array( $user->roles ) ) {
  32.                 //check for admins
  33.                 if ( in_array( 'administrator', $user->roles ) ) {
  34.                         // redirect them to the default place
  35.                         return admin_url();
  36.                 } else {
  37.                         return home_url();
  38.                 }
  39.         } else {
  40.                 return $redirect_to;
  41.         }
  42.         dd_filter( 'login_redirect', 'my_login_redirect', 10, 3 );
  43. }
  44.  
  45.  
  46. /* Kiểm tra lỗi đăng nhập */
  47. function login_failed() {  
  48.     $login_page  = home_url();  
  49.     wp_redirect( $login_page . '?login=failed' );  
  50.     exit;  
  51.     add_action( 'wp_login_failed', 'login_failed' );  
  52. }  
  53.  
  54.  
  55. function verify_username_password( $user, $username, $password ) {  
  56.     $login_page  = home_url( '/dang-nhap/' );  
  57.     if( $username == "" || $password == "" ) {  
  58.         wp_redirect( $login_page . "?login=empty" );  
  59.         exit;  
  60.     }  
  61.     add_filter( 'authenticate', 'verify_username_password', 1, 3);
  62. }  
  63.  
  64.  
  65. function homepage(){
  66.     wp_redirect(home_url());
  67.     exit();
  68. }
  69. add_action('wp-logout','homepage');
  70.  
  71. /**
  72.  * Convert given date string into a different format.
  73.  *
  74.  * $format should be either a PHP date format string, e.g. 'U' for a Unix
  75.  * timestamp, or 'G' for a Unix timestamp assuming that $date is GMT.
  76.  *
  77.  * If $translate is true then the given date and format string will
  78.  * be passed to date_i18n() for translation.
  79.  *
  80.  * @since 0.71
  81.  *
  82.  * @param string $format    Format of the date to return.
  83.  * @param string $date      Date string to convert.
  84.  * @param bool   $translate Whether the return date should be translated. Default true.
  85.  * @return string|int|bool Formatted date string or Unix timestamp. False if $date is empty.
  86.  */
  87. function mysql2date( $format, $date, $translate = true ) {
  88.     if ( empty( $date ) )
  89.         return false;
  90.  
  91.     if ( 'G' == $format )
  92.         return strtotime( $date . ' +0000' );
  93.  
  94.     $i = strtotime( $date );
  95.  
  96.     if ( 'U' == $format )
  97.         return $i;
  98.  
  99.     if ( $translate )
  100.         return date_i18n( $format, $i );
  101.     else
  102.         return date( $format, $i );
  103. }
  104.  
  105.  
  106.  
  107. /**
  108.  * Retrieve the current time based on specified type.
  109.  *
  110.  * The 'mysql' type will return the time in the format for MySQL DATETIME field.
  111.  * The 'timestamp' type will return the current timestamp.
  112.  * Other strings will be interpreted as PHP date formats (e.g. 'Y-m-d').
  113.  *
  114.  * If $gmt is set to either '1' or 'true', then both types will use GMT time.
  115.  * if $gmt is false, the output is adjusted with the GMT offset in the WordPress option.
  116.  *
  117.  * @since 1.0.0
  118.  *
  119.  * @param string   $type Type of time to retrieve. Accepts 'mysql', 'timestamp', or PHP date
  120.  *                       format string (e.g. 'Y-m-d').
  121.  * @param int|bool $gmt  Optional. Whether to use GMT timezone. Default false.
  122.  * @return int|string Integer if $type is 'timestamp', string otherwise.
  123.  */
  124. function current_time( $type, $gmt = 0 ) {
  125.     switch ( $type ) {
  126.         case 'mysql':
  127.             return ( $gmt ) ? gmdate( 'Y-m-d H:i:s' ) : gmdate( 'Y-m-d H:i:s', ( time() + ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS ) ) );
  128.         case 'timestamp':
  129.             return ( $gmt ) ? time() : time() + ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
  130.         default:
  131.             return ( $gmt ) ? date( $type ) : date( $type, time() + ( get_option( 'gmt_offset' ) * HOUR_IN_SECONDS ) );
  132.     }
  133. }
  134.  
  135. /**
  136.  * Retrieve the date in localized format, based on timestamp.
  137.  *
  138.  * If the locale specifies the locale month and weekday, then the locale will
  139.  * take over the format for the date. If it isn't, then the date format string
  140.  * will be used instead.
  141.  *
  142.  * @since 0.71
  143.  *
  144.  * @param string   $dateformatstring Format to display the date.
  145.  * @param bool|int $unixtimestamp    Optional. Unix timestamp. Default false.
  146.  * @param bool     $gmt              Optional. Whether to use GMT timezone. Default false.
  147.  *
  148.  * @return string The date, translated if locale specifies it.
  149.  */
  150. function date_i18n( $dateformatstring, $unixtimestamp = false, $gmt = false ) {
  151.     global $wp_locale;
  152.     $i = $unixtimestamp;
  153.  
  154.     if ( false === $i ) {
  155.         if ( ! $gmt )
  156.             $i = current_time( 'timestamp' );
  157.         else
  158.             $i = time();
  159.         // we should not let date() interfere with our
  160.         // specially computed timestamp
  161.         $gmt = true;
  162.     }
  163.  
  164.     /*
  165.      * Store original value for language with untypical grammars.
  166.      * See http://core.trac.wordpress.org/ticket/9396
  167.      */
  168.     $req_format = $dateformatstring;
  169.  
  170.     $datefunc = $gmt? 'gmdate' : 'date';
  171.  
  172.     if ( ( !empty( $wp_locale->month ) ) && ( !empty( $wp_locale->weekday ) ) ) {
  173.         $datemonth = $wp_locale->get_month( $datefunc( 'm', $i ) );
  174.         $datemonth_abbrev = $wp_locale->get_month_abbrev( $datemonth );
  175.         $dateweekday = $wp_locale->get_weekday( $datefunc( 'w', $i ) );
  176.         $dateweekday_abbrev = $wp_locale->get_weekday_abbrev( $dateweekday );
  177.         $datemeridiem = $wp_locale->get_meridiem( $datefunc( 'a', $i ) );
  178.         $datemeridiem_capital = $wp_locale->get_meridiem( $datefunc( 'A', $i ) );
  179.         $dateformatstring = ' '.$dateformatstring;
  180.         $dateformatstring = preg_replace( "/([^\\\])D/", "\\1" . backslashit( $dateweekday_abbrev ), $dateformatstring );
  181.         $dateformatstring = preg_replace( "/([^\\\])F/", "\\1" . backslashit( $datemonth ), $dateformatstring );
  182.         $dateformatstring = preg_replace( "/([^\\\])l/", "\\1" . backslashit( $dateweekday ), $dateformatstring );
  183.         $dateformatstring = preg_replace( "/([^\\\])M/", "\\1" . backslashit( $datemonth_abbrev ), $dateformatstring );
  184.         $dateformatstring = preg_replace( "/([^\\\])a/", "\\1" . backslashit( $datemeridiem ), $dateformatstring );
  185.         $dateformatstring = preg_replace( "/([^\\\])A/", "\\1" . backslashit( $datemeridiem_capital ), $dateformatstring );
  186.  
  187.         $dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
  188.     }
  189.     $timezone_formats = array( 'P', 'I', 'O', 'T', 'Z', 'e' );
  190.     $timezone_formats_re = implode( '|', $timezone_formats );
  191.     if ( preg_match( "/$timezone_formats_re/", $dateformatstring ) ) {
  192.         $timezone_string = get_option( 'timezone_string' );
  193.         if ( $timezone_string ) {
  194.             $timezone_object = timezone_open( $timezone_string );
  195.             $date_object = date_create( null, $timezone_object );
  196.             foreach( $timezone_formats as $timezone_format ) {
  197.                 if ( false !== strpos( $dateformatstring, $timezone_format ) ) {
  198.                     $formatted = date_format( $date_object, $timezone_format );
  199.                     $dateformatstring = ' '.$dateformatstring;
  200.                     $dateformatstring = preg_replace( "/([^\\\])$timezone_format/", "\\1" . backslashit( $formatted ), $dateformatstring );
  201.                     $dateformatstring = substr( $dateformatstring, 1, strlen( $dateformatstring ) -1 );
  202.                 }
  203.             }
  204.         }
  205.     }
  206.     $j = @$datefunc( $dateformatstring, $i );
  207.  
  208.     /**
  209.      * Filter the date formatted based on the locale.
  210.      *
  211.      * @since 2.8.0
  212.      *
  213.      * @param string $j          Formatted date string.
  214.      * @param string $req_format Format to display the date.
  215.      * @param int    $i          Unix timestamp.
  216.      * @param bool   $gmt        Whether to convert to GMT for time. Default false.
  217.      */
  218.     $j = apply_filters( 'date_i18n', $j, $req_format, $i, $gmt );
  219.     return $j;
  220. }
  221.  
  222. /**
  223.  * Convert integer number to format based on the locale.
  224.  *
  225.  * @since 2.3.0
  226.  *
  227.  * @param int $number   The number to convert based on locale.
  228.  * @param int $decimals Optional. Precision of the number of decimal places. Default 0.
  229.  * @return string Converted number in string format.
  230.  */
  231. function number_format_i18n( $number, $decimals = 0 ) {
  232.     global $wp_locale;
  233.     $formatted = number_format( $number, absint( $decimals ), $wp_locale->number_format['decimal_point'], $wp_locale->number_format['thousands_sep'] );
  234.  
  235.     /**
  236.      * Filter the number formatted based on the locale.
  237.      *
  238.      * @since  2.8.0
  239.      *
  240.      * @param string $formatted Converted number in string format.
  241.      */
  242.     return apply_filters( 'number_format_i18n', $formatted );
  243. }
  244.  
  245. /**
  246.  * Convert number of bytes largest unit bytes will fit into.
  247.  *
  248.  * It is easier to read 1kB than 1024 bytes and 1MB than 1048576 bytes. Converts
  249.  * number of bytes to human readable number by taking the number of that unit
  250.  * that the bytes will go into it. Supports TB value.
  251.  *
  252.  * Please note that integers in PHP are limited to 32 bits, unless they are on
  253.  * 64 bit architecture, then they have 64 bit size. If you need to place the
  254.  * larger size then what PHP integer type will hold, then use a string. It will
  255.  * be converted to a double, which should always have 64 bit length.
  256.  *
  257.  * Technically the correct unit names for powers of 1024 are KiB, MiB etc.
  258.  *
  259.  * @since 2.3.0
  260.  *
  261.  * @param int|string $bytes    Number of bytes. Note max integer size for integers.
  262.  * @param int        $decimals Optional. Precision of number of decimal places. Default 0.
  263.  * @return bool|string False on failure. Number string on success.
  264.  */
  265. function size_format( $bytes, $decimals = 0 ) {
  266.     $quant = array(
  267.         // ========================= Origin ====
  268.         'TB' => 1099511627776,  // pow( 1024, 4)
  269.         'GB' => 1073741824,     // pow( 1024, 3)
  270.         'MB' => 1048576,        // pow( 1024, 2)
  271.         'kB' => 1024,           // pow( 1024, 1)
  272.         'B ' => 1,              // pow( 1024, 0)
  273.     );
  274.     foreach ( $quant as $unit => $mag )
  275.         if ( doubleval($bytes) >= $mag )
  276.             return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit;
  277.  
  278.     return false;
  279. }
  280.  
  281. /**
  282.  * Get the week start and end from the datetime or date string from MySQL.
  283.  *
  284.  * @since 0.71
  285.  *
  286.  * @param string     $mysqlstring   Date or datetime field type from MySQL.
  287.  * @param int|string $start_of_week Optional. Start of the week as an integer. Default empty string.
  288.  * @return array Keys are 'start' and 'end'.
  289.  */
  290. function get_weekstartend( $mysqlstring, $start_of_week = '' ) {
  291.     // MySQL string year.
  292.     $my = substr( $mysqlstring, 0, 4 );
  293.  
  294.     // MySQL string month.
  295.     $mm = substr( $mysqlstring, 8, 2 );
  296.  
  297.     // MySQL string day.
  298.     $md = substr( $mysqlstring, 5, 2 );
  299.  
  300.     // The timestamp for MySQL string day.
  301.     $day = mktime( 0, 0, 0, $md, $mm, $my );
  302.  
  303.     // The day of the week from the timestamp.
  304.     $weekday = date( 'w', $day );
  305.  
  306.     if ( !is_numeric($start_of_week) )
  307.         $start_of_week = get_option( 'start_of_week' );
  308.  
  309.     if ( $weekday < $start_of_week )
  310.         $weekday += 7;
  311.  
  312.     // The most recent week start day on or before $day.
  313.     $start = $day - DAY_IN_SECONDS * ( $weekday - $start_of_week );
  314.  
  315.     // $start + 7 days - 1 second.
  316.     $end = $start + 7 * DAY_IN_SECONDS - 1;
  317.     return compact( 'start', 'end' );
  318. }
  319.  
  320. /**
  321.  * Unserialize value only if it was serialized.
  322.  *
  323.  * @since 2.0.0
  324.  *
  325.  * @param string $original Maybe unserialized original, if is needed.
  326.  * @return mixed Unserialized data can be any type.
  327.  */
  328. function maybe_unserialize( $original ) {
  329.     if ( is_serialized( $original ) ) // don't attempt to unserialize data that wasn't serialized going in
  330.         return @unserialize( $original );
  331.     return $original;
  332. }
  333.  
  334. /**
  335.  * Check value to find if it was serialized.
  336.  *
  337.  * If $data is not an string, then returned value will always be false.
  338.  * Serialized data is always a string.
  339.  *
  340.  * @since 2.0.5
  341.  *
  342.  * @param string $data   Value to check to see if was serialized.
  343.  * @param bool   $strict Optional. Whether to be strict about the end of the string. Default true.
  344.  * @return bool False if not serialized and true if it was.
  345.  */
  346. function is_serialized( $data, $strict = true ) {
  347.     // if it isn't a string, it isn't serialized.
  348.     if ( ! is_string( $data ) ) {
  349.         return false;
  350.     }
  351.     $data = trim( $data );
  352.     if ( 'N;' == $data ) {
  353.         return true;
  354.     }
  355.     if ( strlen( $data ) < 4 ) {
  356.         return false;
  357.     }
  358.     if ( ':' !== $data[1] ) {
  359.         return false;
  360.     }
  361.     if ( $strict ) {
  362.         $lastc = substr( $data, -1 );
  363.         if ( ';' !== $lastc && '}' !== $lastc ) {
  364.             return false;
  365.         }
  366.     } else {
  367.         $semicolon = strpos( $data, ';' );
  368.         $brace     = strpos( $data, '}' );
  369.         // Either ; or } must exist.
  370.         if ( false === $semicolon && false === $brace )
  371.             return false;
  372.         // But neither must be in the first X characters.
  373.         if ( false !== $semicolon && $semicolon < 3 )
  374.             return false;
  375.         if ( false !== $brace && $brace < 4 )
  376.             return false;
  377.     }
  378.     $token = $data[0];
  379.     switch ( $token ) {
  380.         case 's' :
  381.             if ( $strict ) {
  382.                 if ( '"' !== substr( $data, -2, 1 ) ) {
  383.                     return false;
  384.                 }
  385.             } elseif ( false === strpos( $data, '"' ) ) {
  386.                 return false;
  387.             }
  388.             // or else fall through
  389.         case 'a' :
  390.         case 'O' :
  391.             return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
  392.         case 'b' :
  393.         case 'i' :
  394.         case 'd' :
  395.             $end = $strict ? '$' : '';
  396.             return (bool) preg_match( "/^{$token}:[0-9.E-]+;$end/", $data );
  397.     }
  398.     return false;
  399. }
  400.  
  401. /**
  402.  * Check whether serialized data is of string type.
  403.  *
  404.  * @since 2.0.5
  405.  *
  406.  * @param string $data Serialized data.
  407.  * @return bool False if not a serialized string, true if it is.
  408.  */
  409. function is_serialized_string( $data ) {
  410.     // if it isn't a string, it isn't a serialized string.
  411.     if ( ! is_string( $data ) ) {
  412.         return false;
  413.     }
  414.     $data = trim( $data );
  415.     if ( strlen( $data ) < 4 ) {
  416.         return false;
  417.     } elseif ( ':' !== $data[1] ) {
  418.         return false;
  419.     } elseif ( ';' !== substr( $data, -1 ) ) {
  420.         return false;
  421.     } elseif ( $data[0] !== 's' ) {
  422.         return false;
  423.     } elseif ( '"' !== substr( $data, -2, 1 ) ) {
  424.         return false;
  425.     } else {
  426.         return true;
  427.     }
  428. }
  429.  
  430. /**
  431.  * Serialize data, if needed.
  432.  *
  433.  * @since 2.0.5
  434.  *
  435.  * @param string|array|object $data Data that might be serialized.
  436.  * @return mixed A scalar data
  437.  */
  438. function maybe_serialize( $data ) {
  439.     if ( is_array( $data ) || is_object( $data ) )
  440.         return serialize( $data );
  441.  
  442.     // Double serialization is required for backward compatibility.
  443.     // See http://core.trac.wordpress.org/ticket/12930
  444.     if ( is_serialized( $data, false ) )
  445.         return serialize( $data );
  446.  
  447.     return $data;
  448. }
  449.  
  450. /**
  451.  * Retrieve post title from XMLRPC XML.
  452.  *
  453.  * If the title element is not part of the XML, then the default post title from
  454.  * the $post_default_title will be used instead.
  455.  *
  456.  * @since 0.71
  457.  *
  458.  * @global string $post_default_title Default XML-RPC post title.
  459.  *
  460.  * @param string $content XMLRPC XML Request content
  461.  * @return string Post title
  462.  */
  463. function xmlrpc_getposttitle( $content ) {
  464.     global $post_default_title;
  465.     if ( preg_match( '/<title>(.+?)<\/title>/is', $content, $matchtitle ) ) {
  466.         $post_title = $matchtitle[1];
  467.     } else {
  468.         $post_title = $post_default_title;
  469.     }
  470.     return $post_title;
  471. }
  472.  
  473. /**
  474.  * Retrieve the post category or categories from XMLRPC XML.
  475.  *
  476.  * If the category element is not found, then the default post category will be
  477.  * used. The return type then would be what $post_default_category. If the
  478.  * category is found, then it will always be an array.
  479.  *
  480.  * @since 0.71
  481.  *
  482.  * @global string $post_default_category Default XML-RPC post category.
  483.  *
  484.  * @param string $content XMLRPC XML Request content
  485.  * @return string|array List of categories or category name.
  486.  */
  487. function xmlrpc_getpostcategory( $content ) {
  488.     global $post_default_category;
  489.     if ( preg_match( '/<category>(.+?)<\/category>/is', $content, $matchcat ) ) {
  490.         $post_category = trim( $matchcat[1], ',' );
  491.         $post_category = explode( ',', $post_category );
  492.     } else {
  493.         $post_category = $post_default_category;
  494.     }
  495.     return $post_category;
  496. }
  497.  
  498. /**
  499.  * XMLRPC XML content without title and category elements.
  500.  *
  501.  * @since 0.71
  502.  *
  503.  * @param string $content XML-RPC XML Request content.
  504.  * @return string XMLRPC XML Request content without title and category elements.
  505.  */
  506. function xmlrpc_removepostdata( $content ) {
  507.     $content = preg_replace( '/<title>(.+?)<\/title>/si', '', $content );
  508.     $content = preg_replace( '/<category>(.+?)<\/category>/si', '', $content );
  509.     $content = trim( $content );
  510.     return $content;
  511. }
  512.  
  513. /**
  514.  * Use RegEx to extract URLs from arbitrary content.
  515.  *
  516.  * @since 3.7.0
  517.  *
  518.  * @param string $content Content to extract URLs from.
  519.  * @return array URLs found in passed string.
  520.  */
  521. function wp_extract_urls( $content ) {
  522.     preg_match_all(
  523.         "#("
  524.             . "(?:([\w-]+:)?//?)"
  525.             . "[^\s()<>]+"
  526.             . "[.]"
  527.             . "(?:"
  528.                 . "\([\w\d]+\)|"
  529.                 . "(?:"
  530.                     . "[^`!()\[\]{};:'\".,<>?«»“”‘’\s]|"
  531.                     . "(?:[:]\d+)?/?"
  532.                 . ")+"
  533.             . ")"
  534.         . ")#",
  535.         $content,
  536.         $post_links
  537.     );
  538.  
  539.     $post_links = array_unique( array_map( 'html_entity_decode', $post_links[0] ) );
  540.  
  541.     return array_values( $post_links );
  542. }
  543.  
  544. /**
  545.  * Check content for video and audio links to add as enclosures.
  546.  *
  547.  * Will not add enclosures that have already been added and will
  548.  * remove enclosures that are no longer in the post. This is called as
  549.  * pingbacks and trackbacks.
  550.  *
  551.  * @since 1.5.0
  552.  *
  553.  * @see $wpdb
  554.  *
  555.  * @param string $content Post Content.
  556.  * @param int $post_ID Post ID.
  557.  */
  558. function do_enclose( $content, $post_ID ) {
  559.     global $wpdb;
  560.  
  561.     //TODO: Tidy this ghetto code up and make the debug code optional
  562.     include_once( ABSPATH . WPINC . '/class-IXR.php' );
  563.  
  564.     $post_links = array();
  565.  
  566.     $pung = get_enclosed( $post_ID );
  567.  
  568.     $post_links_temp = wp_extract_urls( $content );
  569.  
  570.     foreach ( $pung as $link_test ) {
  571.         if ( ! in_array( $link_test, $post_links_temp ) ) { // link no longer in post
  572.             $mids = $wpdb->get_col( $wpdb->prepare("SELECT meta_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE %s", $post_ID, $wpdb->esc_like( $link_test ) . '%') );
  573.             foreach ( $mids as $mid )
  574.                 delete_metadata_by_mid( 'post', $mid );
  575.         }
  576.     }
  577.  
  578.     foreach ( (array) $post_links_temp as $link_test ) {
  579.         if ( !in_array( $link_test, $pung ) ) { // If we haven't pung it already
  580.             $test = @parse_url( $link_test );
  581.             if ( false === $test )
  582.                 continue;
  583.             if ( isset( $test['query'] ) )
  584.                 $post_links[] = $link_test;
  585.             elseif ( isset($test['path']) && ( $test['path'] != '/' ) &&  ($test['path'] != '' ) )
  586.                 $post_links[] = $link_test;
  587.         }
  588.     }
  589.  
  590.     foreach ( (array) $post_links as $url ) {
  591.         if ( $url != '' && !$wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE post_id = %d AND meta_key = 'enclosure' AND meta_value LIKE %s", $post_ID, $wpdb->esc_like( $url ) . '%' ) ) ) {
  592.  
  593.             if ( $headers = wp_get_http_headers( $url) ) {
  594.                 $len = isset( $headers['content-length'] ) ? (int) $headers['content-length'] : 0;
  595.                 $type = isset( $headers['content-type'] ) ? $headers['content-type'] : '';
  596.                 $allowed_types = array( 'video', 'audio' );
  597.  
  598.                 // Check to see if we can figure out the mime type from
  599.                 // the extension
  600.                 $url_parts = @parse_url( $url );
  601.                 if ( false !== $url_parts ) {
  602.                     $extension = pathinfo( $url_parts['path'], PATHINFO_EXTENSION );
  603.                     if ( !empty( $extension ) ) {
  604.                         foreach ( wp_get_mime_types() as $exts => $mime ) {
  605.                             if ( preg_match( '!^(' . $exts . ')$!i', $extension ) ) {
  606.                                 $type = $mime;
  607.                                 break;
  608.                             }
  609.                         }
  610.                     }
  611.                 }
  612.  
  613.                 if ( in_array( substr( $type, 0, strpos( $type, "/" ) ), $allowed_types ) ) {
  614.                     add_post_meta( $post_ID, 'enclosure', "$url\n$len\n$mime\n" );
  615.                 }
  616.             }
  617.         }
  618.     }
  619. }
  620.  
  621. /**
  622.  * Perform a HTTP HEAD or GET request.
  623.  *
  624.  * If $file_path is a writable filename, this will do a GET request and write
  625.  * the file to that path.
  626.  *
  627.  * @since 2.5.0
  628.  *
  629.  * @param string      $url       URL to fetch.
  630.  * @param string|bool $file_path Optional. File path to write request to. Default false.
  631.  * @param int         $red       Optional. The number of Redirects followed, Upon 5 being hit,
  632.  *                               returns false. Default 1.
  633.  * @return bool|string False on failure and string of headers if HEAD request.
  634.  */
  635. function wp_get_http( $url, $file_path = false, $red = 1 ) {
  636.     @set_time_limit( 60 );
  637.  
  638.     if ( $red > 5 )
  639.         return false;
  640.  
  641.     $options = array();
  642.     $options['redirection'] = 5;
  643.  
  644.     if ( false == $file_path )
  645.         $options['method'] = 'HEAD';
  646.     else
  647.         $options['method'] = 'GET';
  648.  
  649.     $response = wp_safe_remote_request( $url, $options );
  650.  
  651.     if ( is_wp_error( $response ) )
  652.         return false;
  653.  
  654.     $headers = wp_remote_retrieve_headers( $response );
  655.     $headers['response'] = wp_remote_retrieve_response_code( $response );
  656.  
  657.     // WP_HTTP no longer follows redirects for HEAD requests.
  658.     if ( 'HEAD' == $options['method'] && in_array($headers['response'], array(301, 302)) && isset( $headers['location'] ) ) {
  659.         return wp_get_http( $headers['location'], $file_path, ++$red );
  660.     }
  661.  
  662.     if ( false == $file_path )
  663.         return $headers;
  664.  
  665.     // GET request - write it to the supplied filename
  666.     $out_fp = fopen($file_path, 'w');
  667.     if ( !$out_fp )
  668.         return $headers;
  669.  
  670.     fwrite( $out_fp,  wp_remote_retrieve_body( $response ) );
  671.     fclose($out_fp);
  672.     clearstatcache();
  673.  
  674.     return $headers;
  675. }
  676.  
  677. /**
  678.  * Retrieve HTTP Headers from URL.
  679.  *
  680.  * @since 1.5.1
  681.  *
  682.  * @param string $url        URL to retrieve HTTP headers from.
  683.  * @param bool   $deprecated Not Used.
  684.  * @return bool|string False on failure, headers on success.
  685.  */
  686. function wp_get_http_headers( $url, $deprecated = false ) {
  687.     if ( !empty( $deprecated ) )
  688.         _deprecated_argument( __FUNCTION__, '2.7' );
  689.  
  690.     $response = wp_safe_remote_head( $url );
  691.  
  692.     if ( is_wp_error( $response ) )
  693.         return false;
  694.  
  695.     return wp_remote_retrieve_headers( $response );
  696. }
  697.  
  698. /**
  699.  * Whether the publish date of the current post in the loop is different from the
  700.  * publish date of the previous post in the loop.
  701.  *
  702.  * @since 0.71
  703.  *
  704.  * @global string $currentday  The day of the current post in the loop.
  705.  * @global string $previousday The day of the previous post in the loop.
  706.  *
  707.  * @return int|bool 1|true when new day, 0|false if not a new day.
  708.  */
  709. function is_new_day() {
  710.     global $currentday, $previousday;
  711.     if ( $currentday != $previousday )
  712.         return 1;
  713.     else
  714.         return 0;
  715. }
  716.  
  717. /**
  718.  * Build URL query based on an associative and, or indexed array.
  719.  *
  720.  * This is a convenient function for easily building url queries. It sets the
  721.  * separator to '&' and uses _http_build_query() function.
  722.  *
  723.  * @since 2.3.0
  724.  *
  725.  * @see _http_build_query() Used to build the query
  726.  * @see http://us2.php.net/manual/en/function.http-build-query.php for more on what
  727.  *      http_build_query() does.
  728.  *
  729.  * @param array $data URL-encode key/value pairs.
  730.  * @return string URL-encoded string.
  731.  */
  732. function build_query( $data ) {
  733.     return _http_build_query( $data, null, '&', '', false );
  734. }
  735.  
  736. /**
  737.  * From php.net (modified by Mark Jaquith to behave like the native PHP5 function).
  738.  *
  739.  * @since 3.2.0
  740.  * @access private
  741.  *
  742.  * @see http://us1.php.net/manual/en/function.http-build-query.php
  743.  *
  744.  * @param array|object  $data       An array or object of data. Converted to array.
  745.  * @param string        $prefix     Optional. Numeric index. If set, start parameter numbering with it.
  746.  *                                  Default null.
  747.  * @param string        $sep        Optional. Argument separator; defaults to 'arg_separator.output'.
  748.  *                                  Default null.
  749.  * @param string        $key        Optional. Used to prefix key name. Default empty.
  750.  * @param bool          $urlencode  Optional. Whether to use urlencode() in the result. Default true.
  751.  *
  752.  * @return string The query string.
  753.  */
  754. function _http_build_query( $data, $prefix = null, $sep = null, $key = '', $urlencode = true ) {
  755.     $ret = array();
  756.  
  757.     foreach ( (array) $data as $k => $v ) {
  758.         if ( $urlencode)
  759.             $k = urlencode($k);
  760.         if ( is_int($k) && $prefix != null )
  761.             $k = $prefix.$k;
  762.         if ( !empty($key) )
  763.             $k = $key . '%5B' . $k . '%5D';
  764.         if ( $v === null )
  765.             continue;
  766.         elseif ( $v === FALSE )
  767.             $v = '0';
  768.  
  769.         if ( is_array($v) || is_object($v) )
  770.             array_push($ret,_http_build_query($v, '', $sep, $k, $urlencode));
  771.         elseif ( $urlencode )
  772.             array_push($ret, $k.'='.urlencode($v));
  773.         else
  774.             array_push($ret, $k.'='.$v);
  775.     }
  776.  
  777.     if ( null === $sep )
  778.         $sep = ini_get('arg_separator.output');
  779.  
  780.     return implode($sep, $ret);
  781. }
  782.  
  783. /**
  784.  * Retrieve a modified URL query string.
  785.  *
  786.  * You can rebuild the URL and append a new query variable to the URL query by
  787.  * using this function. You can also retrieve the full URL with query data.
  788.  *
  789.  * Adding a single key & value or an associative array. Setting a key value to
  790.  * an empty string removes the key. Omitting oldquery_or_uri uses the $_SERVER
  791.  * value. Additional values provided are expected to be encoded appropriately
  792.  * with urlencode() or rawurlencode().
  793.  *
  794.  * @since 1.5.0
  795.  *
  796.  * @param string|array $param1 Either newkey or an associative_array.
  797.  * @param string       $param2 Either newvalue or oldquery or URI.
  798.  * @param string       $param3 Optional. Old query or URI.
  799.  * @return string New URL query string.
  800.  */
  801. function add_query_arg() {
  802.     $args = func_get_args();
  803.     if ( is_array( $args[0] ) ) {
  804.         if ( count( $args ) < 2 || false === $args[1] )
  805.             $uri = $_SERVER['REQUEST_URI'];
  806.         else
  807.             $uri = $args[1];
  808.     } else {
  809.         if ( count( $args ) < 3 || false === $args[2] )
  810.             $uri = $_SERVER['REQUEST_URI'];
  811.         else
  812.             $uri = $args[2];
  813.     }
  814.  
  815.     if ( $frag = strstr( $uri, '#' ) )
  816.         $uri = substr( $uri, 0, -strlen( $frag ) );
  817.     else
  818.         $frag = '';
  819.  
  820.     if ( 0 === stripos( $uri, 'http://' ) ) {
  821.         $protocol = 'http://';
  822.         $uri = substr( $uri, 7 );
  823.     } elseif ( 0 === stripos( $uri, 'https://' ) ) {
  824.         $protocol = 'https://';
  825.         $uri = substr( $uri, 8 );
  826.     } else {
  827.         $protocol = '';
  828.     }
  829.  
  830.     if ( strpos( $uri, '?' ) !== false ) {
  831.         list( $base, $query ) = explode( '?', $uri, 2 );
  832.         $base .= '?';
  833.     } elseif ( $protocol || strpos( $uri, '=' ) === false ) {
  834.         $base = $uri . '?';
  835.         $query = '';
  836.     } else {
  837.         $base = '';
  838.         $query = $uri;
  839.     }
  840.  
  841.     wp_parse_str( $query, $qs );
  842.     $qs = urlencode_deep( $qs ); // this re-URL-encodes things that were already in the query string
  843.     if ( is_array( $args[0] ) ) {
  844.         $kayvees = $args[0];
  845.         $qs = array_merge( $qs, $kayvees );
  846.     } else {
  847.         $qs[ $args[0] ] = $args[1];
  848.     }
  849.  
  850.     foreach ( $qs as $k => $v ) {
  851.         if ( $v === false )
  852.             unset( $qs[$k] );
  853.     }
  854.  
  855.     $ret = build_query( $qs );
  856.     $ret = trim( $ret, '?' );
  857.     $ret = preg_replace( '#=(&|$)#', '$1', $ret );
  858.     $ret = $protocol . $base . $ret . $frag;
  859.     $ret = rtrim( $ret, '?' );
  860.     return $ret;
  861. }
  862.  
  863. /**
  864.  * Removes an item or list from the query string.
  865.  *
  866.  * @since 1.5.0
  867.  *
  868.  * @param string|array $key   Query key or keys to remove.
  869.  * @param bool         $query Optional. When false uses the $_SERVER value. Default false.
  870.  * @return string New URL query string.
  871.  */
  872. function remove_query_arg( $key, $query = false ) {
  873.     if ( is_array( $key ) ) { // removing multiple keys
  874.         foreach ( $key as $k )
  875.             $query = add_query_arg( $k, false, $query );
  876.         return $query;
  877.     }
  878.     return add_query_arg( $key, false, $query );
  879. }
  880.  
  881. /**
  882.  * Walks the array while sanitizing the contents.
  883.  *
  884.  * @since 0.71
  885.  *
  886.  * @param array $array Array to walk while sanitizing contents.
  887.  * @return array Sanitized $array.
  888.  */
  889. function add_magic_quotes( $array ) {
  890.     foreach ( (array) $array as $k => $v ) {
  891.         if ( is_array( $v ) ) {
  892.             $array[$k] = add_magic_quotes( $v );
  893.         } else {
  894.             $array[$k] = addslashes( $v );
  895.         }
  896.     }
  897.     return $array;
  898. }
  899.  
  900. /**
  901.  * HTTP request for URI to retrieve content.
  902.  *
  903.  * @since 1.5.1
  904.  *
  905.  * @see wp_safe_remote_get()
  906.  *
  907.  * @param string $uri URI/URL of web page to retrieve.
  908.  * @return bool|string HTTP content. False on failure.
  909.  */
  910. function wp_remote_fopen( $uri ) {
  911.     $parsed_url = @parse_url( $uri );
  912.  
  913.     if ( !$parsed_url || !is_array( $parsed_url ) )
  914.         return false;
  915.  
  916.     $options = array();
  917.     $options['timeout'] = 10;
  918.  
  919.     $response = wp_safe_remote_get( $uri, $options );
  920.  
  921.     if ( is_wp_error( $response ) )
  922.         return false;
  923.  
  924.     return wp_remote_retrieve_body( $response );
  925. }
  926.  
  927. /**
  928.  * Set up the WordPress query.
  929.  *
  930.  * @since 2.0.0
  931.  *
  932.  * @param string $query_vars Default WP_Query arguments.
  933.  */
  934. function wp( $query_vars = '' ) {
  935.     global $wp, $wp_query, $wp_the_query;
  936.     $wp->main( $query_vars );
  937.  
  938.     if ( !isset($wp_the_query) )
  939.         $wp_the_query = $wp_query;
  940. }
  941.  
  942. /**
  943.  * Retrieve the description for the HTTP status.
  944.  *
  945.  * @since 2.3.0
  946.  *
  947.  * @param int $code HTTP status code.
  948.  * @return string Empty string if not found, or description if found.
  949.  */
  950. function get_status_header_desc( $code ) {
  951.     global $wp_header_to_desc;
  952.  
  953.     $code = absint( $code );
  954.  
  955.     if ( !isset( $wp_header_to_desc ) ) {
  956.         $wp_header_to_desc = array(
  957.             100 => 'Continue',
  958.             101 => 'Switching Protocols',
  959.             102 => 'Processing',
  960.  
  961.             200 => 'OK',
  962.             201 => 'Created',
  963.             202 => 'Accepted',
  964.             203 => 'Non-Authoritative Information',
  965.             204 => 'No Content',
  966.             205 => 'Reset Content',
  967.             206 => 'Partial Content',
  968.             207 => 'Multi-Status',
  969.             226 => 'IM Used',
  970.  
  971.             300 => 'Multiple Choices',
  972.             301 => 'Moved Permanently',
  973.             302 => 'Found',
  974.             303 => 'See Other',
  975.             304 => 'Not Modified',
  976.             305 => 'Use Proxy',
  977.             306 => 'Reserved',
  978.             307 => 'Temporary Redirect',
  979.  
  980.             400 => 'Bad Request',
  981.             401 => 'Unauthorized',
  982.             402 => 'Payment Required',
  983.             403 => 'Forbidden',
  984.             404 => 'Not Found',
  985.             405 => 'Method Not Allowed',
  986.             406 => 'Not Acceptable',
  987.             407 => 'Proxy Authentication Required',
  988.             408 => 'Request Timeout',
  989.             409 => 'Conflict',
  990.             410 => 'Gone',
  991.             411 => 'Length Required',
  992.             412 => 'Precondition Failed',
  993.             413 => 'Request Entity Too Large',
  994.             414 => 'Request-URI Too Long',
  995.             415 => 'Unsupported Media Type',
  996.             416 => 'Requested Range Not Satisfiable',
  997.             417 => 'Expectation Failed',
  998.             418 => 'I\'m a teapot',
  999.             422 => 'Unprocessable Entity',
  1000.             423 => 'Locked',
  1001.             424 => 'Failed Dependency',
  1002.             426 => 'Upgrade Required',
  1003.             428 => 'Precondition Required',
  1004.             429 => 'Too Many Requests',
  1005.             431 => 'Request Header Fields Too Large',
  1006.  
  1007.             500 => 'Internal Server Error',
  1008.             501 => 'Not Implemented',
  1009.             502 => 'Bad Gateway',
  1010.             503 => 'Service Unavailable',
  1011.             504 => 'Gateway Timeout',
  1012.             505 => 'HTTP Version Not Supported',
  1013.             506 => 'Variant Also Negotiates',
  1014.             507 => 'Insufficient Storage',
  1015.             510 => 'Not Extended',
  1016.             511 => 'Network Authentication Required',
  1017.         );
  1018.     }
  1019.  
  1020.     if ( isset( $wp_header_to_desc[$code] ) )
  1021.         return $wp_header_to_desc[$code];
  1022.     else
  1023.         return '';
  1024. }
  1025.  
  1026. /**
  1027.  * Set HTTP status header.
  1028.  *
  1029.  * @since 2.0.0
  1030.  *
  1031.  * @see get_status_header_desc()
  1032.  *
  1033.  * @param int $code HTTP status code.
  1034.  */
  1035. function status_header( $code ) {
  1036.     $description = get_status_header_desc( $code );
  1037.  
  1038.     if ( empty( $description ) )
  1039.         return;
  1040.  
  1041.     $protocol = $_SERVER['SERVER_PROTOCOL'];
  1042.     if ( 'HTTP/1.1' != $protocol && 'HTTP/1.0' != $protocol )
  1043.         $protocol = 'HTTP/1.0';
  1044.     $status_header = "$protocol $code $description";
  1045.     if ( function_exists( 'apply_filters' ) )
  1046.  
  1047.         /**
  1048.          * Filter an HTTP status header.
  1049.          *
  1050.          * @since 2.2.0
  1051.          *
  1052.          * @param string $status_header HTTP status header.
  1053.          * @param int    $code          HTTP status code.
  1054.          * @param string $description   Description for the status code.
  1055.          * @param string $protocol      Server protocol.
  1056.          */
  1057.         $status_header = apply_filters( 'status_header', $status_header, $code, $description, $protocol );
  1058.  
  1059.     @header( $status_header, true, $code );
  1060. }
  1061.  
  1062. /**
  1063.  * Get the header information to prevent caching.
  1064.  *
  1065.  * The several different headers cover the different ways cache prevention
  1066.  * is handled by different browsers
  1067.  *
  1068.  * @since 2.8.0
  1069.  *
  1070.  * @return array The associative array of header names and field values.
  1071.  */
  1072. function wp_get_nocache_headers() {
  1073.     $headers = array(
  1074.         'Expires' => 'Wed, 11 Jan 1984 05:00:00 GMT',
  1075.         'Cache-Control' => 'no-cache, must-revalidate, max-age=0',
  1076.         'Pragma' => 'no-cache',
  1077.     );
  1078.  
  1079.     if ( function_exists('apply_filters') ) {
  1080.         /**
  1081.          * Filter the cache-controlling headers.
  1082.          *
  1083.          * @since 2.8.0
  1084.          *
  1085.          * @see wp_get_nocache_headers()
  1086.          *
  1087.          * @param array $headers {
  1088.          *     Header names and field values.
  1089.          *
  1090.          *     @type string $Expires       Expires header.
  1091.          *     @type string $Cache-Control Cache-Control header.
  1092.          *     @type string $Pragma        Pragma header.
  1093.          * }
  1094.          */
  1095.         $headers = (array) apply_filters( 'nocache_headers', $headers );
  1096.     }
  1097.     $headers['Last-Modified'] = false;
  1098.     return $headers;
  1099. }
  1100.  
  1101. /**
  1102.  * Set the headers to prevent caching for the different browsers.
  1103.  *
  1104.  * Different browsers support different nocache headers, so several
  1105.  * headers must be sent so that all of them get the point that no
  1106.  * caching should occur.
  1107.  *
  1108.  * @since 2.0.0
  1109.  *
  1110.  * @see wp_get_nocache_headers()
  1111.  */
  1112. function nocache_headers() {
  1113.     $headers = wp_get_nocache_headers();
  1114.  
  1115.     unset( $headers['Last-Modified'] );
  1116.  
  1117.     // In PHP 5.3+, make sure we are not sending a Last-Modified header.
  1118.     if ( function_exists( 'header_remove' ) ) {
  1119.         @header_remove( 'Last-Modified' );
  1120.     } else {
  1121.         // In PHP 5.2, send an empty Last-Modified header, but only as a
  1122.         // last resort to override a header already sent. #WP23021
  1123.         foreach ( headers_list() as $header ) {
  1124.             if ( 0 === stripos( $header, 'Last-Modified' ) ) {
  1125.                 $headers['Last-Modified'] = '';
  1126.                 break;
  1127.             }
  1128.         }
  1129.     }
  1130.  
  1131.     foreach( $headers as $name => $field_value )
  1132.         @header("{$name}: {$field_value}");
  1133. }
  1134.  
  1135. /**
  1136.  * Set the headers for caching for 10 days with JavaScript content type.
  1137.  *
  1138.  * @since 2.1.0
  1139.  */
  1140. function cache_javascript_headers() {
  1141.     $expiresOffset = 10 * DAY_IN_SECONDS;
  1142.  
  1143.     header( "Content-Type: text/javascript; charset=" . get_bloginfo( 'charset' ) );
  1144.     header( "Vary: Accept-Encoding" ); // Handle proxies
  1145.     header( "Expires: " . gmdate( "D, d M Y H:i:s", time() + $expiresOffset ) . " GMT" );
  1146. }
  1147.  
  1148. /**
  1149.  * Retrieve the number of database queries during the WordPress execution.
  1150.  *
  1151.  * @since 2.0.0
  1152.  *
  1153.  * @global wpdb $wpdb WordPress database access abstraction object.
  1154.  *
  1155.  * @return int Number of database queries.
  1156.  */
  1157. function get_num_queries() {
  1158.     global $wpdb;
  1159.     return $wpdb->num_queries;
  1160. }
  1161.  
  1162. /**
  1163.  * Whether input is yes or no.
  1164.  *
  1165.  * Must be 'y' to be true.
  1166.  *
  1167.  * @since 1.0.0
  1168.  *
  1169.  * @param string $yn Character string containing either 'y' (yes) or 'n' (no).
  1170.  * @return bool True if yes, false on anything else.
  1171.  */
  1172. function bool_from_yn( $yn ) {
  1173.     return ( strtolower( $yn ) == 'y' );
  1174. }
  1175.  
  1176. /**
  1177.  * Load the feed template from the use of an action hook.
  1178.  *
  1179.  * If the feed action does not have a hook, then the function will die with a
  1180.  * message telling the visitor that the feed is not valid.
  1181.  *
  1182.  * It is better to only have one hook for each feed.
  1183.  *
  1184.  * @since 2.1.0
  1185.  *
  1186.  * @uses $wp_query Used to tell if the use a comment feed.
  1187.  */
  1188. function do_feed() {
  1189.     global $wp_query;
  1190.  
  1191.     $feed = get_query_var( 'feed' );
  1192.  
  1193.     // Remove the pad, if present.
  1194.     $feed = preg_replace( '/^_+/', '', $feed );
  1195.  
  1196.     if ( $feed == '' || $feed == 'feed' )
  1197.         $feed = get_default_feed();
  1198.  
  1199.     $hook = 'do_feed_' . $feed;
  1200.     if ( ! has_action( $hook ) )
  1201.         wp_die( __( 'ERROR: This is not a valid feed template.' ), '', array( 'response' => 404 ) );
  1202.  
  1203.     /**
  1204.      * Fires once the given feed is loaded.
  1205.      *
  1206.      * The dynamic hook name, $hook, refers to the feed name.
  1207.      *
  1208.      * @since 2.1.0
  1209.      *
  1210.      * @param bool $is_comment_feed Whether the feed is a comment feed.
  1211.      */
  1212.     do_action( $hook, $wp_query->is_comment_feed );
  1213. }
  1214.  
  1215. /**
  1216.  * Load the RDF RSS 0.91 Feed template.
  1217.  *
  1218.  * @since 2.1.0
  1219.  *
  1220.  * @see load_template()
  1221.  */
  1222. function do_feed_rdf() {
  1223.     load_template( ABSPATH . WPINC . '/feed-rdf.php' );
  1224. }
  1225.  
  1226. /**
  1227.  * Load the RSS 1.0 Feed Template.
  1228.  *
  1229.  * @since 2.1.0
  1230.  *
  1231.  * @see load_template()
  1232.  */
  1233. function do_feed_rss() {
  1234.     load_template( ABSPATH . WPINC . '/feed-rss.php' );
  1235. }
  1236.  
  1237. /**
  1238.  * Load either the RSS2 comment feed or the RSS2 posts feed.
  1239.  *
  1240.  * @since 2.1.0
  1241.  *
  1242.  * @see load_template()
  1243.  *
  1244.  * @param bool $for_comments True for the comment feed, false for normal feed.
  1245.  */
  1246. function do_feed_rss2( $for_comments ) {
  1247.     if ( $for_comments )
  1248.         load_template( ABSPATH . WPINC . '/feed-rss2-comments.php' );
  1249.     else
  1250.         load_template( ABSPATH . WPINC . '/feed-rss2.php' );
  1251. }
  1252.  
  1253. /**
  1254.  * Load either Atom comment feed or Atom posts feed.
  1255.  *
  1256.  * @since 2.1.0
  1257.  *
  1258.  * @see load_template()
  1259.  *
  1260.  * @param bool $for_comments True for the comment feed, false for normal feed.
  1261.  */
  1262. function do_feed_atom( $for_comments ) {
  1263.     if ($for_comments)
  1264.         load_template( ABSPATH . WPINC . '/feed-atom-comments.php');
  1265.     else
  1266.         load_template( ABSPATH . WPINC . '/feed-atom.php' );
  1267. }
  1268.  
  1269. /**
  1270.  * Display the robots.txt file content.
  1271.  *
  1272.  * The echo content should be with usage of the permalinks or for creating the
  1273.  * robots.txt file.
  1274.  *
  1275.  * @since 2.1.0
  1276.  */
  1277. function do_robots() {
  1278.     header( 'Content-Type: text/plain; charset=utf-8' );
  1279.  
  1280.     /**
  1281.      * Fires when displaying the robots.txt file.
  1282.      *
  1283.      * @since 2.1.0
  1284.      */
  1285.     do_action( 'do_robotstxt' );
  1286.  
  1287.     $output = "User-agent: *\n";
  1288.     $public = get_option( 'blog_public' );
  1289.     if ( '0' == $public ) {
  1290.         $output .= "Disallow: /\n";
  1291.     } else {
  1292.         $site_url = parse_url( site_url() );
  1293.         $path = ( !empty( $site_url['path'] ) ) ? $site_url['path'] : '';
  1294.         $output .= "Disallow: $path/wp-admin/\n";
  1295.     }
  1296.  
  1297.     /**
  1298.      * Filter the robots.txt output.
  1299.      *
  1300.      * @since 3.0.0
  1301.      *
  1302.      * @param string $output Robots.txt output.
  1303.      * @param bool   $public Whether the site is considered "public".
  1304.      */
  1305.     echo apply_filters( 'robots_txt', $output, $public );
  1306. }
  1307.  
  1308. /**
  1309.  * Test whether blog is already installed.
  1310.  *
  1311.  * The cache will be checked first. If you have a cache plugin, which saves
  1312.  * the cache values, then this will work. If you use the default WordPress
  1313.  * cache, and the database goes away, then you might have problems.
  1314.  *
  1315.  * Checks for the 'siteurl' option for whether WordPress is installed.
  1316.  *
  1317.  * @since 2.1.0
  1318.  *
  1319.  * @global wpdb $wpdb WordPress database access abstraction object.
  1320.  *
  1321.  * @return bool Whether the blog is already installed.
  1322.  */
  1323. function is_blog_installed() {
  1324.     global $wpdb;
  1325.  
  1326.     /*
  1327.      * Check cache first. If options table goes away and we have true
  1328.      * cached, oh well.
  1329.      */
  1330.     if ( wp_cache_get( 'is_blog_installed' ) )
  1331.         return true;
  1332.  
  1333.     $suppress = $wpdb->suppress_errors();
  1334.     if ( ! defined( 'WP_INSTALLING' ) ) {
  1335.         $alloptions = wp_load_alloptions();
  1336.     }
  1337.     // If siteurl is not set to autoload, check it specifically
  1338.     if ( !isset( $alloptions['siteurl'] ) )
  1339.         $installed = $wpdb->get_var( "SELECT option_value FROM $wpdb->options WHERE option_name = 'siteurl'" );
  1340.     else
  1341.         $installed = $alloptions['siteurl'];
  1342.     $wpdb->suppress_errors( $suppress );
  1343.  
  1344.     $installed = !empty( $installed );
  1345.     wp_cache_set( 'is_blog_installed', $installed );
  1346.  
  1347.     if ( $installed )
  1348.         return true;
  1349.  
  1350.     // If visiting repair.php, return true and let it take over.
  1351.     if ( defined( 'WP_REPAIRING' ) )
  1352.         return true;
  1353.  
  1354.     $suppress = $wpdb->suppress_errors();
  1355.  
  1356.     /*
  1357.      * Loop over the WP tables. If none exist, then scratch install is allowed.
  1358.      * If one or more exist, suggest table repair since we got here because the
  1359.      * options table could not be accessed.
  1360.      */
  1361.     $wp_tables = $wpdb->tables();
  1362.     foreach ( $wp_tables as $table ) {
  1363.         // The existence of custom user tables shouldn't suggest an insane state or prevent a clean install.
  1364.         if ( defined( 'CUSTOM_USER_TABLE' ) && CUSTOM_USER_TABLE == $table )
  1365.             continue;
  1366.         if ( defined( 'CUSTOM_USER_META_TABLE' ) && CUSTOM_USER_META_TABLE == $table )
  1367.             continue;
  1368.  
  1369.         if ( ! $wpdb->get_results( "DESCRIBE $table;" ) )
  1370.             continue;
  1371.  
  1372.         // One or more tables exist. We are insane.
  1373.  
  1374.         wp_load_translations_early();
  1375.  
  1376.         // Die with a DB error.
  1377.         $wpdb->error = sprintf( __( 'One or more database tables are unavailable. The database may need to be <a href="%s">repaired</a>.' ), 'maint/repair.php?referrer=is_blog_installed' );
  1378.         dead_db();
  1379.     }
  1380.  
  1381.     $wpdb->suppress_errors( $suppress );
  1382.  
  1383.     wp_cache_set( 'is_blog_installed', false );
  1384.  
  1385.     return false;
  1386. }
  1387.  
  1388. /**
  1389.  * Retrieve URL with nonce added to URL query.
  1390.  *
  1391.  * @since 2.0.4
  1392.  *
  1393.  * @param string $actionurl URL to add nonce action.
  1394.  * @param string $action    Optional. Nonce action name. Default -1.
  1395.  * @param string $name      Optional. Nonce name. Default '_wpnonce'.
  1396.  * @return string Escaped URL with nonce action added.
  1397.  */
  1398. function wp_nonce_url( $actionurl, $action = -1, $name = '_wpnonce' ) {
  1399.     $actionurl = str_replace( '&amp;', '&', $actionurl );
  1400.     return esc_html( add_query_arg( $name, wp_create_nonce( $action ), $actionurl ) );
  1401. }
  1402.  
  1403. /**
  1404.  * Retrieve or display nonce hidden field for forms.
  1405.  *
  1406.  * The nonce field is used to validate that the contents of the form came from
  1407.  * the location on the current site and not somewhere else. The nonce does not
  1408.  * offer absolute protection, but should protect against most cases. It is very
  1409.  * important to use nonce field in forms.
  1410.  *
  1411.  * The $action and $name are optional, but if you want to have better security,
  1412.  * it is strongly suggested to set those two parameters. It is easier to just
  1413.  * call the function without any parameters, because validation of the nonce
  1414.  * doesn't require any parameters, but since crackers know what the default is
  1415.  * it won't be difficult for them to find a way around your nonce and cause
  1416.  * damage.
  1417.  *
  1418.  * The input name will be whatever $name value you gave. The input value will be
  1419.  * the nonce creation value.
  1420.  *
  1421.  * @since 2.0.4
  1422.  *
  1423.  * @param string $action  Optional. Action name. Default -1.
  1424.  * @param string $name    Optional. Nonce name. Default '_wpnonce'.
  1425.  * @param bool   $referer Optional. Whether to set the referer field for validation. Default true.
  1426.  * @param bool   $echo    Optional. Whether to display or return hidden form field. Default true.
  1427.  * @return string Nonce field HTML markup.
  1428.  */
  1429. function wp_nonce_field( $action = -1, $name = "_wpnonce", $referer = true , $echo = true ) {
  1430.     $name = esc_attr( $name );
  1431.     $nonce_field = '<input type="hidden" id="' . $name . '" name="' . $name . '" value="' . wp_create_nonce( $action ) . '" />';
  1432.  
  1433.     if ( $referer )
  1434.         $nonce_field .= wp_referer_field( false );
  1435.  
  1436.     if ( $echo )
  1437.         echo $nonce_field;
  1438.  
  1439.     return $nonce_field;
  1440. }
  1441.  
  1442. /**
  1443.  * Retrieve or display referer hidden field for forms.
  1444.  *
  1445.  * The referer link is the current Request URI from the server super global. The
  1446.  * input name is '_wp_http_referer', in case you wanted to check manually.
  1447.  *
  1448.  * @since 2.0.4
  1449.  *
  1450.  * @param bool $echo Optional. Whether to echo or return the referer field. Default true.
  1451.  * @return string Referer field HTML markup.
  1452.  */
  1453. function wp_referer_field( $echo = true ) {
  1454.     $referer_field = '<input type="hidden" name="_wp_http_referer" value="'. esc_attr( wp_unslash( $_SERVER['REQUEST_URI'] ) ) . '" />';
  1455.  
  1456.     if ( $echo )
  1457.         echo $referer_field;
  1458.     return $referer_field;
  1459. }
  1460.  
  1461. /**
  1462.  * Retrieve or display original referer hidden field for forms.
  1463.  *
  1464.  * The input name is '_wp_original_http_referer' and will be either the same
  1465.  * value of wp_referer_field(), if that was posted already or it will be the
  1466.  * current page, if it doesn't exist.
  1467.  *
  1468.  * @since 2.0.4
  1469.  *
  1470.  * @param bool   $echo         Optional. Whether to echo the original http referer. Default true.
  1471.  * @param string $jump_back_to Optional. Can be 'previous' or page you want to jump back to.
  1472.  *                             Default 'current'.
  1473.  * @return string Original referer field.
  1474.  */
  1475. function wp_original_referer_field( $echo = true, $jump_back_to = 'current' ) {
  1476.     if ( ! $ref = wp_get_original_referer() ) {
  1477.         $ref = 'previous' == $jump_back_to ? wp_get_referer() : wp_unslash( $_SERVER['REQUEST_URI'] );
  1478.     }
  1479.     $orig_referer_field = '<input type="hidden" name="_wp_original_http_referer" value="' . esc_attr( $ref ) . '" />';
  1480.     if ( $echo )
  1481.         echo $orig_referer_field;
  1482.     return $orig_referer_field;
  1483. }
  1484.  
  1485. /**
  1486.  * Retrieve referer from '_wp_http_referer' or HTTP referer.
  1487.  *
  1488.  * If it's the same as the current request URL, will return false.
  1489.  *
  1490.  * @since 2.0.4
  1491.  *
  1492.  * @return string|bool False on failure. Referer URL on success.
  1493.  */
  1494. function wp_get_referer() {
  1495.     if ( ! function_exists( 'wp_validate_redirect' ) )
  1496.         return false;
  1497.     $ref = false;
  1498.     if ( ! empty( $_REQUEST['_wp_http_referer'] ) )
  1499.         $ref = wp_unslash( $_REQUEST['_wp_http_referer'] );
  1500.     else if ( ! empty( $_SERVER['HTTP_REFERER'] ) )
  1501.         $ref = wp_unslash( $_SERVER['HTTP_REFERER'] );
  1502.  
  1503.     if ( $ref && $ref !== wp_unslash( $_SERVER['REQUEST_URI'] ) )
  1504.         return wp_validate_redirect( $ref, false );
  1505.     return false;
  1506. }
  1507.  
  1508. /**
  1509.  * Retrieve original referer that was posted, if it exists.
  1510.  *
  1511.  * @since 2.0.4
  1512.  *
  1513.  * @return string|bool False if no original referer or original referer if set.
  1514.  */
  1515. function wp_get_original_referer() {
  1516.     if ( ! empty( $_REQUEST['_wp_original_http_referer'] ) && function_exists( 'wp_validate_redirect' ) )
  1517.         return wp_validate_redirect( wp_unslash( $_REQUEST['_wp_original_http_referer'] ), false );
  1518.     return false;
  1519. }
  1520.  
  1521. /**
  1522.  * Recursive directory creation based on full path.
  1523.  *
  1524.  * Will attempt to set permissions on folders.
  1525.  *
  1526.  * @since 2.0.1
  1527.  *
  1528.  * @param string $target Full path to attempt to create.
  1529.  * @return bool Whether the path was created. True if path already exists.
  1530.  */
  1531. function wp_mkdir_p( $target ) {
  1532.     $wrapper = null;
  1533.  
  1534.     // Strip the protocol.
  1535.     if( wp_is_stream( $target ) ) {
  1536.         list( $wrapper, $target ) = explode( '://', $target, 2 );
  1537.     }
  1538.  
  1539.     // From php.net/mkdir user contributed notes.
  1540.     $target = str_replace( '//', '/', $target );
  1541.  
  1542.     // Put the wrapper back on the target.
  1543.     if( $wrapper !== null ) {
  1544.         $target = $wrapper . '://' . $target;
  1545.     }
  1546.  
  1547.     /*
  1548.      * Safe mode fails with a trailing slash under certain PHP versions.
  1549.      * Use rtrim() instead of untrailingslashit to avoid formatting.php dependency.
  1550.      */
  1551.     $target = rtrim($target, '/');
  1552.     if ( empty($target) )
  1553.         $target = '/';
  1554.  
  1555.     if ( file_exists( $target ) )
  1556.         return @is_dir( $target );
  1557.  
  1558.     // We need to find the permissions of the parent folder that exists and inherit that.
  1559.     $target_parent = dirname( $target );
  1560.     while ( '.' != $target_parent && ! is_dir( $target_parent ) ) {
  1561.         $target_parent = dirname( $target_parent );
  1562.     }
  1563.  
  1564.     // Get the permission bits.
  1565.     if ( $stat = @stat( $target_parent ) ) {
  1566.         $dir_perms = $stat['mode'] & 0007777;
  1567.     } else {
  1568.         $dir_perms = 0777;
  1569.     }
  1570.  
  1571.     if ( @mkdir( $target, $dir_perms, true ) ) {
  1572.  
  1573.         /*
  1574.          * If a umask is set that modifies $dir_perms, we'll have to re-set
  1575.          * the $dir_perms correctly with chmod()
  1576.          */
  1577.         if ( $dir_perms != ( $dir_perms & ~umask() ) ) {
  1578.             $folder_parts = explode( '/', substr( $target, strlen( $target_parent ) + 1 ) );
  1579.             for ( $i = 1; $i <= count( $folder_parts ); $i++ ) {
  1580.                 @chmod( $target_parent . '/' . implode( '/', array_slice( $folder_parts, 0, $i ) ), $dir_perms );
  1581.             }
  1582.         }
  1583.  
  1584.         return true;
  1585.     }
  1586.  
  1587.     return false;
  1588. }
  1589.  
  1590. /**
  1591.  * Test if a give filesystem path is absolute.
  1592.  *
  1593.  * For example, '/foo/bar', or 'c:\windows'.
  1594.  *
  1595.  * @since 2.5.0
  1596.  *
  1597.  * @param string $path File path.
  1598.  * @return bool True if path is absolute, false is not absolute.
  1599.  */
  1600. function path_is_absolute( $path ) {
  1601.     /*
  1602.      * This is definitive if true but fails if $path does not exist or contains
  1603.      * a symbolic link.
  1604.      */
  1605.     if ( realpath($path) == $path )
  1606.         return true;
  1607.  
  1608.     if ( strlen($path) == 0 || $path[0] == '.' )
  1609.         return false;
  1610.  
  1611.     // Windows allows absolute paths like this.
  1612.     if ( preg_match('#^[a-zA-Z]:\\\\#', $path) )
  1613.         return true;
  1614.  
  1615.     // A path starting with / or \ is absolute; anything else is relative.
  1616.     return ( $path[0] == '/' || $path[0] == '\\' );
  1617. }
  1618.  
  1619. /**
  1620.  * Join two filesystem paths together.
  1621.  *
  1622.  * For example, 'give me $path relative to $base'. If the $path is absolute,
  1623.  * then it the full path is returned.
  1624.  *
  1625.  * @since 2.5.0
  1626.  *
  1627.  * @param string $base Base path.
  1628.  * @param string $path Path relative to $base.
  1629.  * @return string The path with the base or absolute path.
  1630.  */
  1631. function path_join( $base, $path ) {
  1632.     if ( path_is_absolute($path) )
  1633.         return $path;
  1634.  
  1635.     return rtrim($base, '/') . '/' . ltrim($path, '/');
  1636. }
  1637.  
  1638. /**
  1639.  * Normalize a filesystem path.
  1640.  *
  1641.  * Replaces backslashes with forward slashes for Windows systems, and ensures
  1642.  * no duplicate slashes exist.
  1643.  *
  1644.  * @since 3.9.0
  1645.  *
  1646.  * @param string $path Path to normalize.
  1647.  * @return string Normalized path.
  1648.  */
  1649. function wp_normalize_path( $path ) {
  1650.     $path = str_replace( '\\', '/', $path );
  1651.     $path = preg_replace( '|/+|','/', $path );
  1652.     return $path;
  1653. }
  1654.  
  1655. /**
  1656.  * Determine a writable directory for temporary files.
  1657.  *
  1658.  * Function's preference is the return value of sys_get_temp_dir(),
  1659.  * followed by your PHP temporary upload directory, followed by WP_CONTENT_DIR,
  1660.  * before finally defaulting to /tmp/
  1661.  *
  1662.  * In the event that this function does not find a writable location,
  1663.  * It may be overridden by the WP_TEMP_DIR constant in your wp-config.php file.
  1664.  *
  1665.  * @since 2.5.0
  1666.  *
  1667.  * @return string Writable temporary directory.
  1668.  */
  1669. function get_temp_dir() {
  1670.     static $temp;
  1671.     if ( defined('WP_TEMP_DIR') )
  1672.         return trailingslashit(WP_TEMP_DIR);
  1673.  
  1674.     if ( $temp )
  1675.         return trailingslashit( $temp );
  1676.  
  1677.     if ( function_exists('sys_get_temp_dir') ) {
  1678.         $temp = sys_get_temp_dir();
  1679.         if ( @is_dir( $temp ) && wp_is_writable( $temp ) )
  1680.             return trailingslashit( $temp );
  1681.     }
  1682.  
  1683.     $temp = ini_get('upload_tmp_dir');
  1684.     if ( @is_dir( $temp ) && wp_is_writable( $temp ) )
  1685.         return trailingslashit( $temp );
  1686.  
  1687.     $temp = WP_CONTENT_DIR . '/';
  1688.     if ( is_dir( $temp ) && wp_is_writable( $temp ) )
  1689.         return $temp;
  1690.  
  1691.     $temp = '/tmp/';
  1692.     return $temp;
  1693. }
  1694.  
  1695. /**
  1696.  * Determine if a directory is writable.
  1697.  *
  1698.  * This function is used to work around certain ACL issues in PHP primarily
  1699.  * affecting Windows Servers.
  1700.  *
  1701.  * @since 3.6.0
  1702.  *
  1703.  * @see win_is_writable()
  1704.  *
  1705.  * @param string $path Path to check for write-ability.
  1706.  * @return bool Whether the path is writable.
  1707.  */
  1708. function wp_is_writable( $path ) {
  1709.     if ( 'WIN' === strtoupper( substr( PHP_OS, 0, 3 ) ) )
  1710.         return win_is_writable( $path );
  1711.     else
  1712.         return @is_writable( $path );
  1713. }
  1714.  
  1715. /**
  1716.  * Workaround for Windows bug in is_writable() function
  1717.  *
  1718.  * PHP has issues with Windows ACL's for determine if a
  1719.  * directory is writable or not, this works around them by
  1720.  * checking the ability to open files rather than relying
  1721.  * upon PHP to interprate the OS ACL.
  1722.  *
  1723.  * @since 2.8.0
  1724.  *
  1725.  * @see http://bugs.php.net/bug.php?id=27609
  1726.  * @see http://bugs.php.net/bug.php?id=30931
  1727.  *
  1728.  * @param string $path Windows path to check for write-ability.
  1729.  * @return bool Whether the path is writable.
  1730.  */
  1731. function win_is_writable( $path ) {
  1732.  
  1733.     if ( $path[strlen( $path ) - 1] == '/' ) // if it looks like a directory, check a random file within the directory
  1734.         return win_is_writable( $path . uniqid( mt_rand() ) . '.tmp');
  1735.     else if ( is_dir( $path ) ) // If it's a directory (and not a file) check a random file within the directory
  1736.         return win_is_writable( $path . '/' . uniqid( mt_rand() ) . '.tmp' );
  1737.  
  1738.     // check tmp file for read/write capabilities
  1739.     $should_delete_tmp_file = !file_exists( $path );
  1740.     $f = @fopen( $path, 'a' );
  1741.     if ( $f === false )
  1742.         return false;
  1743.     fclose( $f );
  1744.     if ( $should_delete_tmp_file )
  1745.         unlink( $path );
  1746.     return true;
  1747. }
  1748.  
  1749. /**
  1750.  * Get an array containing the current upload directory's path and url.
  1751.  *
  1752.  * Checks the 'upload_path' option, which should be from the web root folder,
  1753.  * and if it isn't empty it will be used. If it is empty, then the path will be
  1754.  * 'WP_CONTENT_DIR/uploads'. If the 'UPLOADS' constant is defined, then it will
  1755.  * override the 'upload_path' option and 'WP_CONTENT_DIR/uploads' path.
  1756.  *
  1757.  * The upload URL path is set either by the 'upload_url_path' option or by using
  1758.  * the 'WP_CONTENT_URL' constant and appending '/uploads' to the path.
  1759.  *
  1760.  * If the 'uploads_use_yearmonth_folders' is set to true (checkbox if checked in
  1761.  * the administration settings panel), then the time will be used. The format
  1762.  * will be year first and then month.
  1763.  *
  1764.  * If the path couldn't be created, then an error will be returned with the key
  1765.  * 'error' containing the error message. The error suggests that the parent
  1766.  * directory is not writable by the server.
  1767.  *
  1768.  * On success, the returned array will have many indices:
  1769.  * 'path' - base directory and sub directory or full path to upload directory.
  1770.  * 'url' - base url and sub directory or absolute URL to upload directory.
  1771.  * 'subdir' - sub directory if uploads use year/month folders option is on.
  1772.  * 'basedir' - path without subdir.
  1773.  * 'baseurl' - URL path without subdir.
  1774.  * 'error' - set to false.
  1775.  *
  1776.  * @since 2.0.0
  1777.  *
  1778.  * @param string $time Optional. Time formatted in 'yyyy/mm'. Default null.
  1779.  * @return array See above for description.
  1780.  */
  1781. function wp_upload_dir( $time = null ) {
  1782.     $siteurl = get_option( 'siteurl' );
  1783.     $upload_path = trim( get_option( 'upload_path' ) );
  1784.  
  1785.     if ( empty( $upload_path ) || 'wp-content/uploads' == $upload_path ) {
  1786.         $dir = WP_CONTENT_DIR . '/uploads';
  1787.     } elseif ( 0 !== strpos( $upload_path, ABSPATH ) ) {
  1788.         // $dir is absolute, $upload_path is (maybe) relative to ABSPATH
  1789.         $dir = path_join( ABSPATH, $upload_path );
  1790.     } else {
  1791.         $dir = $upload_path;
  1792.     }
  1793.  
  1794.     if ( !$url = get_option( 'upload_url_path' ) ) {
  1795.         if ( empty($upload_path) || ( 'wp-content/uploads' == $upload_path ) || ( $upload_path == $dir ) )
  1796.             $url = WP_CONTENT_URL . '/uploads';
  1797.         else
  1798.             $url = trailingslashit( $siteurl ) . $upload_path;
  1799.     }
  1800.  
  1801.     /*
  1802.      * Honor the value of UPLOADS. This happens as long as ms-files rewriting is disabled.
  1803.      * We also sometimes obey UPLOADS when rewriting is enabled -- see the next block.
  1804.      */
  1805.     if ( defined( 'UPLOADS' ) && ! ( is_multisite() && get_site_option( 'ms_files_rewriting' ) ) ) {
  1806.         $dir = ABSPATH . UPLOADS;
  1807.         $url = trailingslashit( $siteurl ) . UPLOADS;
  1808.     }
  1809.  
  1810.     // If multisite (and if not the main site in a post-MU network)
  1811.     if ( is_multisite() && ! ( is_main_network() && is_main_site() && defined( 'MULTISITE' ) ) ) {
  1812.  
  1813.         if ( ! get_site_option( 'ms_files_rewriting' ) ) {
  1814.             /*
  1815.              * If ms-files rewriting is disabled (networks created post-3.5), it is fairly
  1816.              * straightforward: Append sites/%d if we're not on the main site (for post-MU
  1817.              * networks). (The extra directory prevents a four-digit ID from conflicting with
  1818.              * a year-based directory for the main site. But if a MU-era network has disabled
  1819.              * ms-files rewriting manually, they don't need the extra directory, as they never
  1820.              * had wp-content/uploads for the main site.)
  1821.              */
  1822.  
  1823.             if ( defined( 'MULTISITE' ) )
  1824.                 $ms_dir = '/sites/' . get_current_blog_id();
  1825.             else
  1826.                 $ms_dir = '/' . get_current_blog_id();
  1827.  
  1828.             $dir .= $ms_dir;
  1829.             $url .= $ms_dir;
  1830.  
  1831.         } elseif ( defined( 'UPLOADS' ) && ! ms_is_switched() ) {
  1832.             /*
  1833.              * Handle the old-form ms-files.php rewriting if the network still has that enabled.
  1834.              * When ms-files rewriting is enabled, then we only listen to UPLOADS when:
  1835.              * 1) We are not on the main site in a post-MU network, as wp-content/uploads is used
  1836.              *    there, and
  1837.              * 2) We are not switched, as ms_upload_constants() hardcodes these constants to reflect
  1838.              *    the original blog ID.
  1839.              *
  1840.              * Rather than UPLOADS, we actually use BLOGUPLOADDIR if it is set, as it is absolute.
  1841.              * (And it will be set, see ms_upload_constants().) Otherwise, UPLOADS can be used, as
  1842.              * as it is relative to ABSPATH. For the final piece: when UPLOADS is used with ms-files
  1843.              * rewriting in multisite, the resulting URL is /files. (#WP22702 for background.)
  1844.              */
  1845.  
  1846.             if ( defined( 'BLOGUPLOADDIR' ) )
  1847.                 $dir = untrailingslashit( BLOGUPLOADDIR );
  1848.             else
  1849.                 $dir = ABSPATH . UPLOADS;
  1850.             $url = trailingslashit( $siteurl ) . 'files';
  1851.         }
  1852.     }
  1853.  
  1854.     $basedir = $dir;
  1855.     $baseurl = $url;
  1856.  
  1857.     $subdir = '';
  1858.     if ( get_option( 'uploads_use_yearmonth_folders' ) ) {
  1859.         // Generate the yearly and monthly dirs
  1860.         if ( !$time )
  1861.             $time = current_time( 'mysql' );
  1862.         $y = substr( $time, 0, 4 );
  1863.         $m = substr( $time, 5, 2 );
  1864.         $subdir = "/$y/$m";
  1865.     }
  1866.  
  1867.     $dir .= $subdir;
  1868.     $url .= $subdir;
  1869.  
  1870.     /**
  1871.      * Filter the uploads directory data.
  1872.      *
  1873.      * @since 2.0.0
  1874.      *
  1875.      * @param array $uploads Array of upload directory data with keys of 'path',
  1876.      *                       'url', 'subdir, 'basedir', and 'error'.
  1877.      */
  1878.     $uploads = apply_filters( 'upload_dir',
  1879.         array(
  1880.             'path'    => $dir,
  1881.             'url'     => $url,
  1882.             'subdir'  => $subdir,
  1883.             'basedir' => $basedir,
  1884.             'baseurl' => $baseurl,
  1885.             'error'   => false,
  1886.         ) );
  1887.  
  1888.     // Make sure we have an uploads directory.
  1889.     if ( ! wp_mkdir_p( $uploads['path'] ) ) {
  1890.         if ( 0 === strpos( $uploads['basedir'], ABSPATH ) )
  1891.             $error_path = str_replace( ABSPATH, '', $uploads['basedir'] ) . $uploads['subdir'];
  1892.         else
  1893.             $error_path = basename( $uploads['basedir'] ) . $uploads['subdir'];
  1894.  
  1895.         $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), $error_path );
  1896.         $uploads['error'] = $message;
  1897.     }
  1898.  
  1899.     return $uploads;
  1900. }
  1901.  
  1902. /**
  1903.  * Get a filename that is sanitized and unique for the given directory.
  1904.  *
  1905.  * If the filename is not unique, then a number will be added to the filename
  1906.  * before the extension, and will continue adding numbers until the filename is
  1907.  * unique.
  1908.  *
  1909.  * The callback is passed three parameters, the first one is the directory, the
  1910.  * second is the filename, and the third is the extension.
  1911.  *
  1912.  * @since 2.5.0
  1913.  *
  1914.  * @param string   $dir                      Directory.
  1915.  * @param string   $filename                 File name.
  1916.  * @param callback $unique_filename_callback Callback. Default null.
  1917.  * @return string New filename, if given wasn't unique.
  1918.  */
  1919. function wp_unique_filename( $dir, $filename, $unique_filename_callback = null ) {
  1920.     // Sanitize the file name before we begin processing.
  1921.     $filename = sanitize_file_name($filename);
  1922.  
  1923.     // Separate the filename into a name and extension.
  1924.     $info = pathinfo($filename);
  1925.     $ext = !empty($info['extension']) ? '.' . $info['extension'] : '';
  1926.     $name = basename($filename, $ext);
  1927.  
  1928.     // Edge case: if file is named '.ext', treat as an empty name.
  1929.     if ( $name === $ext )
  1930.         $name = '';
  1931.  
  1932.     /*
  1933.      * Increment the file number until we have a unique file to save in $dir.
  1934.      * Use callback if supplied.
  1935.      */
  1936.     if ( $unique_filename_callback && is_callable( $unique_filename_callback ) ) {
  1937.         $filename = call_user_func( $unique_filename_callback, $dir, $name, $ext );
  1938.     } else {
  1939.         $number = '';
  1940.  
  1941.         // Change '.ext' to lower case.
  1942.         if ( $ext && strtolower($ext) != $ext ) {
  1943.             $ext2 = strtolower($ext);
  1944.             $filename2 = preg_replace( '|' . preg_quote($ext) . '$|', $ext2, $filename );
  1945.  
  1946.             // Check for both lower and upper case extension or image sub-sizes may be overwritten.
  1947.             while ( file_exists($dir . "/$filename") || file_exists($dir . "/$filename2") ) {
  1948.                 $new_number = $number + 1;
  1949.                 $filename = str_replace( "$number$ext", "$new_number$ext", $filename );
  1950.                 $filename2 = str_replace( "$number$ext2", "$new_number$ext2", $filename2 );
  1951.                 $number = $new_number;
  1952.             }
  1953.             return $filename2;
  1954.         }
  1955.  
  1956.         while ( file_exists( $dir . "/$filename" ) ) {
  1957.             if ( '' == "$number$ext" )
  1958.                 $filename = $filename . ++$number . $ext;
  1959.             else
  1960.                 $filename = str_replace( "$number$ext", ++$number . $ext, $filename );
  1961.         }
  1962.     }
  1963.  
  1964.     return $filename;
  1965. }
  1966.  
  1967. /**
  1968.  * Create a file in the upload folder with given content.
  1969.  *
  1970.  * If there is an error, then the key 'error' will exist with the error message.
  1971.  * If success, then the key 'file' will have the unique file path, the 'url' key
  1972.  * will have the link to the new file. and the 'error' key will be set to false.
  1973.  *
  1974.  * This function will not move an uploaded file to the upload folder. It will
  1975.  * create a new file with the content in $bits parameter. If you move the upload
  1976.  * file, read the content of the uploaded file, and then you can give the
  1977.  * filename and content to this function, which will add it to the upload
  1978.  * folder.
  1979.  *
  1980.  * The permissions will be set on the new file automatically by this function.
  1981.  *
  1982.  * @since 2.0.0
  1983.  *
  1984.  * @param string $name       Filename.
  1985.  * @param null   $deprecated Never used. Set to null.
  1986.  * @param mixed  $bits       File content
  1987.  * @param string $time       Optional. Time formatted in 'yyyy/mm'. Default null.
  1988.  * @return array
  1989.  */
  1990. function wp_upload_bits( $name, $deprecated, $bits, $time = null ) {
  1991.     if ( !empty( $deprecated ) )
  1992.         _deprecated_argument( __FUNCTION__, '2.0' );
  1993.  
  1994.     if ( empty( $name ) )
  1995.         return array( 'error' => __( 'Empty filename' ) );
  1996.  
  1997.     $wp_filetype = wp_check_filetype( $name );
  1998.     if ( ! $wp_filetype['ext'] && ! current_user_can( 'unfiltered_upload' ) )
  1999.         return array( 'error' => __( 'Invalid file type' ) );
  2000.  
  2001.     $upload = wp_upload_dir( $time );
  2002.  
  2003.     if ( $upload['error'] !== false )
  2004.         return $upload;
  2005.  
  2006.     /**
  2007.      * Filter whether to treat the upload bits as an error.
  2008.      *
  2009.      * Passing a non-array to the filter will effectively short-circuit preparing
  2010.      * the upload bits, returning that value instead.
  2011.      *
  2012.      * @since 3.0.0
  2013.      *
  2014.      * @param mixed $upload_bits_error An array of upload bits data, or a non-array error to return.
  2015.      */
  2016.     $upload_bits_error = apply_filters( 'wp_upload_bits', array( 'name' => $name, 'bits' => $bits, 'time' => $time ) );
  2017.     if ( !is_array( $upload_bits_error ) ) {
  2018.         $upload[ 'error' ] = $upload_bits_error;
  2019.         return $upload;
  2020.     }
  2021.  
  2022.     $filename = wp_unique_filename( $upload['path'], $name );
  2023.  
  2024.     $new_file = $upload['path'] . "/$filename";
  2025.     if ( ! wp_mkdir_p( dirname( $new_file ) ) ) {
  2026.         if ( 0 === strpos( $upload['basedir'], ABSPATH ) )
  2027.             $error_path = str_replace( ABSPATH, '', $upload['basedir'] ) . $upload['subdir'];
  2028.         else
  2029.             $error_path = basename( $upload['basedir'] ) . $upload['subdir'];
  2030.  
  2031.         $message = sprintf( __( 'Unable to create directory %s. Is its parent directory writable by the server?' ), $error_path );
  2032.         return array( 'error' => $message );
  2033.     }
  2034.  
  2035.     $ifp = @ fopen( $new_file, 'wb' );
  2036.     if ( ! $ifp )
  2037.         return array( 'error' => sprintf( __( 'Could not write file %s' ), $new_file ) );
  2038.  
  2039.     @fwrite( $ifp, $bits );
  2040.     fclose( $ifp );
  2041.     clearstatcache();
  2042.  
  2043.     // Set correct file permissions
  2044.     $stat = @ stat( dirname( $new_file ) );
  2045.     $perms = $stat['mode'] & 0007777;
  2046.     $perms = $perms & 0000666;
  2047.     @ chmod( $new_file, $perms );
  2048.     clearstatcache();
  2049.  
  2050.     // Compute the URL
  2051.     $url = $upload['url'] . "/$filename";
  2052.  
  2053.     return array( 'file' => $new_file, 'url' => $url, 'error' => false );
  2054. }
  2055.  
  2056. /**
  2057.  * Retrieve the file type based on the extension name.
  2058.  *
  2059.  * @since 2.5.0
  2060.  *
  2061.  * @param string $ext The extension to search.
  2062.  * @return string|null The file type, example: audio, video, document, spreadsheet, etc.
  2063.  *                     Null if not found.
  2064.  */
  2065. function wp_ext2type( $ext ) {
  2066.     $ext = strtolower( $ext );
  2067.  
  2068.     /**
  2069.      * Filter file type based on the extension name.
  2070.      *
  2071.      * @since 2.5.0
  2072.      *
  2073.      * @see wp_ext2type()
  2074.      *
  2075.      * @param array $ext2type Multi-dimensional array with extensions for a default set
  2076.      *                        of file types.
  2077.      */
  2078.     $ext2type = apply_filters( 'ext2type', array(
  2079.         'image'       => array( 'jpg', 'jpeg', 'jpe',  'gif',  'png',  'bmp',   'tif',  'tiff', 'ico' ),
  2080.         'audio'       => array( 'aac', 'ac3',  'aif',  'aiff', 'm3a',  'm4a',   'm4b',  'mka',  'mp1',  'mp2',  'mp3', 'ogg', 'oga', 'ram', 'wav', 'wma' ),
  2081.         'video'       => array( '3g2',  '3gp', '3gpp', 'asf', 'avi',  'divx', 'dv',   'flv',  'm4v',   'mkv',  'mov',  'mp4',  'mpeg', 'mpg', 'mpv', 'ogm', 'ogv', 'qt',  'rm', 'vob', 'wmv' ),
  2082.         'document'    => array( 'doc', 'docx', 'docm', 'dotm', 'odt',  'pages', 'pdf',  'xps',  'oxps', 'rtf',  'wp',   'wpd' ),
  2083.         'spreadsheet' => array( 'numbers',     'ods',  'xls',  'xlsx', 'xlsm',  'xlsb' ),
  2084.         'interactive' => array( 'swf', 'key',  'ppt',  'pptx', 'pptm', 'pps',   'ppsx', 'ppsm', 'sldx', 'sldm', 'odp' ),
  2085.         'text'        => array( 'asc', 'csv',  'tsv',  'txt' ),
  2086.         'archive'     => array( 'bz2', 'cab',  'dmg',  'gz',   'rar',  'sea',   'sit',  'sqx',  'tar',  'tgz',  'zip', '7z' ),
  2087.         'code'        => array( 'css', 'htm',  'html', 'php',  'js' ),
  2088.     ) );
  2089.  
  2090.     foreach ( $ext2type as $type => $exts )
  2091.         if ( in_array( $ext, $exts ) )
  2092.             return $type;
  2093.  
  2094.     return null;
  2095. }
  2096.  
  2097. /**
  2098.  * Retrieve the file type from the file name.
  2099.  *
  2100.  * You can optionally define the mime array, if needed.
  2101.  *
  2102.  * @since 2.0.4
  2103.  *
  2104.  * @param string $filename File name or path.
  2105.  * @param array  $mimes    Optional. Key is the file extension with value as the mime type.
  2106.  * @return array Values with extension first and mime type.
  2107.  */
  2108. function wp_check_filetype( $filename, $mimes = null ) {
  2109.     if ( empty($mimes) )
  2110.         $mimes = get_allowed_mime_types();
  2111.     $type = false;
  2112.     $ext = false;
  2113.  
  2114.     foreach ( $mimes as $ext_preg => $mime_match ) {
  2115.         $ext_preg = '!\.(' . $ext_preg . ')$!i';
  2116.         if ( preg_match( $ext_preg, $filename, $ext_matches ) ) {
  2117.             $type = $mime_match;
  2118.             $ext = $ext_matches[1];
  2119.             break;
  2120.         }
  2121.     }
  2122.  
  2123.     return compact( 'ext', 'type' );
  2124. }
  2125.  
  2126. /**
  2127.  * Attempt to determine the real file type of a file.
  2128.  *
  2129.  * If unable to, the file name extension will be used to determine type.
  2130.  *
  2131.  * If it's determined that the extension does not match the file's real type,
  2132.  * then the "proper_filename" value will be set with a proper filename and extension.
  2133.  *
  2134.  * Currently this function only supports validating images known to getimagesize().
  2135.  *
  2136.  * @since 3.0.0
  2137.  *
  2138.  * @param string $file     Full path to the file.
  2139.  * @param string $filename The name of the file (may differ from $file due to $file being
  2140.  *                         in a tmp directory).
  2141.  * @param array   $mimes   Optional. Key is the file extension with value as the mime type.
  2142.  * @return array Values for the extension, MIME, and either a corrected filename or false
  2143.  *               if original $filename is valid.
  2144.  */
  2145. function wp_check_filetype_and_ext( $file, $filename, $mimes = null ) {
  2146.  
  2147.     $proper_filename = false;
  2148.  
  2149.     // Do basic extension validation and MIME mapping
  2150.     $wp_filetype = wp_check_filetype( $filename, $mimes );
  2151.     $ext = $wp_filetype['ext'];
  2152.     $type = $wp_filetype['type'];
  2153.  
  2154.     // We can't do any further validation without a file to work with
  2155.     if ( ! file_exists( $file ) ) {
  2156.         return compact( 'ext', 'type', 'proper_filename' );
  2157.     }
  2158.  
  2159.     // We're able to validate images using GD
  2160.     if ( $type && 0 === strpos( $type, 'image/' ) && function_exists('getimagesize') ) {
  2161.  
  2162.         // Attempt to figure out what type of image it actually is
  2163.         $imgstats = @getimagesize( $file );
  2164.  
  2165.         // If getimagesize() knows what kind of image it really is and if the real MIME doesn't match the claimed MIME
  2166.         if ( !empty($imgstats['mime']) && $imgstats['mime'] != $type ) {
  2167.             /**
  2168.              * Filter the list mapping image mime types to their respective extensions.
  2169.              *
  2170.              * @since 3.0.0
  2171.              *
  2172.              * @param  array $mime_to_ext Array of image mime types and their matching extensions.
  2173.              */
  2174.             $mime_to_ext = apply_filters( 'getimagesize_mimes_to_exts', array(
  2175.                 'image/jpeg' => 'jpg',
  2176.                 'image/png'  => 'png',
  2177.                 'image/gif'  => 'gif',
  2178.                 'image/bmp'  => 'bmp',
  2179.                 'image/tiff' => 'tif',
  2180.             ) );
  2181.  
  2182.             // Replace whatever is after the last period in the filename with the correct extension
  2183.             if ( ! empty( $mime_to_ext[ $imgstats['mime'] ] ) ) {
  2184.                 $filename_parts = explode( '.', $filename );
  2185.                 array_pop( $filename_parts );
  2186.                 $filename_parts[] = $mime_to_ext[ $imgstats['mime'] ];
  2187.                 $new_filename = implode( '.', $filename_parts );
  2188.  
  2189.                 if ( $new_filename != $filename ) {
  2190.                     $proper_filename = $new_filename; // Mark that it changed
  2191.                 }
  2192.                 // Redefine the extension / MIME
  2193.                 $wp_filetype = wp_check_filetype( $new_filename, $mimes );
  2194.                 $ext = $wp_filetype['ext'];
  2195.                 $type = $wp_filetype['type'];
  2196.             }
  2197.         }
  2198.     }
  2199.  
  2200.     /**
  2201.      * Filter the "real" file type of the given file.
  2202.      *
  2203.      * @since 3.0.0
  2204.      *
  2205.      * @param array  $wp_check_filetype_and_ext File data array containing 'ext', 'type', and
  2206.      *                                          'proper_filename' keys.
  2207.      * @param string $file                      Full path to the file.
  2208.      * @param string $filename                  The name of the file (may differ from $file due to
  2209.      *                                          $file being in a tmp directory).
  2210.      * @param array  $mimes                     Key is the file extension with value as the mime type.
  2211.      */
  2212.     return apply_filters( 'wp_check_filetype_and_ext', compact( 'ext', 'type', 'proper_filename' ), $file, $filename, $mimes );
  2213. }
  2214.  
  2215. /**
  2216.  * Retrieve list of mime types and file extensions.
  2217.  *
  2218.  * @since 3.5.0
  2219.  *
  2220.  * @return array Array of mime types keyed by the file extension regex corresponding to those types.
  2221.  */
  2222. function wp_get_mime_types() {
  2223.     /**
  2224.      * Filter the list of mime types and file extensions.
  2225.      *
  2226.      * This filter should be used to add, not remove, mime types. To remove
  2227.      * mime types, use the 'upload_mimes' filter.
  2228.      *
  2229.      * @since 3.5.0
  2230.      *
  2231.      * @param array $wp_get_mime_types Mime types keyed by the file extension regex
  2232.      *                                 corresponding to those types.
  2233.      */
  2234.     return apply_filters( 'mime_types', array(
  2235.     // Image formats.
  2236.     'jpg|jpeg|jpe' => 'image/jpeg',
  2237.     'gif' => 'image/gif',
  2238.     'png' => 'image/png',
  2239.     'bmp' => 'image/bmp',
  2240.     'tif|tiff' => 'image/tiff',
  2241.     'ico' => 'image/x-icon',
  2242.     // Video formats.
  2243.     'asf|asx' => 'video/x-ms-asf',
  2244.     'wmv' => 'video/x-ms-wmv',
  2245.     'wmx' => 'video/x-ms-wmx',
  2246.     'wm' => 'video/x-ms-wm',
  2247.     'avi' => 'video/avi',
  2248.     'divx' => 'video/divx',
  2249.     'flv' => 'video/x-flv',
  2250.     'mov|qt' => 'video/quicktime',
  2251.     'mpeg|mpg|mpe' => 'video/mpeg',
  2252.     'mp4|m4v' => 'video/mp4',
  2253.     'ogv' => 'video/ogg',
  2254.     'webm' => 'video/webm',
  2255.     'mkv' => 'video/x-matroska',
  2256.     '3gp|3gpp' => 'video/3gpp', // Can also be audio
  2257.     '3g2|3gp2' => 'video/3gpp2', // Can also be audio
  2258.     // Text formats.
  2259.     'txt|asc|c|cc|h|srt' => 'text/plain',
  2260.     'csv' => 'text/csv',
  2261.     'tsv' => 'text/tab-separated-values',
  2262.     'ics' => 'text/calendar',
  2263.     'rtx' => 'text/richtext',
  2264.     'css' => 'text/css',
  2265.     'htm|html' => 'text/html',
  2266.     'vtt' => 'text/vtt',
  2267.     'dfxp' => 'application/ttaf+xml',
  2268.     // Audio formats.
  2269.     'mp3|m4a|m4b' => 'audio/mpeg',
  2270.     'ra|ram' => 'audio/x-realaudio',
  2271.     'wav' => 'audio/wav',
  2272.     'ogg|oga' => 'audio/ogg',
  2273.     'mid|midi' => 'audio/midi',
  2274.     'wma' => 'audio/x-ms-wma',
  2275.     'wax' => 'audio/x-ms-wax',
  2276.     'mka' => 'audio/x-matroska',
  2277.     // Misc application formats.
  2278.     'rtf' => 'application/rtf',
  2279.     'js' => 'application/javascript',
  2280.     'pdf' => 'application/pdf',
  2281.     'swf' => 'application/x-shockwave-flash',
  2282.     'class' => 'application/java',
  2283.     'tar' => 'application/x-tar',
  2284.     'zip' => 'application/zip',
  2285.     'gz|gzip' => 'application/x-gzip',
  2286.     'rar' => 'application/rar',
  2287.     '7z' => 'application/x-7z-compressed',
  2288.     'exe' => 'application/x-msdownload',
  2289.     // MS Office formats.
  2290.     'doc' => 'application/msword',
  2291.     'pot|pps|ppt' => 'application/vnd.ms-powerpoint',
  2292.     'wri' => 'application/vnd.ms-write',
  2293.     'xla|xls|xlt|xlw' => 'application/vnd.ms-excel',
  2294.     'mdb' => 'application/vnd.ms-access',
  2295.     'mpp' => 'application/vnd.ms-project',
  2296.     'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  2297.     'docm' => 'application/vnd.ms-word.document.macroEnabled.12',
  2298.     'dotx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.template',
  2299.     'dotm' => 'application/vnd.ms-word.template.macroEnabled.12',
  2300.     'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  2301.     'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12',
  2302.     'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
  2303.     'xltx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.template',
  2304.     'xltm' => 'application/vnd.ms-excel.template.macroEnabled.12',
  2305.     'xlam' => 'application/vnd.ms-excel.addin.macroEnabled.12',
  2306.     'pptx' => 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  2307.     'pptm' => 'application/vnd.ms-powerpoint.presentation.macroEnabled.12',
  2308.     'ppsx' => 'application/vnd.openxmlformats-officedocument.presentationml.slideshow',
  2309.     'ppsm' => 'application/vnd.ms-powerpoint.slideshow.macroEnabled.12',
  2310.     'potx' => 'application/vnd.openxmlformats-officedocument.presentationml.template',
  2311.     'potm' => 'application/vnd.ms-powerpoint.template.macroEnabled.12',
  2312.     'ppam' => 'application/vnd.ms-powerpoint.addin.macroEnabled.12',
  2313.     'sldx' => 'application/vnd.openxmlformats-officedocument.presentationml.slide',
  2314.     'sldm' => 'application/vnd.ms-powerpoint.slide.macroEnabled.12',
  2315.     'onetoc|onetoc2|onetmp|onepkg' => 'application/onenote',
  2316.     'oxps' => 'application/oxps',
  2317.     'xps' => 'application/vnd.ms-xpsdocument',
  2318.     // OpenOffice formats.
  2319.     'odt' => 'application/vnd.oasis.opendocument.text',
  2320.     'odp' => 'application/vnd.oasis.opendocument.presentation',
  2321.     'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
  2322.     'odg' => 'application/vnd.oasis.opendocument.graphics',
  2323.     'odc' => 'application/vnd.oasis.opendocument.chart',
  2324.     'odb' => 'application/vnd.oasis.opendocument.database',
  2325.     'odf' => 'application/vnd.oasis.opendocument.formula',
  2326.     // WordPerfect formats.
  2327.     'wp|wpd' => 'application/wordperfect',
  2328.     // iWork formats.
  2329.     'key' => 'application/vnd.apple.keynote',
  2330.     'numbers' => 'application/vnd.apple.numbers',
  2331.     'pages' => 'application/vnd.apple.pages',
  2332.     ) );
  2333. }
  2334. /**
  2335.  * Retrieve list of allowed mime types and file extensions.
  2336.  *
  2337.  * @since 2.8.6
  2338.  *
  2339.  * @uses wp_get_upload_mime_types() to fetch the list of mime types
  2340.  *
  2341.  * @param int|WP_User $user Optional. User to check. Defaults to current user.
  2342.  * @return array Array of mime types keyed by the file extension regex corresponding
  2343.  *               to those types.
  2344.  */
  2345. function get_allowed_mime_types( $user = null ) {
  2346.     $t = wp_get_mime_types();
  2347.  
  2348.     unset( $t['swf'], $t['exe'] );
  2349.     if ( function_exists( 'current_user_can' ) )
  2350.         $unfiltered = $user ? user_can( $user, 'unfiltered_html' ) : current_user_can( 'unfiltered_html' );
  2351.  
  2352.     if ( empty( $unfiltered ) )
  2353.         unset( $t['htm|html'] );
  2354.  
  2355.     /**
  2356.      * Filter list of allowed mime types and file extensions.
  2357.      *
  2358.      * @since 2.0.0
  2359.      *
  2360.      * @param array            $t    Mime types keyed by the file extension regex corresponding to
  2361.      *                               those types. 'swf' and 'exe' removed from full list. 'htm|html' also
  2362.      *                               removed depending on '$user' capabilities.
  2363.      * @param int|WP_User|null $user User ID, User object or null if not provided (indicates current user).
  2364.      */
  2365.     return apply_filters( 'upload_mimes', $t, $user );
  2366. }
  2367.  
  2368. /**
  2369.  * Display "Are You Sure" message to confirm the action being taken.
  2370.  *
  2371.  * If the action has the nonce explain message, then it will be displayed
  2372.  * along with the "Are you sure?" message.
  2373.  *
  2374.  * @since 2.0.4
  2375.  *
  2376.  * @param string $action The nonce action.
  2377.  */
  2378. function wp_nonce_ays( $action ) {
  2379.     $title = __( 'WordPress Failure Notice' );
  2380.     if ( 'log-out' == $action ) {
  2381.         $html = sprintf( __( 'You are attempting to log out of %s' ), get_bloginfo( 'name' ) ) . '</p><p>';
  2382.         $redirect_to = isset( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : '';
  2383.         $html .= sprintf( __( "Do you really want to <a href='%s'>log out</a>?"), wp_logout_url( $redirect_to ) );
  2384.     } else {
  2385.         $html = __( 'Are you sure you want to do this?' );
  2386.         if ( wp_get_referer() )
  2387.             $html .= "</p><p><a href='" . esc_url( remove_query_arg( 'updated', wp_get_referer() ) ) . "'>" . __( 'Please try again.' ) . "</a>";
  2388.     }
  2389.  
  2390.     wp_die( $html, $title, array('response' => 403) );
  2391. }
  2392.  
  2393. /**
  2394.  * Kill WordPress execution and display HTML message with error message.
  2395.  *
  2396.  * This function complements the die() PHP function. The difference is that
  2397.  * HTML will be displayed to the user. It is recommended to use this function
  2398.  * only, when the execution should not continue any further. It is not
  2399.  * recommended to call this function very often and try to handle as many errors
  2400.  * as possible silently.
  2401.  *
  2402.  * @since 2.0.4
  2403.  *
  2404.  * @param string       $message Optional. Error message. Default empty.
  2405.  * @param string       $title   Optional. Error title. Default empty.
  2406.  * @param string|array $args    Optional. Arguments to control behavior. Default empty array.
  2407.  */
  2408. function wp_die( $message = '', $title = '', $args = array() ) {
  2409.     if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
  2410.         /**
  2411.          * Filter callback for killing WordPress execution for AJAX requests.
  2412.          *
  2413.          * @since 3.4.0
  2414.          *
  2415.          * @param callback $function Callback function name.
  2416.          */
  2417.         $function = apply_filters( 'wp_die_ajax_handler', '_ajax_wp_die_handler' );
  2418.     } elseif ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST ) {
  2419.         /**
  2420.          * Filter callback for killing WordPress execution for XML-RPC requests.
  2421.          *
  2422.          * @since 3.4.0
  2423.          *
  2424.          * @param callback $function Callback function name.
  2425.          */
  2426.         $function = apply_filters( 'wp_die_xmlrpc_handler', '_xmlrpc_wp_die_handler' );
  2427.     } else {
  2428.         /**
  2429.          * Filter callback for killing WordPress execution for all non-AJAX, non-XML-RPC requests.
  2430.          *
  2431.          * @since 3.0.0
  2432.          *
  2433.          * @param callback $function Callback function name.
  2434.          */
  2435.         $function = apply_filters( 'wp_die_handler', '_default_wp_die_handler' );
  2436.     }
  2437.  
  2438.     call_user_func( $function, $message, $title, $args );
  2439. }
  2440.  
  2441. /**
  2442.  * Kill WordPress execution and display HTML message with error message.
  2443.  *
  2444.  * This is the default handler for wp_die if you want a custom one for your
  2445.  * site then you can overload using the wp_die_handler filter in wp_die
  2446.  *
  2447.  * @since 3.0.0
  2448.  * @access private
  2449.  *
  2450.  * @param string       $message Error message.
  2451.  * @param string       $title   Optional. Error title. Default empty.
  2452.  * @param string|array $args    Optional. Arguments to control behavior. Default empty array.
  2453.  */
  2454. function _default_wp_die_handler( $message, $title = '', $args = array() ) {
  2455.     $defaults = array( 'response' => 500 );
  2456.     $r = wp_parse_args($args, $defaults);
  2457.  
  2458.     $have_gettext = function_exists('__');
  2459.  
  2460.     if ( function_exists( 'is_wp_error' ) && is_wp_error( $message ) ) {
  2461.         if ( empty( $title ) ) {
  2462.             $error_data = $message->get_error_data();
  2463.             if ( is_array( $error_data ) && isset( $error_data['title'] ) )
  2464.                 $title = $error_data['title'];
  2465.         }
  2466.         $errors = $message->get_error_messages();
  2467.         switch ( count( $errors ) ) {
  2468.         case 0 :
  2469.             $message = '';
  2470.             break;
  2471.         case 1 :
  2472.             $message = "<p>{$errors[0]}</p>";
  2473.             break;
  2474.         default :
  2475.             $message = "<ul>\n\t\t<li>" . join( "</li>\n\t\t<li>", $errors ) . "</li>\n\t</ul>";
  2476.             break;
  2477.         }
  2478.     } elseif ( is_string( $message ) ) {
  2479.         $message = "<p>$message</p>";
  2480.     }
  2481.  
  2482.     if ( isset( $r['back_link'] ) && $r['back_link'] ) {
  2483.         $back_text = $have_gettext? __('&laquo; Back') : '&laquo; Back';
  2484.         $message .= "\n<p><a href='javascript:history.back()'>$back_text</a></p>";
  2485.     }
  2486.  
  2487.     if ( ! did_action( 'admin_head' ) ) :
  2488.         if ( !headers_sent() ) {
  2489.             status_header( $r['response'] );
  2490.             nocache_headers();
  2491.             header( 'Content-Type: text/html; charset=utf-8' );
  2492.         }
  2493.  
  2494.         if ( empty($title) )
  2495.             $title = $have_gettext ? __('WordPress &rsaquo; Error') : 'WordPress &rsaquo; Error';
  2496.  
  2497.         $text_direction = 'ltr';
  2498.         if ( isset($r['text_direction']) && 'rtl' == $r['text_direction'] )
  2499.             $text_direction = 'rtl';
  2500.         elseif ( function_exists( 'is_rtl' ) && is_rtl() )
  2501.             $text_direction = 'rtl';
  2502. ?>
  2503. <!DOCTYPE html>
  2504. <!-- Ticket #11289, IE bug fix: always pad the error page with enough characters such that it is greater than 512 bytes, even after gzip compression abcdefghijklmnopqrstuvwxyz1234567890aabbccddeeffgghhiijjkkllmmnnooppqqrrssttuuvvwwxxyyzz11223344556677889900abacbcbdcdcededfefegfgfhghgihihjijikjkjlklkmlmlnmnmononpopoqpqprqrqsrsrtstsubcbcdcdedefefgfabcadefbghicjkldmnoepqrfstugvwxhyz1i234j567k890laabmbccnddeoeffpgghqhiirjjksklltmmnunoovppqwqrrxsstytuuzvvw0wxx1yyz2z113223434455666777889890091abc2def3ghi4jkl5mno6pqr7stu8vwx9yz11aab2bcc3dd4ee5ff6gg7hh8ii9j0jk1kl2lmm3nnoo4p5pq6qrr7ss8tt9uuvv0wwx1x2yyzz13aba4cbcb5dcdc6dedfef8egf9gfh0ghg1ihi2hji3jik4jkj5lkl6kml7mln8mnm9ono
  2505. -->
  2506. <html xmlns="http://www.w3.org/1999/xhtml" <?php if ( function_exists( 'language_attributes' ) && function_exists( 'is_rtl' ) ) language_attributes(); else echo "dir='$text_direction'"; ?>>
  2507. <head>
  2508.     <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  2509.     <title><?php echo $title ?></title>
  2510.     <style type="text/css">
  2511.         html {
  2512.             background: #f1f1f1;
  2513.         }
  2514.         body {
  2515.             background: #fff;
  2516.             color: #444;
  2517.             font-family: "Open Sans", sans-serif;
  2518.             margin: 2em auto;
  2519.             padding: 1em 2em;
  2520.             max-width: 700px;
  2521.             -webkit-box-shadow: 0 1px 3px rgba(0,0,0,0.13);
  2522.             box-shadow: 0 1px 3px rgba(0,0,0,0.13);
  2523.         }
  2524.         h1 {
  2525.             border-bottom: 1px solid #dadada;
  2526.             clear: both;
  2527.             color: #666;
  2528.             font: 24px "Open Sans", sans-serif;
  2529.             margin: 30px 0 0 0;
  2530.             padding: 0;
  2531.             padding-bottom: 7px;
  2532.         }
  2533.         #error-page {
  2534.             margin-top: 50px;
  2535.         }
  2536.         #error-page p {
  2537.             font-size: 14px;
  2538.             line-height: 1.5;
  2539.             margin: 25px 0 20px;
  2540.         }
  2541.         #error-page code {
  2542.             font-family: Consolas, Monaco, monospace;
  2543.         }
  2544.         ul li {
  2545.             margin-bottom: 10px;
  2546.             font-size: 14px ;
  2547.         }
  2548.         a {
  2549.             color: #21759B;
  2550.             text-decoration: none;
  2551.         }
  2552.         a:hover {
  2553.             color: #D54E21;
  2554.         }
  2555.         .button {
  2556.             background: #f7f7f7;
  2557.             border: 1px solid #cccccc;
  2558.             color: #555;
  2559.             display: inline-block;
  2560.             text-decoration: none;
  2561.             font-size: 13px;
  2562.             line-height: 26px;
  2563.             height: 28px;
  2564.             margin: 0;
  2565.             padding: 0 10px 1px;
  2566.             cursor: pointer;
  2567.             -webkit-border-radius: 3px;
  2568.             -webkit-appearance: none;
  2569.             border-radius: 3px;
  2570.             white-space: nowrap;
  2571.             -webkit-box-sizing: border-box;
  2572.             -moz-box-sizing:    border-box;
  2573.             box-sizing:         border-box;
  2574.  
  2575.             -webkit-box-shadow: inset 0 1px 0 #fff, 0 1px 0 rgba(0,0,0,.08);
  2576.             box-shadow: inset 0 1px 0 #fff, 0 1px 0 rgba(0,0,0,.08);
  2577.             vertical-align: top;
  2578.         }
  2579.  
  2580.         .button.button-large {
  2581.             height: 29px;
  2582.             line-height: 28px;
  2583.             padding: 0 12px;
  2584.         }
  2585.  
  2586.         .button:hover,
  2587.         .button:focus {
  2588.             background: #fafafa;
  2589.             border-color: #999;
  2590.             color: #222;
  2591.         }
  2592.  
  2593.         .button:focus  {
  2594.             -webkit-box-shadow: 1px 1px 1px rgba(0,0,0,.2);
  2595.             box-shadow: 1px 1px 1px rgba(0,0,0,.2);
  2596.         }
  2597.  
  2598.         .button:active {
  2599.             background: #eee;
  2600.             border-color: #999;
  2601.             color: #333;
  2602.             -webkit-box-shadow: inset 0 2px 5px -3px rgba( 0, 0, 0, 0.5 );
  2603.             box-shadow: inset 0 2px 5px -3px rgba( 0, 0, 0, 0.5 );
  2604.         }
  2605.  
  2606.         <?php if ( 'rtl' == $text_direction ) : ?>
  2607.         body { font-family: Tahoma, Arial; }
  2608.         <?php endif; ?>
  2609.     </style>
  2610. </head>
  2611. <body id="error-page">
  2612. <?php endif; // ! did_action( 'admin_head' ) ?>
  2613.     <?php echo $message; ?>
  2614. </body>
  2615. </html>
  2616. <?php
  2617.     die();
  2618. }
  2619.  
  2620. /**
  2621.  * Kill WordPress execution and display XML message with error message.
  2622.  *
  2623.  * This is the handler for wp_die when processing XMLRPC requests.
  2624.  *
  2625.  * @since 3.2.0
  2626.  * @access private
  2627.  *
  2628.  * @param string       $message Error message.
  2629.  * @param string       $title   Optional. Error title. Default empty.
  2630.  * @param string|array $args    Optional. Arguments to control behavior. Default empty array.
  2631.  */
  2632. function _xmlrpc_wp_die_handler( $message, $title = '', $args = array() ) {
  2633.     global $wp_xmlrpc_server;
  2634.     $defaults = array( 'response' => 500 );
  2635.  
  2636.     $r = wp_parse_args($args, $defaults);
  2637.  
  2638.     if ( $wp_xmlrpc_server ) {
  2639.         $error = new IXR_Error( $r['response'] , $message);
  2640.         $wp_xmlrpc_server->output( $error->getXml() );
  2641.     }
  2642.     die();
  2643. }
  2644.  
  2645. /**
  2646.  * Kill WordPress ajax execution.
  2647.  *
  2648.  * This is the handler for wp_die when processing Ajax requests.
  2649.  *
  2650.  * @since 3.4.0
  2651.  * @access private
  2652.  *
  2653.  * @param string $message Optional. Response to print. Default empty.
  2654.  */
  2655. function _ajax_wp_die_handler( $message = '' ) {
  2656.     if ( is_scalar( $message ) )
  2657.         die( (string) $message );
  2658.     die( '0' );
  2659. }
  2660.  
  2661. /**
  2662.  * Kill WordPress execution.
  2663.  *
  2664.  * This is the handler for wp_die when processing APP requests.
  2665.  *
  2666.  * @since 3.4.0
  2667.  * @access private
  2668.  *
  2669.  * @param string $message Optional. Response to print. Default empty.
  2670.  */
  2671. function _scalar_wp_die_handler( $message = '' ) {
  2672.     if ( is_scalar( $message ) )
  2673.         die( (string) $message );
  2674.     die();
  2675. }
  2676.  
  2677. /**
  2678.  * Send a JSON response back to an Ajax request.
  2679.  *
  2680.  * @since 3.5.0
  2681.  *
  2682.  * @param mixed $response Variable (usually an array or object) to encode as JSON,
  2683.  *                        then print and die.
  2684.  */
  2685. function wp_send_json( $response ) {
  2686.     @header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
  2687.     echo json_encode( $response );
  2688.     if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
  2689.         wp_die();
  2690.     else
  2691.         die;
  2692. }
  2693.  
  2694. /**
  2695.  * Send a JSON response back to an Ajax request, indicating success.
  2696.  *
  2697.  * @since 3.5.0
  2698.  *
  2699.  * @param mixed $data Data to encode as JSON, then print and die.
  2700.  */
  2701. function wp_send_json_success( $data = null ) {
  2702.     $response = array( 'success' => true );
  2703.  
  2704.     if ( isset( $data ) )
  2705.         $response['data'] = $data;
  2706.  
  2707.     wp_send_json( $response );
  2708. }
  2709.  
  2710. /**
  2711.  * Send a JSON response back to an Ajax request, indicating failure.
  2712.  *
  2713.  * @since 3.5.0
  2714.  *
  2715.  * @param mixed $data Data to encode as JSON, then print and die.
  2716.  */
  2717. function wp_send_json_error( $data = null ) {
  2718.     $response = array( 'success' => false );
  2719.  
  2720.     if ( isset( $data ) )
  2721.         $response['data'] = $data;
  2722.  
  2723.     wp_send_json( $response );
  2724. }
  2725.  
  2726. /**
  2727.  * Retrieve the WordPress home page URL.
  2728.  *
  2729.  * If the constant named 'WP_HOME' exists, then it will be used and returned
  2730.  * by the function. This can be used to counter the redirection on your local
  2731.  * development environment.
  2732.  *
  2733.  * @since 2.2.0
  2734.  * @access private
  2735.  *
  2736.  * @see WP_HOME
  2737.  *
  2738.  * @param string $url URL for the home location.
  2739.  * @return string Homepage location.
  2740.  */
  2741. function _config_wp_home( $url = '' ) {
  2742.     if ( defined( 'WP_HOME' ) )
  2743.         return untrailingslashit( WP_HOME );
  2744.     return $url;
  2745. }
  2746.  
  2747. /**
  2748.  * Retrieve the WordPress site URL.
  2749.  *
  2750.  * If the constant named 'WP_SITEURL' is defined, then the value in that
  2751.  * constant will always be returned. This can be used for debugging a site
  2752.  * on your localhost while not having to change the database to your URL.
  2753.  *
  2754.  * @since 2.2.0
  2755.  * @access private
  2756.  *
  2757.  * @see WP_SITEURL
  2758.  *
  2759.  * @param string $url URL to set the WordPress site location.
  2760.  * @return string The WordPress Site URL.
  2761.  */
  2762. function _config_wp_siteurl( $url = '' ) {
  2763.     if ( defined( 'WP_SITEURL' ) )
  2764.         return untrailingslashit( WP_SITEURL );
  2765.     return $url;
  2766. }
  2767.  
  2768. /**
  2769.  * Set the localized direction for MCE plugin.
  2770.  *
  2771.  * Will only set the direction to 'rtl', if the WordPress locale has
  2772.  * the text direction set to 'rtl'.
  2773.  *
  2774.  * Fills in the 'directionality' setting, enables the 'directionality'
  2775.  * plugin, and adds the 'ltr' button to 'toolbar1', formerly
  2776.  * 'theme_advanced_buttons1' array keys. These keys are then returned
  2777.  * in the $input (TinyMCE settings) array.
  2778.  *
  2779.  * @since 2.1.0
  2780.  * @access private
  2781.  *
  2782.  * @param array $input MCE settings array.
  2783.  * @return array Direction set for 'rtl', if needed by locale.
  2784.  */
  2785. function _mce_set_direction( $input ) {
  2786.     if ( is_rtl() ) {
  2787.         $input['directionality'] = 'rtl';
  2788.         $input['plugins'] .= ',directionality';
  2789.         $input['toolbar1'] .= ',ltr';
  2790.     }
  2791.  
  2792.     return $input;
  2793. }
  2794.  
  2795.  
  2796. /**
  2797.  * Convert smiley code to the icon graphic file equivalent.
  2798.  *
  2799.  * You can turn off smilies, by going to the write setting screen and unchecking
  2800.  * the box, or by setting 'use_smilies' option to false or removing the option.
  2801.  *
  2802.  * Plugins may override the default smiley list by setting the $wpsmiliestrans
  2803.  * to an array, with the key the code the blogger types in and the value the
  2804.  * image file.
  2805.  *
  2806.  * The $wp_smiliessearch global is for the regular expression and is set each
  2807.  * time the function is called.
  2808.  *
  2809.  * The full list of smilies can be found in the function and won't be listed in
  2810.  * the description. Probably should create a Codex page for it, so that it is
  2811.  * available.
  2812.  *
  2813.  * @global array $wpsmiliestrans
  2814.  * @global array $wp_smiliessearch
  2815.  *
  2816.  * @since 2.2.0
  2817.  */
  2818. function smilies_init() {
  2819.     global $wpsmiliestrans, $wp_smiliessearch;
  2820.  
  2821.     // don't bother setting up smilies if they are disabled
  2822.     if ( !get_option( 'use_smilies' ) )
  2823.         return;
  2824.  
  2825.     if ( !isset( $wpsmiliestrans ) ) {
  2826.         $wpsmiliestrans = array(
  2827.         ':mrgreen:' => 'icon_mrgreen.gif',
  2828.         ':neutral:' => 'icon_neutral.gif',
  2829.         ':twisted:' => 'icon_twisted.gif',
  2830.           ':arrow:' => 'icon_arrow.gif',
  2831.           ':shock:' => 'icon_eek.gif',
  2832.           ':smile:' => 'icon_smile.gif',
  2833.             ':???:' => 'icon_confused.gif',
  2834.            ':cool:' => 'icon_cool.gif',
  2835.            ':evil:' => 'icon_evil.gif',
  2836.            ':grin:' => 'icon_biggrin.gif',
  2837.            ':idea:' => 'icon_idea.gif',
  2838.            ':oops:' => 'icon_redface.gif',
  2839.            ':razz:' => 'icon_razz.gif',
  2840.            ':roll:' => 'icon_rolleyes.gif',
  2841.            ':wink:' => 'icon_wink.gif',
  2842.             ':cry:' => 'icon_cry.gif',
  2843.             ':eek:' => 'icon_surprised.gif',
  2844.             ':lol:' => 'icon_lol.gif',
  2845.             ':mad:' => 'icon_mad.gif',
  2846.             ':sad:' => 'icon_sad.gif',
  2847.               '8-)' => 'icon_cool.gif',
  2848.               '8-O' => 'icon_eek.gif',
  2849.               ':-(' => 'icon_sad.gif',
  2850.               ':-)' => 'icon_smile.gif',
  2851.               ':-?' => 'icon_confused.gif',
  2852.               ':-D' => 'icon_biggrin.gif',
  2853.               ':-P' => 'icon_razz.gif',
  2854.               ':-o' => 'icon_surprised.gif',
  2855.               ':-x' => 'icon_mad.gif',
  2856.               ':-|' => 'icon_neutral.gif',
  2857.               ';-)' => 'icon_wink.gif',
  2858.         // This one transformation breaks regular text with frequency.
  2859.         //     '8)' => 'icon_cool.gif',
  2860.                '8O' => 'icon_eek.gif',
  2861.                ':(' => 'icon_sad.gif',
  2862.                ':)' => 'icon_smile.gif',
  2863.                ':?' => 'icon_confused.gif',
  2864.                ':D' => 'icon_biggrin.gif',
  2865.                ':P' => 'icon_razz.gif',
  2866.                ':o' => 'icon_surprised.gif',
  2867.                ':x' => 'icon_mad.gif',
  2868.                ':|' => 'icon_neutral.gif',
  2869.                ';)' => 'icon_wink.gif',
  2870.               ':!:' => 'icon_exclaim.gif',
  2871.               ':?:' => 'icon_question.gif',
  2872.         );
  2873.     }
  2874.  
  2875.     if (count($wpsmiliestrans) == 0) {
  2876.         return;
  2877.     }
  2878.  
  2879.     /*
  2880.      * NOTE: we sort the smilies in reverse key order. This is to make sure
  2881.      * we match the longest possible smilie (:???: vs :?) as the regular
  2882.      * expression used below is first-match
  2883.      */
  2884.     krsort($wpsmiliestrans);
  2885.  
  2886.     $spaces = wp_spaces_regexp();
  2887.  
  2888.     // Begin first "subpattern"
  2889.     $wp_smiliessearch = '/(?<=' . $spaces . '|^)';
  2890.  
  2891.     $subchar = '';
  2892.     foreach ( (array) $wpsmiliestrans as $smiley => $img ) {
  2893.         $firstchar = substr($smiley, 0, 1);
  2894.         $rest = substr($smiley, 1);
  2895.  
  2896.         // new subpattern?
  2897.         if ($firstchar != $subchar) {
  2898.             if ($subchar != '') {
  2899.                 $wp_smiliessearch .= ')(?=' . $spaces . '|$)';  // End previous "subpattern"
  2900.                 $wp_smiliessearch .= '|(?<=' . $spaces . '|^)'; // Begin another "subpattern"
  2901.             }
  2902.             $subchar = $firstchar;
  2903.             $wp_smiliessearch .= preg_quote($firstchar, '/') . '(?:';
  2904.         } else {
  2905.             $wp_smiliessearch .= '|';
  2906.         }
  2907.         $wp_smiliessearch .= preg_quote($rest, '/');
  2908.     }
  2909.  
  2910.     $wp_smiliessearch .= ')(?=' . $spaces . '|$)/m';
  2911.  
  2912. }
  2913.  
  2914. /**
  2915.  * Merge user defined arguments into defaults array.
  2916.  *
  2917.  * This function is used throughout WordPress to allow for both string or array
  2918.  * to be merged into another array.
  2919.  *
  2920.  * @since 2.2.0
  2921.  *
  2922.  * @param string|array $args     Value to merge with $defaults
  2923.  * @param array        $defaults Optional. Array that serves as the defaults. Default empty.
  2924.  * @return array Merged user defined values with defaults.
  2925.  */
  2926. function wp_parse_args( $args, $defaults = '' ) {
  2927.     if ( is_object( $args ) )
  2928.         $r = get_object_vars( $args );
  2929.     elseif ( is_array( $args ) )
  2930.         $r =& $args;
  2931.     else
  2932.         wp_parse_str( $args, $r );
  2933.  
  2934.     if ( is_array( $defaults ) )
  2935.         return array_merge( $defaults, $r );
  2936.     return $r;
  2937. }
  2938.  
  2939. /**
  2940.  * Clean up an array, comma- or space-separated list of IDs.
  2941.  *
  2942.  * @since 3.0.0
  2943.  *
  2944.  * @param array|string $list List of ids.
  2945.  * @return array Sanitized array of IDs.
  2946.  */
  2947. function wp_parse_id_list( $list ) {
  2948.     if ( !is_array($list) )
  2949.         $list = preg_split('/[\s,]+/', $list);
  2950.  
  2951.     return array_unique(array_map('absint', $list));
  2952. }
  2953.  
  2954. /**
  2955.  * Extract a slice of an array, given a list of keys.
  2956.  *
  2957.  * @since 3.1.0
  2958.  *
  2959.  * @param array $array The original array.
  2960.  * @param array $keys  The list of keys.
  2961.  * @return array The array slice.
  2962.  */
  2963. function wp_array_slice_assoc( $array, $keys ) {
  2964.     $slice = array();
  2965.     foreach ( $keys as $key )
  2966.         if ( isset( $array[ $key ] ) )
  2967.             $slice[ $key ] = $array[ $key ];
  2968.  
  2969.     return $slice;
  2970. }
  2971.  
  2972. /**
  2973.  * Filters a list of objects, based on a set of key => value arguments.
  2974.  *
  2975.  * @since 3.0.0
  2976.  *
  2977.  * @param array       $list     An array of objects to filter
  2978.  * @param array       $args     Optional. An array of key => value arguments to match
  2979.  *                              against each object. Default empty array.
  2980.  * @param string      $operator Optional. The logical operation to perform. 'or' means
  2981.  *                              only one element from the array needs to match; 'and'
  2982.  *                              means all elements must match. Default 'and'.
  2983.  * @param bool|string $field    A field from the object to place instead of the entire object.
  2984.  *                              Default false.
  2985.  * @return array A list of objects or object fields.
  2986.  */
  2987. function wp_filter_object_list( $list, $args = array(), $operator = 'and', $field = false ) {
  2988.     if ( ! is_array( $list ) )
  2989.         return array();
  2990.  
  2991.     $list = wp_list_filter( $list, $args, $operator );
  2992.  
  2993.     if ( $field )
  2994.         $list = wp_list_pluck( $list, $field );
  2995.  
  2996.     return $list;
  2997. }
  2998.  
  2999. /**
  3000.  * Filters a list of objects, based on a set of key => value arguments.
  3001.  *
  3002.  * @since 3.1.0
  3003.  *
  3004.  * @param array  $list     An array of objects to filter.
  3005.  * @param array  $args     Optional. An array of key => value arguments to match
  3006.  *                         against each object. Default empty array.
  3007.  * @param string $operator Optional. The logical operation to perform. 'AND' means
  3008.  *                         all elements from the array must match. 'OR' means only
  3009.  *                         one element needs to match. 'NOT' means no elements may
  3010.  *                         match. Default 'AND'.
  3011.  * @return array Array of found values.
  3012.  */
  3013. function wp_list_filter( $list, $args = array(), $operator = 'AND' ) {
  3014.     if ( ! is_array( $list ) )
  3015.         return array();
  3016.  
  3017.     if ( empty( $args ) )
  3018.         return $list;
  3019.  
  3020.     $operator = strtoupper( $operator );
  3021.     $count = count( $args );
  3022.     $filtered = array();
  3023.  
  3024.     foreach ( $list as $key => $obj ) {
  3025.         $to_match = (array) $obj;
  3026.  
  3027.         $matched = 0;
  3028.         foreach ( $args as $m_key => $m_value ) {
  3029.             if ( array_key_exists( $m_key, $to_match ) && $m_value == $to_match[ $m_key ] )
  3030.                 $matched++;
  3031.         }
  3032.  
  3033.         if ( ( 'AND' == $operator && $matched == $count )
  3034.           || ( 'OR' == $operator && $matched > 0 )
  3035.           || ( 'NOT' == $operator && 0 == $matched ) ) {
  3036.             $filtered[$key] = $obj;
  3037.         }
  3038.     }
  3039.  
  3040.     return $filtered;
  3041. }
  3042.  
  3043. /**
  3044.  * Pluck a certain field out of each object in a list.
  3045.  *
  3046.  * This has the same functionality and prototype of
  3047.  * array_column() (PHP 5.5) but also supports objects.
  3048.  *
  3049.  * @since 3.1.0
  3050.  * @since 4.0.0 $index_key parameter added.
  3051.  *
  3052.  * @param array      $list      List of objects or arrays
  3053.  * @param int|string $field     Field from the object to place instead of the entire object
  3054.  * @param int|string $index_key Optional. Field from the object to use as keys for the new array.
  3055.  *                              Default null.
  3056.  * @return array Array of found values. If $index_key is set, an array of found values with keys
  3057.  *               corresponding to $index_key.
  3058.  */
  3059. function wp_list_pluck( $list, $field, $index_key = null ) {
  3060.     if ( ! $index_key ) {
  3061.         /*
  3062.          * This is simple. Could at some point wrap array_column()
  3063.          * if we knew we had an array of arrays.
  3064.          */
  3065.         foreach ( $list as $key => $value ) {
  3066.             if ( is_object( $value ) ) {
  3067.                 $list[ $key ] = $value->$field;
  3068.             } else {
  3069.                 $list[ $key ] = $value[ $field ];
  3070.             }
  3071.         }
  3072.         return $list;
  3073.     }
  3074.  
  3075.     /*
  3076.      * When index_key is not set for a particular item, push the value
  3077.      * to the end of the stack. This is how array_column() behaves.
  3078.      */
  3079.     $newlist = array();
  3080.     foreach ( $list as $value ) {
  3081.         if ( is_object( $value ) ) {
  3082.             if ( isset( $value->$index_key ) ) {
  3083.                 $newlist[ $value->$index_key ] = $value->$field;
  3084.             } else {
  3085.                 $newlist[] = $value->$field;
  3086.             }
  3087.         } else {
  3088.             if ( isset( $value[ $index_key ] ) ) {
  3089.                 $newlist[ $value[ $index_key ] ] = $value[ $field ];
  3090.             } else {
  3091.                 $newlist[] = $value[ $field ];
  3092.             }
  3093.         }
  3094.     }
  3095.  
  3096.     return $newlist;
  3097. }
  3098.  
  3099. /**
  3100.  * Determines if Widgets library should be loaded.
  3101.  *
  3102.  * Checks to make sure that the widgets library hasn't already been loaded.
  3103.  * If it hasn't, then it will load the widgets library and run an action hook.
  3104.  *
  3105.  * @since 2.2.0
  3106.  */
  3107. function wp_maybe_load_widgets() {
  3108.     /**
  3109.      * Filter whether to load the Widgets library.
  3110.      *
  3111.      * Passing a falsey value to the filter will effectively short-circuit
  3112.      * the Widgets library from loading.
  3113.      *
  3114.      * @since 2.8.0
  3115.      *
  3116.      * @param bool $wp_maybe_load_widgets Whether to load the Widgets library.
  3117.      *                                    Default true.
  3118.      */
  3119.     if ( ! apply_filters( 'load_default_widgets', true ) ) {
  3120.         return;
  3121.     }
  3122.  
  3123.     require_once( ABSPATH . WPINC . '/default-widgets.php' );
  3124.  
  3125.     add_action( '_admin_menu', 'wp_widgets_add_menu' );
  3126. }
  3127.  
  3128. /**
  3129.  * Append the Widgets menu to the themes main menu.
  3130.  *
  3131.  * @since 2.2.0
  3132.  *
  3133.  * @uses $submenu The administration submenu list.
  3134.  */
  3135. function wp_widgets_add_menu() {
  3136.     global $submenu;
  3137.  
  3138.     if ( ! current_theme_supports( 'widgets' ) )
  3139.         return;
  3140.  
  3141.     $submenu['themes.php'][7] = array( __( 'Widgets' ), 'edit_theme_options', 'widgets.php' );
  3142.     ksort( $submenu['themes.php'], SORT_NUMERIC );
  3143. }
  3144.  
  3145. /**
  3146.  * Flush all output buffers for PHP 5.2.
  3147.  *
  3148.  * Make sure all output buffers are flushed before our singletons are destroyed.
  3149.  *
  3150.  * @since 2.2.0
  3151.  */
  3152. function wp_ob_end_flush_all() {
  3153.     $levels = ob_get_level();
  3154.     for ($i=0; $i<$levels; $i++)
  3155.         ob_end_flush();
  3156. }
  3157.  
  3158. /**
  3159.  * Load custom DB error or display WordPress DB error.
  3160.  *
  3161.  * If a file exists in the wp-content directory named db-error.php, then it will
  3162.  * be loaded instead of displaying the WordPress DB error. If it is not found,
  3163.  * then the WordPress DB error will be displayed instead.
  3164.  *
  3165.  * The WordPress DB error sets the HTTP status header to 500 to try to prevent
  3166.  * search engines from caching the message. Custom DB messages should do the
  3167.  * same.
  3168.  *
  3169.  * This function was backported to WordPress 2.3.2, but originally was added
  3170.  * in WordPress 2.5.0.
  3171.  *
  3172.  * @since 2.3.2
  3173.  *
  3174.  * @global wpdb $wpdb WordPress database access abstraction object.
  3175.  */
  3176. function dead_db() {
  3177.     global $wpdb;
  3178.  
  3179.     wp_load_translations_early();
  3180.  
  3181.     // Load custom DB error template, if present.
  3182.     if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
  3183.         require_once( WP_CONTENT_DIR . '/db-error.php' );
  3184.         die();
  3185.     }
  3186.  
  3187.     // If installing or in the admin, provide the verbose message.
  3188.     if ( defined('WP_INSTALLING') || defined('WP_ADMIN') )
  3189.         wp_die($wpdb->error);
  3190.  
  3191.     // Otherwise, be terse.
  3192.     status_header( 500 );
  3193.     nocache_headers();
  3194.     header( 'Content-Type: text/html; charset=utf-8' );
  3195. ?>
  3196. <!DOCTYPE html>
  3197. <html xmlns="http://www.w3.org/1999/xhtml"<?php if ( is_rtl() ) echo ' dir="rtl"'; ?>>
  3198. <head>
  3199. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  3200.     <title><?php _e( 'Database Error' ); ?></title>
  3201.  
  3202. </head>
  3203. <body>
  3204.     <h1><?php _e( 'Error establishing a database connection' ); ?></h1>
  3205. </body>
  3206. </html>
  3207. <?php
  3208.     die();
  3209. }
  3210.  
  3211. /**
  3212.  * Convert a value to non-negative integer.
  3213.  *
  3214.  * @since 2.5.0
  3215.  *
  3216.  * @param mixed $maybeint Data you wish to have converted to a non-negative integer.
  3217.  * @return int A non-negative integer.
  3218.  */
  3219. function absint( $maybeint ) {
  3220.     return abs( intval( $maybeint ) );
  3221. }
  3222.  
  3223. /**
  3224.  * Mark a function as deprecated and inform when it has been used.
  3225.  *
  3226.  * There is a hook deprecated_function_run that will be called that can be used
  3227.  * to get the backtrace up to what file and function called the deprecated
  3228.  * function.
  3229.  *
  3230.  * The current behavior is to trigger a user error if WP_DEBUG is true.
  3231.  *
  3232.  * This function is to be used in every function that is deprecated.
  3233.  *
  3234.  * @since 2.5.0
  3235.  * @access private
  3236.  *
  3237.  * @param string $function    The function that was called.
  3238.  * @param string $version     The version of WordPress that deprecated the function.
  3239.  * @param string $replacement Optional. The function that should have been called. Default null.
  3240.  */
  3241. function _deprecated_function( $function, $version, $replacement = null ) {
  3242.  
  3243.     /**
  3244.      * Fires when a deprecated function is called.
  3245.      *
  3246.      * @since 2.5.0
  3247.      *
  3248.      * @param string $function    The function that was called.
  3249.      * @param string $replacement The function that should have been called.
  3250.      * @param string $version     The version of WordPress that deprecated the function.
  3251.      */
  3252.     do_action( 'deprecated_function_run', $function, $replacement, $version );
  3253.  
  3254.     /**
  3255.      * Filter whether to trigger an error for deprecated functions.
  3256.      *
  3257.      * @since 2.5.0
  3258.      *
  3259.      * @param bool $trigger Whether to trigger the error for deprecated functions. Default true.
  3260.      */
  3261.     if ( WP_DEBUG && apply_filters( 'deprecated_function_trigger_error', true ) ) {
  3262.         if ( function_exists( '__' ) ) {
  3263.             if ( ! is_null( $replacement ) )
  3264.                 trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $function, $version, $replacement ) );
  3265.             else
  3266.                 trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $function, $version ) );
  3267.         } else {
  3268.             if ( ! is_null( $replacement ) )
  3269.                 trigger_error( sprintf( '%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.', $function, $version, $replacement ) );
  3270.             else
  3271.                 trigger_error( sprintf( '%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.', $function, $version ) );
  3272.         }
  3273.     }
  3274. }
  3275.  
  3276. /**
  3277.  * Mark a file as deprecated and inform when it has been used.
  3278.  *
  3279.  * There is a hook deprecated_file_included that will be called that can be used
  3280.  * to get the backtrace up to what file and function included the deprecated
  3281.  * file.
  3282.  *
  3283.  * The current behavior is to trigger a user error if WP_DEBUG is true.
  3284.  *
  3285.  * This function is to be used in every file that is deprecated.
  3286.  *
  3287.  * @since 2.5.0
  3288.  * @access private
  3289.  *
  3290.  * @param string $file        The file that was included.
  3291.  * @param string $version     The version of WordPress that deprecated the file.
  3292.  * @param string $replacement Optional. The file that should have been included based on ABSPATH.
  3293.  *                            Default null.
  3294.  * @param string $message     Optional. A message regarding the change. Default empty.
  3295.  */
  3296. function _deprecated_file( $file, $version, $replacement = null, $message = '' ) {
  3297.  
  3298.     /**
  3299.      * Fires when a deprecated file is called.
  3300.      *
  3301.      * @since 2.5.0
  3302.      *
  3303.      * @param string $file        The file that was called.
  3304.      * @param string $replacement The file that should have been included based on ABSPATH.
  3305.      * @param string $version     The version of WordPress that deprecated the file.
  3306.      * @param string $message     A message regarding the change.
  3307.      */
  3308.     do_action( 'deprecated_file_included', $file, $replacement, $version, $message );
  3309.  
  3310.     /**
  3311.      * Filter whether to trigger an error for deprecated files.
  3312.      *
  3313.      * @since 2.5.0
  3314.      *
  3315.      * @param bool $trigger Whether to trigger the error for deprecated files. Default true.
  3316.      */
  3317.     if ( WP_DEBUG && apply_filters( 'deprecated_file_trigger_error', true ) ) {
  3318.         $message = empty( $message ) ? '' : ' ' . $message;
  3319.         if ( function_exists( '__' ) ) {
  3320.             if ( ! is_null( $replacement ) )
  3321.                 trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.'), $file, $version, $replacement ) . $message );
  3322.             else
  3323.                 trigger_error( sprintf( __('%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.'), $file, $version ) . $message );
  3324.         } else {
  3325.             if ( ! is_null( $replacement ) )
  3326.                 trigger_error( sprintf( '%1$s is <strong>deprecated</strong> since version %2$s! Use %3$s instead.', $file, $version, $replacement ) . $message );
  3327.             else
  3328.                 trigger_error( sprintf( '%1$s is <strong>deprecated</strong> since version %2$s with no alternative available.', $file, $version ) . $message );
  3329.         }
  3330.     }
  3331. }
  3332. /**
  3333.  * Mark a function argument as deprecated and inform when it has been used.
  3334.  *
  3335.  * This function is to be used whenever a deprecated function argument is used.
  3336.  * Before this function is called, the argument must be checked for whether it was
  3337.  * used by comparing it to its default value or evaluating whether it is empty.
  3338.  * For example:
  3339.  * <code>
  3340.  * if ( ! empty( $deprecated ) ) {
  3341.  *  _deprecated_argument( __FUNCTION__, '3.0' );
  3342.  * }
  3343.  * </code>
  3344.  *
  3345.  * There is a hook deprecated_argument_run that will be called that can be used
  3346.  * to get the backtrace up to what file and function used the deprecated
  3347.  * argument.
  3348.  *
  3349.  * The current behavior is to trigger a user error if WP_DEBUG is true.
  3350.  *
  3351.  * @since 3.0.0
  3352.  * @access private
  3353.  *
  3354.  * @param string $function The function that was called.
  3355.  * @param string $version  The version of WordPress that deprecated the argument used.
  3356.  * @param string $message  Optional. A message regarding the change. Default null.
  3357.  */
  3358. function _deprecated_argument( $function, $version, $message = null ) {
  3359.  
  3360.     /**
  3361.      * Fires when a deprecated argument is called.
  3362.      *
  3363.      * @since 3.0.0
  3364.      *
  3365.      * @param string $function The function that was called.
  3366.      * @param string $message  A message regarding the change.
  3367.      * @param string $version  The version of WordPress that deprecated the argument used.
  3368.      */
  3369.     do_action( 'deprecated_argument_run', $function, $message, $version );
  3370.  
  3371.     /**
  3372.      * Filter whether to trigger an error for deprecated arguments.
  3373.      *
  3374.      * @since 3.0.0
  3375.      *
  3376.      * @param bool $trigger Whether to trigger the error for deprecated arguments. Default true.
  3377.      */
  3378.     if ( WP_DEBUG && apply_filters( 'deprecated_argument_trigger_error', true ) ) {
  3379.         if ( function_exists( '__' ) ) {
  3380.             if ( ! is_null( $message ) )
  3381.                 trigger_error( sprintf( __('%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s! %3$s'), $function, $version, $message ) );
  3382.             else
  3383.                 trigger_error( sprintf( __('%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s with no alternative available.'), $function, $version ) );
  3384.         } else {
  3385.             if ( ! is_null( $message ) )
  3386.                 trigger_error( sprintf( '%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s! %3$s', $function, $version, $message ) );
  3387.             else
  3388.                 trigger_error( sprintf( '%1$s was called with an argument that is <strong>deprecated</strong> since version %2$s with no alternative available.', $function, $version ) );
  3389.         }
  3390.     }
  3391. }
  3392.  
  3393. /**
  3394.  * Mark something as being incorrectly called.
  3395.  *
  3396.  * There is a hook doing_it_wrong_run that will be called that can be used
  3397.  * to get the backtrace up to what file and function called the deprecated
  3398.  * function.
  3399.  *
  3400.  * The current behavior is to trigger a user error if WP_DEBUG is true.
  3401.  *
  3402.  * @since 3.1.0
  3403.  * @access private
  3404.  *
  3405.  * @param string $function The function that was called.
  3406.  * @param string $message  A message explaining what has been done incorrectly.
  3407.  * @param string $version  The version of WordPress where the message was added.
  3408.  */
  3409. function _doing_it_wrong( $function, $message, $version ) {
  3410.  
  3411.     /**
  3412.      * Fires when the given function is being used incorrectly.
  3413.      *
  3414.      * @since 3.1.0
  3415.      *
  3416.      * @param string $function The function that was called.
  3417.      * @param string $message  A message explaining what has been done incorrectly.
  3418.      * @param string $version  The version of WordPress where the message was added.
  3419.      */
  3420.     do_action( 'doing_it_wrong_run', $function, $message, $version );
  3421.  
  3422.     /**
  3423.      * Filter whether to trigger an error for _doing_it_wrong() calls.
  3424.      *
  3425.      * @since 3.1.0
  3426.      *
  3427.      * @param bool $trigger Whether to trigger the error for _doing_it_wrong() calls. Default true.
  3428.      */
  3429.     if ( WP_DEBUG && apply_filters( 'doing_it_wrong_trigger_error', true ) ) {
  3430.         if ( function_exists( '__' ) ) {
  3431.             $version = is_null( $version ) ? '' : sprintf( __( '(This message was added in version %s.)' ), $version );
  3432.             $message .= ' ' . __( 'Please see <a href="http://codex.wordpress.org/Debugging_in_WordPress">Debugging in WordPress</a> for more information.' );
  3433.             trigger_error( sprintf( __( '%1$s was called <strong>incorrectly</strong>. %2$s %3$s' ), $function, $message, $version ) );
  3434.         } else {
  3435.             $version = is_null( $version ) ? '' : sprintf( '(This message was added in version %s.)', $version );
  3436.             $message .= ' Please see <a href="http://codex.wordpress.org/Debugging_in_WordPress">Debugging in WordPress</a> for more information.';
  3437.             trigger_error( sprintf( '%1$s was called <strong>incorrectly</strong>. %2$s %3$s', $function, $message, $version ) );
  3438.         }
  3439.     }
  3440. }
  3441.  
  3442. /**
  3443.  * Is the server running earlier than 1.5.0 version of lighttpd?
  3444.  *
  3445.  * @since 2.5.0
  3446.  *
  3447.  * @return bool Whether the server is running lighttpd < 1.5.0.
  3448.  */
  3449. function is_lighttpd_before_150() {
  3450.     $server_parts = explode( '/', isset( $_SERVER['SERVER_SOFTWARE'] )? $_SERVER['SERVER_SOFTWARE'] : '' );
  3451.     $server_parts[1] = isset( $server_parts[1] )? $server_parts[1] : '';
  3452.     return  'lighttpd' == $server_parts[0] && -1 == version_compare( $server_parts[1], '1.5.0' );
  3453. }
  3454.  
  3455. /**
  3456.  * Does the specified module exist in the Apache config?
  3457.  *
  3458.  * @since 2.5.0
  3459.  *
  3460.  * @param string $mod     The module, e.g. mod_rewrite.
  3461.  * @param bool   $default Optional. The default return value if the module is not found. Default false.
  3462.  * @return bool Whether the specified module is loaded.
  3463.  */
  3464. function apache_mod_loaded($mod, $default = false) {
  3465.     global $is_apache;
  3466.  
  3467.     if ( !$is_apache )
  3468.         return false;
  3469.  
  3470.     if ( function_exists( 'apache_get_modules' ) ) {
  3471.         $mods = apache_get_modules();
  3472.         if ( in_array($mod, $mods) )
  3473.             return true;
  3474.     } elseif ( function_exists( 'phpinfo' ) && false === strpos( ini_get( 'disable_functions' ), 'phpinfo' ) ) {
  3475.             ob_start();
  3476.             phpinfo(8);
  3477.             $phpinfo = ob_get_clean();
  3478.             if ( false !== strpos($phpinfo, $mod) )
  3479.                 return true;
  3480.     }
  3481.     return $default;
  3482. }
  3483.  
  3484. /**
  3485.  * Check if IIS 7+ supports pretty permalinks.
  3486.  *
  3487.  * @since 2.8.0
  3488.  *
  3489.  * @return bool Whether IIS7 supports permalinks.
  3490.  */
  3491. function iis7_supports_permalinks() {
  3492.     global $is_iis7;
  3493.  
  3494.     $supports_permalinks = false;
  3495.     if ( $is_iis7 ) {
  3496.         /* First we check if the DOMDocument class exists. If it does not exist, then we cannot
  3497.          * easily update the xml configuration file, hence we just bail out and tell user that
  3498.          * pretty permalinks cannot be used.
  3499.          *
  3500.          * Next we check if the URL Rewrite Module 1.1 is loaded and enabled for the web site. When
  3501.          * URL Rewrite 1.1 is loaded it always sets a server variable called 'IIS_UrlRewriteModule'.
  3502.          * Lastly we make sure that PHP is running via FastCGI. This is important because if it runs
  3503.          * via ISAPI then pretty permalinks will not work.
  3504.          */
  3505.         $supports_permalinks = class_exists('DOMDocument') && isset($_SERVER['IIS_UrlRewriteModule']) && ( php_sapi_name() == 'cgi-fcgi' );
  3506.     }
  3507.  
  3508.     /**
  3509.      * Filter whether IIS 7+ supports pretty permalinks.
  3510.      *
  3511.      * @since 2.8.0
  3512.      *
  3513.      * @param bool $supports_permalinks Whether IIS7 supports permalinks. Default false.
  3514.      */
  3515.     return apply_filters( 'iis7_supports_permalinks', $supports_permalinks );
  3516. }
  3517.  
  3518. /**
  3519.  * File validates against allowed set of defined rules.
  3520.  *
  3521.  * A return value of '1' means that the $file contains either '..' or './'. A
  3522.  * return value of '2' means that the $file contains ':' after the first
  3523.  * character. A return value of '3' means that the file is not in the allowed
  3524.  * files list.
  3525.  *
  3526.  * @since 1.2.0
  3527.  *
  3528.  * @param string $file File path.
  3529.  * @param array $allowed_files List of allowed files.
  3530.  * @return int 0 means nothing is wrong, greater than 0 means something was wrong.
  3531.  */
  3532. function validate_file( $file, $allowed_files = '' ) {
  3533.     if ( false !== strpos( $file, '..' ) )
  3534.         return 1;
  3535.  
  3536.     if ( false !== strpos( $file, './' ) )
  3537.         return 1;
  3538.  
  3539.     if ( ! empty( $allowed_files ) && ! in_array( $file, $allowed_files ) )
  3540.         return 3;
  3541.  
  3542.     if (':' == substr( $file, 1, 1 ) )
  3543.         return 2;
  3544.  
  3545.     return 0;
  3546. }
  3547.  
  3548. /**
  3549.  * Determine if SSL is used.
  3550.  *
  3551.  * @since 2.6.0
  3552.  *
  3553.  * @return bool True if SSL, false if not used.
  3554.  */
  3555. function is_ssl() {
  3556.     if ( isset($_SERVER['HTTPS']) ) {
  3557.         if ( 'on' == strtolower($_SERVER['HTTPS']) )
  3558.             return true;
  3559.         if ( '1' == $_SERVER['HTTPS'] )
  3560.             return true;
  3561.     } elseif ( isset($_SERVER['SERVER_PORT']) && ( '443' == $_SERVER['SERVER_PORT'] ) ) {
  3562.         return true;
  3563.     }
  3564.     return false;
  3565. }
  3566.  
  3567. /**
  3568.  * Whether SSL login should be forced.
  3569.  *
  3570.  * @since 2.6.0
  3571.  *
  3572.  * @see force_ssl_admin()
  3573.  *
  3574.  * @param string|bool $force Optional Whether to force SSL login. Default null.
  3575.  * @return bool True if forced, false if not forced.
  3576.  */
  3577. function force_ssl_login( $force = null ) {
  3578.     return force_ssl_admin( $force );
  3579. }
  3580.  
  3581. /**
  3582.  * Whether to force SSL used for the Administration Screens.
  3583.  *
  3584.  * @since 2.6.0
  3585.  *
  3586.  * @param string|bool $force Optional. Whether to force SSL in admin screens. Default null.
  3587.  * @return bool True if forced, false if not forced.
  3588.  */
  3589. function force_ssl_admin( $force = null ) {
  3590.     static $forced = false;
  3591.  
  3592.     if ( !is_null( $force ) ) {
  3593.         $old_forced = $forced;
  3594.         $forced = $force;
  3595.         return $old_forced;
  3596.     }
  3597.  
  3598.     return $forced;
  3599. }
  3600.  
  3601. /**
  3602.  * Guess the URL for the site.
  3603.  *
  3604.  * Will remove wp-admin links to retrieve only return URLs not in the wp-admin
  3605.  * directory.
  3606.  *
  3607.  * @since 2.6.0
  3608.  *
  3609.  * @return string The guessed URL.
  3610.  */
  3611. function wp_guess_url() {
  3612.     if ( defined('WP_SITEURL') && '' != WP_SITEURL ) {
  3613.         $url = WP_SITEURL;
  3614.     } else {
  3615.         $abspath_fix = str_replace( '\\', '/', ABSPATH );
  3616.         $script_filename_dir = dirname( $_SERVER['SCRIPT_FILENAME'] );
  3617.  
  3618.         // The request is for the admin
  3619.         if ( strpos( $_SERVER['REQUEST_URI'], 'wp-admin' ) !== false || strpos( $_SERVER['REQUEST_URI'], 'wp-login.php' ) !== false ) {
  3620.             $path = preg_replace( '#/(wp-admin/.*|wp-login.php)#i', '', $_SERVER['REQUEST_URI'] );
  3621.  
  3622.         // The request is for a file in ABSPATH
  3623.         } elseif ( $script_filename_dir . '/' == $abspath_fix ) {
  3624.             // Strip off any file/query params in the path
  3625.             $path = preg_replace( '#/[^/]*$#i', '', $_SERVER['PHP_SELF'] );
  3626.  
  3627.         } else {
  3628.             if ( false !== strpos( $_SERVER['SCRIPT_FILENAME'], $abspath_fix ) ) {
  3629.                 // Request is hitting a file inside ABSPATH
  3630.                 $directory = str_replace( ABSPATH, '', $script_filename_dir );
  3631.                 // Strip off the sub directory, and any file/query paramss
  3632.                 $path = preg_replace( '#/' . preg_quote( $directory, '#' ) . '/[^/]*$#i', '' , $_SERVER['REQUEST_URI'] );
  3633.             } elseif ( false !== strpos( $abspath_fix, $script_filename_dir ) ) {
  3634.                 // Request is hitting a file above ABSPATH
  3635.                 $subdirectory = substr( $abspath_fix, strpos( $abspath_fix, $script_filename_dir ) + strlen( $script_filename_dir ) );
  3636.                 // Strip off any file/query params from the path, appending the sub directory to the install
  3637.                 $path = preg_replace( '#/[^/]*$#i', '' , $_SERVER['REQUEST_URI'] ) . $subdirectory;
  3638.             } else {
  3639.                 $path = $_SERVER['REQUEST_URI'];
  3640.             }
  3641.         }
  3642.  
  3643.         $schema = is_ssl() ? 'https://' : 'http://'; // set_url_scheme() is not defined yet
  3644.         $url = $schema . $_SERVER['HTTP_HOST'] . $path;
  3645.     }
  3646.  
  3647.     return rtrim($url, '/');
  3648. }
  3649.  
  3650. /**
  3651.  * Temporarily suspend cache additions.
  3652.  *
  3653.  * Stops more data being added to the cache, but still allows cache retrieval.
  3654.  * This is useful for actions, such as imports, when a lot of data would otherwise
  3655.  * be almost uselessly added to the cache.
  3656.  *
  3657.  * Suspension lasts for a single page load at most. Remember to call this
  3658.  * function again if you wish to re-enable cache adds earlier.
  3659.  *
  3660.  * @since 3.3.0
  3661.  *
  3662.  * @param bool $suspend Optional. Suspends additions if true, re-enables them if false.
  3663.  * @return bool The current suspend setting
  3664.  */
  3665. function wp_suspend_cache_addition( $suspend = null ) {
  3666.     static $_suspend = false;
  3667.  
  3668.     if ( is_bool( $suspend ) )
  3669.         $_suspend = $suspend;
  3670.  
  3671.     return $_suspend;
  3672. }
  3673.  
  3674. /**
  3675.  * Suspend cache invalidation.
  3676.  *
  3677.  * Turns cache invalidation on and off. Useful during imports where you don't wont to do
  3678.  * invalidations every time a post is inserted. Callers must be sure that what they are
  3679.  * doing won't lead to an inconsistent cache when invalidation is suspended.
  3680.  *
  3681.  * @since 2.7.0
  3682.  *
  3683.  * @param bool $suspend Optional. Whether to suspend or enable cache invalidation. Default true.
  3684.  * @return bool The current suspend setting.
  3685.  */
  3686. function wp_suspend_cache_invalidation( $suspend = true ) {
  3687.     global $_wp_suspend_cache_invalidation;
  3688.  
  3689.     $current_suspend = $_wp_suspend_cache_invalidation;
  3690.     $_wp_suspend_cache_invalidation = $suspend;
  3691.     return $current_suspend;
  3692. }
  3693.  
  3694. /**
  3695.  * Determine whether a site is the main site of the current network.
  3696.  *
  3697.  * @since 3.0.0
  3698.  *
  3699.  * @param int $site_id Optional. Site ID to test. Defaults to current site.
  3700.  *                     Defaults to current site.
  3701.  * @return bool True if $site_id is the main site of the network, or if not
  3702.  *              running Multisite.
  3703.  */
  3704. function is_main_site( $site_id = null ) {
  3705.     // This is the current network's information; 'site' is old terminology.
  3706.     global $current_site;
  3707.  
  3708.     if ( ! is_multisite() )
  3709.         return true;
  3710.  
  3711.     if ( ! $site_id )
  3712.         $site_id = get_current_blog_id();
  3713.  
  3714.     return (int) $site_id === (int) $current_site->blog_id;
  3715. }
  3716.  
  3717. /**
  3718.  * Determine whether a network is the main network of the Multisite install.
  3719.  *
  3720.  * @since 3.7.0
  3721.  *
  3722.  * @param int $network_id Optional. Network ID to test. Defaults to current network.
  3723.  * @return bool True if $network_id is the main network, or if not running Multisite.
  3724.  */
  3725. function is_main_network( $network_id = null ) {
  3726.     global $wpdb;
  3727.  
  3728.     if ( ! is_multisite() )
  3729.         return true;
  3730.  
  3731.     $current_network_id = (int) get_current_site()->id;
  3732.  
  3733.     if ( ! $network_id )
  3734.         $network_id = $current_network_id;
  3735.     $network_id = (int) $network_id;
  3736.  
  3737.     if ( defined( 'PRIMARY_NETWORK_ID' ) )
  3738.         return $network_id === (int) PRIMARY_NETWORK_ID;
  3739.  
  3740.     if ( 1 === $current_network_id )
  3741.         return $network_id === $current_network_id;
  3742.  
  3743.     $primary_network_id = (int) wp_cache_get( 'primary_network_id', 'site-options' );
  3744.  
  3745.     if ( $primary_network_id )
  3746.         return $network_id === $primary_network_id;
  3747.  
  3748.     $primary_network_id = (int) $wpdb->get_var( "SELECT id FROM $wpdb->site ORDER BY id LIMIT 1" );
  3749.     wp_cache_add( 'primary_network_id', $primary_network_id, 'site-options' );
  3750.  
  3751.     return $network_id === $primary_network_id;
  3752. }
  3753.  
  3754. /**
  3755.  * Determine whether global terms are enabled.
  3756.  *
  3757.  * @since 3.0.0
  3758.  *
  3759.  * @return bool True if multisite and global terms enabled.
  3760.  */
  3761. function global_terms_enabled() {
  3762.     if ( ! is_multisite() )
  3763.         return false;
  3764.  
  3765.     static $global_terms = null;
  3766.     if ( is_null( $global_terms ) ) {
  3767.  
  3768.         /**
  3769.          * Filter whether global terms are enabled.
  3770.          *
  3771.          * Passing a non-null value to the filter will effectively short-circuit the function,
  3772.          * returning the value of the 'global_terms_enabled' site option instead.
  3773.          *
  3774.          * @since 3.0.0
  3775.          *
  3776.          * @param null $anbled Whether global terms are enabled.
  3777.          */
  3778.         $filter = apply_filters( 'global_terms_enabled', null );
  3779.         if ( ! is_null( $filter ) )
  3780.             $global_terms = (bool) $filter;
  3781.         else
  3782.             $global_terms = (bool) get_site_option( 'global_terms_enabled', false );
  3783.     }
  3784.     return $global_terms;
  3785. }
  3786.  
  3787. /**
  3788.  * gmt_offset modification for smart timezone handling.
  3789.  *
  3790.  * Overrides the gmt_offset option if we have a timezone_string available.
  3791.  *
  3792.  * @since 2.8.0
  3793.  *
  3794.  * @return float|bool Timezone GMT offset, false otherwise.
  3795.  */
  3796. function wp_timezone_override_offset() {
  3797.     if ( !$timezone_string = get_option( 'timezone_string' ) ) {
  3798.         return false;
  3799.     }
  3800.  
  3801.     $timezone_object = timezone_open( $timezone_string );
  3802.     $datetime_object = date_create();
  3803.     if ( false === $timezone_object || false === $datetime_object ) {
  3804.         return false;
  3805.     }
  3806.     return round( timezone_offset_get( $timezone_object, $datetime_object ) / HOUR_IN_SECONDS, 2 );
  3807. }
  3808.  
  3809. /**
  3810.  * Sort-helper for timezones.
  3811.  *
  3812.  * @since 2.9.0
  3813.  * @access private
  3814.  *
  3815.  * @param array $a
  3816.  * @param array $b
  3817.  * @return int
  3818.  */
  3819. function _wp_timezone_choice_usort_callback( $a, $b ) {
  3820.     // Don't use translated versions of Etc
  3821.     if ( 'Etc' === $a['continent'] && 'Etc' === $b['continent'] ) {
  3822.         // Make the order of these more like the old dropdown
  3823.         if ( 'GMT+' === substr( $a['city'], 0, 4 ) && 'GMT+' === substr( $b['city'], 0, 4 ) ) {
  3824.             return -1 * ( strnatcasecmp( $a['city'], $b['city'] ) );
  3825.         }
  3826.         if ( 'UTC' === $a['city'] ) {
  3827.             if ( 'GMT+' === substr( $b['city'], 0, 4 ) ) {
  3828.                 return 1;
  3829.             }
  3830.             return -1;
  3831.         }
  3832.         if ( 'UTC' === $b['city'] ) {
  3833.             if ( 'GMT+' === substr( $a['city'], 0, 4 ) ) {
  3834.                 return -1;
  3835.             }
  3836.             return 1;
  3837.         }
  3838.         return strnatcasecmp( $a['city'], $b['city'] );
  3839.     }
  3840.     if ( $a['t_continent'] == $b['t_continent'] ) {
  3841.         if ( $a['t_city'] == $b['t_city'] ) {
  3842.             return strnatcasecmp( $a['t_subcity'], $b['t_subcity'] );
  3843.         }
  3844.         return strnatcasecmp( $a['t_city'], $b['t_city'] );
  3845.     } else {
  3846.         // Force Etc to the bottom of the list
  3847.         if ( 'Etc' === $a['continent'] ) {
  3848.             return 1;
  3849.         }
  3850.         if ( 'Etc' === $b['continent'] ) {
  3851.             return -1;
  3852.         }
  3853.         return strnatcasecmp( $a['t_continent'], $b['t_continent'] );
  3854.     }
  3855. }
  3856.  
  3857. /**
  3858.  * Gives a nicely-formatted list of timezone strings.
  3859.  *
  3860.  * @since 2.9.0
  3861.  *
  3862.  * @param string $selected_zone Selected timezone.
  3863.  * @return string
  3864.  */
  3865. function wp_timezone_choice( $selected_zone ) {
  3866.     static $mo_loaded = false;
  3867.  
  3868.     $continents = array( 'Africa', 'America', 'Antarctica', 'Arctic', 'Asia', 'Atlantic', 'Australia', 'Europe', 'Indian', 'Pacific');
  3869.  
  3870.     // Load translations for continents and cities
  3871.     if ( !$mo_loaded ) {
  3872.         $locale = get_locale();
  3873.         $mofile = WP_LANG_DIR . '/continents-cities-' . $locale . '.mo';
  3874.         load_textdomain( 'continents-cities', $mofile );
  3875.         $mo_loaded = true;
  3876.     }
  3877.  
  3878.     $zonen = array();
  3879.     foreach ( timezone_identifiers_list() as $zone ) {
  3880.         $zone = explode( '/', $zone );
  3881.         if ( !in_array( $zone[0], $continents ) ) {
  3882.             continue;
  3883.         }
  3884.  
  3885.         // This determines what gets set and translated - we don't translate Etc/* strings here, they are done later
  3886.         $exists = array(
  3887.             0 => ( isset( $zone[0] ) && $zone[0] ),
  3888.             1 => ( isset( $zone[1] ) && $zone[1] ),
  3889.             2 => ( isset( $zone[2] ) && $zone[2] ),
  3890.         );
  3891.         $exists[3] = ( $exists[0] && 'Etc' !== $zone[0] );
  3892.         $exists[4] = ( $exists[1] && $exists[3] );
  3893.         $exists[5] = ( $exists[2] && $exists[3] );
  3894.  
  3895.         $zonen[] = array(
  3896.             'continent'   => ( $exists[0] ? $zone[0] : '' ),
  3897.             'city'        => ( $exists[1] ? $zone[1] : '' ),
  3898.             'subcity'     => ( $exists[2] ? $zone[2] : '' ),
  3899.             't_continent' => ( $exists[3] ? translate( str_replace( '_', ' ', $zone[0] ), 'continents-cities' ) : '' ),
  3900.             't_city'      => ( $exists[4] ? translate( str_replace( '_', ' ', $zone[1] ), 'continents-cities' ) : '' ),
  3901.             't_subcity'   => ( $exists[5] ? translate( str_replace( '_', ' ', $zone[2] ), 'continents-cities' ) : '' )
  3902.         );
  3903.     }
  3904.     usort( $zonen, '_wp_timezone_choice_usort_callback' );
  3905.  
  3906.     $structure = array();
  3907.  
  3908.     if ( empty( $selected_zone ) ) {
  3909.         $structure[] = '<option selected="selected" value="">' . __( 'Select a city' ) . '</option>';
  3910.     }
  3911.  
  3912.     foreach ( $zonen as $key => $zone ) {
  3913.         // Build value in an array to join later
  3914.         $value = array( $zone['continent'] );
  3915.  
  3916.         if ( empty( $zone['city'] ) ) {
  3917.             // It's at the continent level (generally won't happen)
  3918.             $display = $zone['t_continent'];
  3919.         } else {
  3920.             // It's inside a continent group
  3921.  
  3922.             // Continent optgroup
  3923.             if ( !isset( $zonen[$key - 1] ) || $zonen[$key - 1]['continent'] !== $zone['continent'] ) {
  3924.                 $label = $zone['t_continent'];
  3925.                 $structure[] = '<optgroup label="'. esc_attr( $label ) .'">';
  3926.             }
  3927.  
  3928.             // Add the city to the value
  3929.             $value[] = $zone['city'];
  3930.  
  3931.             $display = $zone['t_city'];
  3932.             if ( !empty( $zone['subcity'] ) ) {
  3933.                 // Add the subcity to the value
  3934.                 $value[] = $zone['subcity'];
  3935.                 $display .= ' - ' . $zone['t_subcity'];
  3936.             }
  3937.         }
  3938.  
  3939.         // Build the value
  3940.         $value = join( '/', $value );
  3941.         $selected = '';
  3942.         if ( $value === $selected_zone ) {
  3943.             $selected = 'selected="selected" ';
  3944.         }
  3945.         $structure[] = '<option ' . $selected . 'value="' . esc_attr( $value ) . '">' . esc_html( $display ) . "</option>";
  3946.  
  3947.         // Close continent optgroup
  3948.         if ( !empty( $zone['city'] ) && ( !isset($zonen[$key + 1]) || (isset( $zonen[$key + 1] ) && $zonen[$key + 1]['continent'] !== $zone['continent']) ) ) {
  3949.             $structure[] = '</optgroup>';
  3950.         }
  3951.     }
  3952.  
  3953.     // Do UTC
  3954.     $structure[] = '<optgroup label="'. esc_attr__( 'UTC' ) .'">';
  3955.     $selected = '';
  3956.     if ( 'UTC' === $selected_zone )
  3957.         $selected = 'selected="selected" ';
  3958.     $structure[] = '<option ' . $selected . 'value="' . esc_attr( 'UTC' ) . '">' . __('UTC') . '</option>';
  3959.     $structure[] = '</optgroup>';
  3960.  
  3961.     // Do manual UTC offsets
  3962.     $structure[] = '<optgroup label="'. esc_attr__( 'Manual Offsets' ) .'">';
  3963.     $offset_range = array (-12, -11.5, -11, -10.5, -10, -9.5, -9, -8.5, -8, -7.5, -7, -6.5, -6, -5.5, -5, -4.5, -4, -3.5, -3, -2.5, -2, -1.5, -1, -0.5,
  3964.         0, 0.5, 1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 5.75, 6, 6.5, 7, 7.5, 8, 8.5, 8.75, 9, 9.5, 10, 10.5, 11, 11.5, 12, 12.75, 13, 13.75, 14);
  3965.     foreach ( $offset_range as $offset ) {
  3966.         if ( 0 <= $offset )
  3967.             $offset_name = '+' . $offset;
  3968.         else
  3969.             $offset_name = (string) $offset;
  3970.  
  3971.         $offset_value = $offset_name;
  3972.         $offset_name = str_replace(array('.25','.5','.75'), array(':15',':30',':45'), $offset_name);
  3973.         $offset_name = 'UTC' . $offset_name;
  3974.         $offset_value = 'UTC' . $offset_value;
  3975.         $selected = '';
  3976.         if ( $offset_value === $selected_zone )
  3977.             $selected = 'selected="selected" ';
  3978.         $structure[] = '<option ' . $selected . 'value="' . esc_attr( $offset_value ) . '">' . esc_html( $offset_name ) . "</option>";
  3979.  
  3980.     }
  3981.     $structure[] = '</optgroup>';
  3982.  
  3983.     return join( "\n", $structure );
  3984. }
  3985.  
  3986. /**
  3987.  * Strip close comment and close php tags from file headers used by WP.
  3988.  *
  3989.  * @since 2.8.0
  3990.  * @access private
  3991.  *
  3992.  * @see http://core.trac.wordpress.org/ticket/8497
  3993.  *
  3994.  * @param string $str Header comment to clean up.
  3995.  * @return string
  3996.  */
  3997. function _cleanup_header_comment( $str ) {
  3998.     return trim(preg_replace("/\s*(?:\*\/|\?>).*/", '', $str));
  3999. }
  4000.  
  4001. /**
  4002.  * Permanently delete posts, pages, attachments, and comments which have been
  4003.  * in the trash for EMPTY_TRASH_DAYS.
  4004.  *
  4005.  * @since 2.9.0
  4006.  */
  4007. function wp_scheduled_delete() {
  4008.     global $wpdb;
  4009.  
  4010.     $delete_timestamp = time() - ( DAY_IN_SECONDS * EMPTY_TRASH_DAYS );
  4011.  
  4012.     $posts_to_delete = $wpdb->get_results($wpdb->prepare("SELECT post_id FROM $wpdb->postmeta WHERE meta_key = '_wp_trash_meta_time' AND meta_value < '%d'", $delete_timestamp), ARRAY_A);
  4013.  
  4014.     foreach ( (array) $posts_to_delete as $post ) {
  4015.         $post_id = (int) $post['post_id'];
  4016.         if ( !$post_id )
  4017.             continue;
  4018.  
  4019.         $del_post = get_post($post_id);
  4020.  
  4021.         if ( !$del_post || 'trash' != $del_post->post_status ) {
  4022.             delete_post_meta($post_id, '_wp_trash_meta_status');
  4023.             delete_post_meta($post_id, '_wp_trash_meta_time');
  4024.         } else {
  4025.             wp_delete_post($post_id);
  4026.         }
  4027.     }
  4028.  
  4029.     $comments_to_delete = $wpdb->get_results($wpdb->prepare("SELECT comment_id FROM $wpdb->commentmeta WHERE meta_key = '_wp_trash_meta_time' AND meta_value < '%d'", $delete_timestamp), ARRAY_A);
  4030.  
  4031.     foreach ( (array) $comments_to_delete as $comment ) {
  4032.         $comment_id = (int) $comment['comment_id'];
  4033.         if ( !$comment_id )
  4034.             continue;
  4035.  
  4036.         $del_comment = get_comment($comment_id);
  4037.  
  4038.         if ( !$del_comment || 'trash' != $del_comment->comment_approved ) {
  4039.             delete_comment_meta($comment_id, '_wp_trash_meta_time');
  4040.             delete_comment_meta($comment_id, '_wp_trash_meta_status');
  4041.         } else {
  4042.             wp_delete_comment($comment_id);
  4043.         }
  4044.     }
  4045. }
  4046.  
  4047. /**
  4048.  * Retrieve metadata from a file.
  4049.  *
  4050.  * Searches for metadata in the first 8kiB of a file, such as a plugin or theme.
  4051.  * Each piece of metadata must be on its own line. Fields can not span multiple
  4052.  * lines, the value will get cut at the end of the first line.
  4053.  *
  4054.  * If the file data is not within that first 8kiB, then the author should correct
  4055.  * their plugin file and move the data headers to the top.
  4056.  *
  4057.  * @see http://codex.wordpress.org/File_Header
  4058.  *
  4059.  * @since 2.9.0
  4060.  * @param string $file            Path to the file.
  4061.  * @param array  $default_headers List of headers, in the format array('HeaderKey' => 'Header Name').
  4062.  * @param string $context         Optional. If specified adds filter hook "extra_{$context}_headers".
  4063.  *                                Default empty.
  4064.  */
  4065. function get_file_data( $file, $default_headers, $context = '' ) {
  4066.     // We don't need to write to the file, so just open for reading.
  4067.     $fp = fopen( $file, 'r' );
  4068.  
  4069.     // Pull only the first 8kiB of the file in.
  4070.     $file_data = fread( $fp, 8192 );
  4071.  
  4072.     // PHP will close file handle, but we are good citizens.
  4073.     fclose( $fp );
  4074.  
  4075.     // Make sure we catch CR-only line endings.
  4076.     $file_data = str_replace( "\r", "\n", $file_data );
  4077.  
  4078.     /**
  4079.      * Filter extra file headers by context.
  4080.      *
  4081.      * The dynamic portion of the hook name, $context, refers to the context
  4082.      * where extra headers might be loaded.
  4083.      *
  4084.      * @since 2.9.0
  4085.      *
  4086.      * @param array $extra_context_headers Empty array by default.
  4087.      */
  4088.     if ( $context && $extra_headers = apply_filters( "extra_{$context}_headers", array() ) ) {
  4089.         $extra_headers = array_combine( $extra_headers, $extra_headers ); // keys equal values
  4090.         $all_headers = array_merge( $extra_headers, (array) $default_headers );
  4091.     } else {
  4092.         $all_headers = $default_headers;
  4093.     }
  4094.  
  4095.     foreach ( $all_headers as $field => $regex ) {
  4096.         if ( preg_match( '/^[ \t\/*#@]*' . preg_quote( $regex, '/' ) . ':(.*)$/mi', $file_data, $match ) && $match[1] )
  4097.             $all_headers[ $field ] = _cleanup_header_comment( $match[1] );
  4098.         else
  4099.             $all_headers[ $field ] = '';
  4100.     }
  4101.  
  4102.     return $all_headers;
  4103. }
  4104.  
  4105. /**
  4106.  * Returns true.
  4107.  *
  4108.  * Useful for returning true to filters easily.
  4109.  *
  4110.  * @since 3.0.0
  4111.  *
  4112.  * @see __return_false()
  4113.  *
  4114.  * @return bool True.
  4115.  */
  4116. function __return_true() {
  4117.     return true;
  4118. }
  4119.  
  4120. /**
  4121.  * Returns false.
  4122.  *
  4123.  * Useful for returning false to filters easily.
  4124.  *
  4125.  * @since 3.0.0
  4126.  *
  4127.  * @see __return_true()
  4128.  *
  4129.  * @return bool False.
  4130.  */
  4131. function __return_false() {
  4132.     return false;
  4133. }
  4134.  
  4135. /**
  4136.  * Returns 0.
  4137.  *
  4138.  * Useful for returning 0 to filters easily.
  4139.  *
  4140.  * @since 3.0.0
  4141.  *
  4142.  * @return int 0.
  4143.  */
  4144. function __return_zero() {
  4145.     return 0;
  4146. }
  4147.  
  4148. /**
  4149.  * Returns an empty array.
  4150.  *
  4151.  * Useful for returning an empty array to filters easily.
  4152.  *
  4153.  * @since 3.0.0
  4154.  *
  4155.  * @return array Empty array.
  4156.  */
  4157. function __return_empty_array() {
  4158.     return array();
  4159. }
  4160.  
  4161. /**
  4162.  * Returns null.
  4163.  *
  4164.  * Useful for returning null to filters easily.
  4165.  *
  4166.  * @since 3.4.0
  4167.  *
  4168.  * @return null Null value.
  4169.  */
  4170. function __return_null() {
  4171.     return null;
  4172. }
  4173.  
  4174. /**
  4175.  * Returns an empty string.
  4176.  *
  4177.  * Useful for returning an empty string to filters easily.
  4178.  *
  4179.  * @since 3.7.0
  4180.  *
  4181.  * @see __return_null()
  4182.  *
  4183.  * @return string Empty string.
  4184.  */
  4185. function __return_empty_string() {
  4186.     return '';
  4187. }
  4188.  
  4189. /**
  4190.  * Send a HTTP header to disable content type sniffing in browsers which support it.
  4191.  *
  4192.  * @since 3.0.0
  4193.  *
  4194.  * @see http://blogs.msdn.com/ie/archive/2008/07/02/ie8-security-part-v-comprehensive-protection.aspx
  4195.  * @see http://src.chromium.org/viewvc/chrome?view=rev&revision=6985
  4196.  */
  4197. function send_nosniff_header() {
  4198.     @header( 'X-Content-Type-Options: nosniff' );
  4199. }
  4200.  
  4201. /**
  4202.  * Return a MySQL expression for selecting the week number based on the start_of_week option.
  4203.  *
  4204.  * @internal
  4205.  * @since 3.0.0
  4206.  *
  4207.  * @param string $column Database column.
  4208.  * @return string SQL clause.
  4209.  */
  4210. function _wp_mysql_week( $column ) {
  4211.     switch ( $start_of_week = (int) get_option( 'start_of_week' ) ) {
  4212.     case 1 :
  4213.         return "WEEK( $column, 1 )";
  4214.     case 2 :
  4215.     case 3 :
  4216.     case 4 :
  4217.     case 5 :
  4218.     case 6 :
  4219.         return "WEEK( DATE_SUB( $column, INTERVAL $start_of_week DAY ), 0 )";
  4220.     case 0 :
  4221.     default :
  4222.         return "WEEK( $column, 0 )";
  4223.     }
  4224. }
  4225.  
  4226. /**
  4227.  * Find hierarchy loops using a callback function that maps object IDs to parent IDs.
  4228.  *
  4229.  * @since 3.1.0
  4230.  * @access private
  4231.  *
  4232.  * @param callback $callback      Function that accepts ( ID, $callback_args ) and outputs parent_ID.
  4233.  * @param int      $start         The ID to start the loop check at.
  4234.  * @param int      $start_parent  The parent_ID of $start to use instead of calling $callback( $start ).
  4235.  *                                Use null to always use $callback
  4236.  * @param array    $callback_args Optional. Additional arguments to send to $callback.
  4237.  * @return array IDs of all members of loop.
  4238.  */
  4239. function wp_find_hierarchy_loop( $callback, $start, $start_parent, $callback_args = array() ) {
  4240.     $override = is_null( $start_parent ) ? array() : array( $start => $start_parent );
  4241.  
  4242.     if ( !$arbitrary_loop_member = wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override, $callback_args ) )
  4243.         return array();
  4244.  
  4245.     return wp_find_hierarchy_loop_tortoise_hare( $callback, $arbitrary_loop_member, $override, $callback_args, true );
  4246. }
  4247.  
  4248. /**
  4249.  * Use the "The Tortoise and the Hare" algorithm to detect loops.
  4250.  *
  4251.  * For every step of the algorithm, the hare takes two steps and the tortoise one.
  4252.  * If the hare ever laps the tortoise, there must be a loop.
  4253.  *
  4254.  * @since 3.1.0
  4255.  * @access private
  4256.  *
  4257.  * @param callback $callback      Function that accepts ( ID, callback_arg, ... ) and outputs parent_ID.
  4258.  * @param int      $start         The ID to start the loop check at.
  4259.  * @param array    $override      Optional. An array of ( ID => parent_ID, ... ) to use instead of $callback.
  4260.  *                                Default empty array.
  4261.  * @param array    $callback_args Optional. Additional arguments to send to $callback. Default empty array.
  4262.  * @param bool     $_return_loop  Optional. Return loop members or just detect presence of loop? Only set
  4263.  *                                to true if you already know the given $start is part of a loop (otherwise
  4264.  *                                the returned array might include branches). Default false.
  4265.  * @return mixed Scalar ID of some arbitrary member of the loop, or array of IDs of all members of loop if
  4266.  *               $_return_loop
  4267.  */
  4268. function wp_find_hierarchy_loop_tortoise_hare( $callback, $start, $override = array(), $callback_args = array(), $_return_loop = false ) {
  4269.     $tortoise = $hare = $evanescent_hare = $start;
  4270.     $return = array();
  4271.  
  4272.     // Set evanescent_hare to one past hare
  4273.     // Increment hare two steps
  4274.     while (
  4275.         $tortoise
  4276.     &&
  4277.         ( $evanescent_hare = isset( $override[$hare] ) ? $override[$hare] : call_user_func_array( $callback, array_merge( array( $hare ), $callback_args ) ) )
  4278.     &&
  4279.         ( $hare = isset( $override[$evanescent_hare] ) ? $override[$evanescent_hare] : call_user_func_array( $callback, array_merge( array( $evanescent_hare ), $callback_args ) ) )
  4280.     ) {
  4281.         if ( $_return_loop )
  4282.             $return[$tortoise] = $return[$evanescent_hare] = $return[$hare] = true;
  4283.  
  4284.         // tortoise got lapped - must be a loop
  4285.         if ( $tortoise == $evanescent_hare || $tortoise == $hare )
  4286.             return $_return_loop ? $return : $tortoise;
  4287.  
  4288.         // Increment tortoise by one step
  4289.         $tortoise = isset( $override[$tortoise] ) ? $override[$tortoise] : call_user_func_array( $callback, array_merge( array( $tortoise ), $callback_args ) );
  4290.     }
  4291.  
  4292.     return false;
  4293. }
  4294.  
  4295. /**
  4296.  * Send a HTTP header to limit rendering of pages to same origin iframes.
  4297.  *
  4298.  * @since 3.1.3
  4299.  *
  4300.  * @see https://developer.mozilla.org/en/the_x-frame-options_response_header
  4301.  */
  4302. function send_frame_options_header() {
  4303.     @header( 'X-Frame-Options: SAMEORIGIN' );
  4304. }
  4305.  
  4306. /**
  4307.  * Retrieve a list of protocols to allow in HTML attributes.
  4308.  *
  4309.  * @since 3.3.0
  4310.  *
  4311.  * @see wp_kses()
  4312.  * @see esc_url()
  4313.  *
  4314.  * @return array Array of allowed protocols.
  4315.  */
  4316. function wp_allowed_protocols() {
  4317.     static $protocols;
  4318.  
  4319.     if ( empty( $protocols ) ) {
  4320.         $protocols = array( 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn', 'tel', 'fax', 'xmpp' );
  4321.  
  4322.         /**
  4323.          * Filter the list of protocols allowed in HTML attributes.
  4324.          *
  4325.          * @since 3.0.0
  4326.          *
  4327.          * @param array $protocols Array of allowed protocols e.g. 'http', 'ftp', 'tel', and more.
  4328.          */
  4329.         $protocols = apply_filters( 'kses_allowed_protocols', $protocols );
  4330.     }
  4331.  
  4332.     return $protocols;
  4333. }
  4334.  
  4335. /**
  4336.  * Return a comma-separated string of functions that have been called to get
  4337.  * to the current point in code.
  4338.  *
  4339.  * @since 3.4.0
  4340.  *
  4341.  * @see http://core.trac.wordpress.org/ticket/19589
  4342.  *
  4343.  * @param string $ignore_class Optional. A class to ignore all function calls within - useful
  4344.  *                             when you want to just give info about the callee. Default null.
  4345.  * @param int    $skip_frames  Optional. A number of stack frames to skip - useful for unwinding
  4346.  *                             back to the source of the issue. Default 0.
  4347.  * @param bool   $pretty       Optional. Whether or not you want a comma separated string or raw
  4348.  *                             array returned. Default true.
  4349.  * @return string|array Either a string containing a reversed comma separated trace or an array
  4350.  *                      of individual calls.
  4351.  */
  4352. function wp_debug_backtrace_summary( $ignore_class = null, $skip_frames = 0, $pretty = true ) {
  4353.     if ( version_compare( PHP_VERSION, '5.2.5', '>=' ) )
  4354.         $trace = debug_backtrace( false );
  4355.     else
  4356.         $trace = debug_backtrace();
  4357.  
  4358.     $caller = array();
  4359.     $check_class = ! is_null( $ignore_class );
  4360.     $skip_frames++; // skip this function
  4361.  
  4362.     foreach ( $trace as $call ) {
  4363.         if ( $skip_frames > 0 ) {
  4364.             $skip_frames--;
  4365.         } elseif ( isset( $call['class'] ) ) {
  4366.             if ( $check_class && $ignore_class == $call['class'] )
  4367.                 continue; // Filter out calls
  4368.  
  4369.             $caller[] = "{$call['class']}{$call['type']}{$call['function']}";
  4370.         } else {
  4371.             if ( in_array( $call['function'], array( 'do_action', 'apply_filters' ) ) ) {
  4372.                 $caller[] = "{$call['function']}('{$call['args'][0]}')";
  4373.             } elseif ( in_array( $call['function'], array( 'include', 'include_once', 'require', 'require_once' ) ) ) {
  4374.                 $caller[] = $call['function'] . "('" . str_replace( array( WP_CONTENT_DIR, ABSPATH ) , '', $call['args'][0] ) . "')";
  4375.             } else {
  4376.                 $caller[] = $call['function'];
  4377.             }
  4378.         }
  4379.     }
  4380.     if ( $pretty )
  4381.         return join( ', ', array_reverse( $caller ) );
  4382.     else
  4383.         return $caller;
  4384. }
  4385.  
  4386. /**
  4387.  * Retrieve ids that are not already present in the cache.
  4388.  *
  4389.  * @since 3.4.0
  4390.  * @access private
  4391.  *
  4392.  * @param array  $object_ids ID list.
  4393.  * @param string $cache_key  The cache bucket to check against.
  4394.  *
  4395.  * @return array List of ids not present in the cache.
  4396.  */
  4397. function _get_non_cached_ids( $object_ids, $cache_key ) {
  4398.     $clean = array();
  4399.     foreach ( $object_ids as $id ) {
  4400.         $id = (int) $id;
  4401.         if ( !wp_cache_get( $id, $cache_key ) ) {
  4402.             $clean[] = $id;
  4403.         }
  4404.     }
  4405.  
  4406.     return $clean;
  4407. }
  4408.  
  4409. /**
  4410.  * Test if the current device has the capability to upload files.
  4411.  *
  4412.  * @since 3.4.0
  4413.  * @access private
  4414.  *
  4415.  * @return bool true|false Whether the device is able to upload files.
  4416.  */
  4417. function _device_can_upload() {
  4418.     if ( ! wp_is_mobile() )
  4419.         return true;
  4420.  
  4421.     $ua = $_SERVER['HTTP_USER_AGENT'];
  4422.  
  4423.     if ( strpos($ua, 'iPhone') !== false
  4424.         || strpos($ua, 'iPad') !== false
  4425.         || strpos($ua, 'iPod') !== false ) {
  4426.             return preg_match( '#OS ([\d_]+) like Mac OS X#', $ua, $version ) && version_compare( $version[1], '6', '>=' );
  4427.     }
  4428.  
  4429.     return true;
  4430. }
  4431.  
  4432. /**
  4433.  * Test if a given path is a stream URL
  4434.  *
  4435.  * @param string $path The resource path or URL.
  4436.  * @return bool True if the path is a stream URL.
  4437.  */
  4438. function wp_is_stream( $path ) {
  4439.     $wrappers = stream_get_wrappers();
  4440.     $wrappers_re = '(' . join('|', $wrappers) . ')';
  4441.  
  4442.     return preg_match( "!^$wrappers_re://!", $path ) === 1;
  4443. }
  4444.  
  4445. /**
  4446.  * Test if the supplied date is valid for the Gregorian calendar.
  4447.  *
  4448.  * @since 3.5.0
  4449.  *
  4450.  * @see checkdate()
  4451.  *
  4452.  * @param  int    $month       Month number.
  4453.  * @param  int    $day         Day number.
  4454.  * @param  int    $year        Year number.
  4455.  * @param  string $source_date The date to filter.
  4456.  * @return bool True if valid date, false if not valid date.
  4457.  */
  4458. function wp_checkdate( $month, $day, $year, $source_date ) {
  4459.     /**
  4460.      * Filter whether the given date is valid for the Gregorian calendar.
  4461.      *
  4462.      * @since 3.5.0
  4463.      *
  4464.      * @param bool   $checkdate   Whether the given date is valid.
  4465.      * @param string $source_date Date to check.
  4466.      */
  4467.     return apply_filters( 'wp_checkdate', checkdate( $month, $day, $year ), $source_date );
  4468. }
  4469.  
  4470. /**
  4471.  * Load the auth check for monitoring whether the user is still logged in.
  4472.  *
  4473.  * Can be disabled with remove_action( 'admin_enqueue_scripts', 'wp_auth_check_load' );
  4474.  *
  4475.  * This is disabled for certain screens where a login screen could cause an
  4476.  * inconvenient interruption. A filter called wp_auth_check_load can be used
  4477.  * for fine-grained control.
  4478.  *
  4479.  * @since 3.6.0
  4480.  */
  4481. function wp_auth_check_load() {
  4482.     if ( ! is_admin() && ! is_user_logged_in() )
  4483.         return;
  4484.  
  4485.     if ( defined( 'IFRAME_REQUEST' ) )
  4486.         return;
  4487.  
  4488.     $screen = get_current_screen();
  4489.     $hidden = array( 'update', 'update-network', 'update-core', 'update-core-network', 'upgrade', 'upgrade-network', 'network' );
  4490.     $show = ! in_array( $screen->id, $hidden );
  4491.  
  4492.     /**
  4493.      * Filter whether to load the authentication check.
  4494.      *
  4495.      * Passing a falsey value to the filter will effectively short-circuit
  4496.      * loading the authentication check.
  4497.      *
  4498.      * @since 3.6.0
  4499.      *
  4500.      * @param bool      $show   Whether to load the authentication check.
  4501.      * @param WP_Screen $screen The current screen object.
  4502.      */
  4503.     if ( apply_filters( 'wp_auth_check_load', $show, $screen ) ) {
  4504.         wp_enqueue_style( 'wp-auth-check' );
  4505.         wp_enqueue_script( 'wp-auth-check' );
  4506.  
  4507.         add_action( 'admin_print_footer_scripts', 'wp_auth_check_html', 5 );
  4508.         add_action( 'wp_print_footer_scripts', 'wp_auth_check_html', 5 );
  4509.     }
  4510. }
  4511.  
  4512. /**
  4513.  * Output the HTML that shows the wp-login dialog when the user is no longer logged in.
  4514.  *
  4515.  * @since 3.6.0
  4516.  */
  4517. function wp_auth_check_html() {
  4518.     $login_url = wp_login_url();
  4519.     $current_domain = ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'];
  4520.     $same_domain = ( strpos( $login_url, $current_domain ) === 0 );
  4521.  
  4522.     /**
  4523.      * Filter whether the authentication check originated at the same domain.
  4524.      *
  4525.      * @since 3.6.0
  4526.      *
  4527.      * @param bool $same_domain Whether the authentication check originated at the same domain.
  4528.      */
  4529.     $same_domain = apply_filters( 'wp_auth_check_same_domain', $same_domain );
  4530.     $wrap_class = $same_domain ? 'hidden' : 'hidden fallback';
  4531.  
  4532.     ?>
  4533.     <div id="wp-auth-check-wrap" class="<?php echo $wrap_class; ?>">
  4534.     <div id="wp-auth-check-bg"></div>
  4535.     <div id="wp-auth-check">
  4536.     <div class="wp-auth-check-close" tabindex="0" title="<?php esc_attr_e('Close'); ?>"></div>
  4537.     <?php
  4538.  
  4539.     if ( $same_domain ) {
  4540.         ?>
  4541.         <div id="wp-auth-check-form" data-src="<?php echo esc_url( add_query_arg( array( 'interim-login' => 1 ), $login_url ) ); ?>"></div>
  4542.         <?php
  4543.     }
  4544.  
  4545.     ?>
  4546.     <div class="wp-auth-fallback">
  4547.         <p><b class="wp-auth-fallback-expired" tabindex="0"><?php _e('Session expired'); ?></b></p>
  4548.         <p><a href="<?php echo esc_url( $login_url ); ?>" target="_blank"><?php _e('Please log in again.'); ?></a>
  4549.         <?php _e('The login page will open in a new window. After logging in you can close it and return to this page.'); ?></p>
  4550.     </div>
  4551.     </div>
  4552.     </div>
  4553.     <?php
  4554. }
  4555.  
  4556. /**
  4557.  * Check whether a user is still logged in, for the heartbeat.
  4558.  *
  4559.  * Send a result that shows a log-in box if the user is no longer logged in,
  4560.  * or if their cookie is within the grace period.
  4561.  *
  4562.  * @since 3.6.0
  4563.  *
  4564.  * @param array|object $response  The Heartbeat response object or array.
  4565.  * @return array|object $response The Heartbeat response object or array with 'wp-auth-check'
  4566.  *                                value set.
  4567.  */
  4568. function wp_auth_check( $response ) {
  4569.     $response['wp-auth-check'] = is_user_logged_in() && empty( $GLOBALS['login_grace_period'] );
  4570.     return $response;
  4571. }
  4572.  
  4573. /**
  4574.  * Return RegEx body to liberally match an opening HTML tag.
  4575.  *
  4576.  * Matches an opening HTML tag that:
  4577.  * 1. Is self-closing or
  4578.  * 2. Has no body but has a closing tag of the same name or
  4579.  * 3. Contains a body and a closing tag of the same name
  4580.  *
  4581.  * Note: this RegEx does not balance inner tags and does not attempt
  4582.  * to produce valid HTML
  4583.  *
  4584.  * @since 3.6.0
  4585.  *
  4586.  * @param string $tag An HTML tag name. Example: 'video'.
  4587.  * @return string Tag RegEx.
  4588.  */
  4589. function get_tag_regex( $tag ) {
  4590.     if ( empty( $tag ) )
  4591.         return;
  4592.     return sprintf( '<%1$s[^<]*(?:>[\s\S]*<\/%1$s>|\s*\/>)', tag_escape( $tag ) );
  4593. }
  4594.  
  4595. /**
  4596.  * Retrieve a canonical form of the provided charset appropriate for passing to PHP
  4597.  * functions such as htmlspecialchars() and charset html attributes.
  4598.  *
  4599.  * @since 3.6.0
  4600.  * @access private
  4601.  *
  4602.  * @see http://core.trac.wordpress.org/ticket/23688
  4603.  *
  4604.  * @param string $charset A charset name.
  4605.  * @return string The canonical form of the charset.
  4606.  */
  4607. function _canonical_charset( $charset ) {
  4608.     if ( 'UTF-8' === $charset || 'utf-8' === $charset || 'utf8' === $charset ||
  4609.         'UTF8' === $charset )
  4610.         return 'UTF-8';
  4611.  
  4612.     if ( 'ISO-8859-1' === $charset || 'iso-8859-1' === $charset ||
  4613.         'iso8859-1' === $charset || 'ISO8859-1' === $charset )
  4614.         return 'ISO-8859-1';
  4615.  
  4616.     return $charset;
  4617. }
  4618.  
  4619. /**
  4620.  * Set the mbstring internal encoding to a binary safe encoding when func_overload
  4621.  * is enabled.
  4622.  *
  4623.  * When mbstring.func_overload is in use for multi-byte encodings, the results from
  4624.  * strlen() and similar functions respect the utf8 characters, causing binary data
  4625.  * to return incorrect lengths.
  4626.  *
  4627.  * This function overrides the mbstring encoding to a binary-safe encoding, and
  4628.  * resets it to the users expected encoding afterwards through the
  4629.  * `reset_mbstring_encoding` function.
  4630.  *
  4631.  * It is safe to recursively call this function, however each
  4632.  * `mbstring_binary_safe_encoding()` call must be followed up with an equal number
  4633.  * of `reset_mbstring_encoding()` calls.
  4634.  *
  4635.  * @since 3.7.0
  4636.  *
  4637.  * @see reset_mbstring_encoding()
  4638.  *
  4639.  * @param bool $reset Optional. Whether to reset the encoding back to a previously-set encoding.
  4640.  *                    Default false.
  4641.  */
  4642. function mbstring_binary_safe_encoding( $reset = false ) {
  4643.     static $encodings = array();
  4644.     static $overloaded = null;
  4645.  
  4646.     if ( is_null( $overloaded ) )
  4647.         $overloaded = function_exists( 'mb_internal_encoding' ) && ( ini_get( 'mbstring.func_overload' ) & 2 );
  4648.  
  4649.     if ( false === $overloaded )
  4650.         return;
  4651.  
  4652.     if ( ! $reset ) {
  4653.         $encoding = mb_internal_encoding();
  4654.         array_push( $encodings, $encoding );
  4655.         mb_internal_encoding( 'ISO-8859-1' );
  4656.     }
  4657.  
  4658.     if ( $reset && $encodings ) {
  4659.         $encoding = array_pop( $encodings );
  4660.         mb_internal_encoding( $encoding );
  4661.     }
  4662. }
  4663.  
  4664. /**
  4665.  * Reset the mbstring internal encoding to a users previously set encoding.
  4666.  *
  4667.  * @see mbstring_binary_safe_encoding()
  4668.  *
  4669.  * @since 3.7.0
  4670.  */
  4671. function reset_mbstring_encoding() {
  4672.     mbstring_binary_safe_encoding( true );
  4673. }
  4674.  
  4675. /**
  4676.  * Alternative to filter_var( $var, FILTER_VALIDATE_BOOLEAN ).
  4677.  *
  4678.  * @since 4.0.0
  4679.  *
  4680.  * @param mixed $var Boolean value to validate.
  4681.  * @return bool Whether the value is validated.
  4682.  */
  4683. function wp_validate_boolean( $var ) {
  4684.     if ( is_bool( $var ) ) {
  4685.         return $var;
  4686.     }
  4687.  
  4688.     if ( 'false' === $var ) {
  4689.         return false;
  4690.     }
  4691.  
  4692.     return (bool) $var;
  4693. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement