daily pastebin goal
44%
SHARE
TWEET

Untitled

avinashd Jan 28th, 2016 41 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2. /**
  3.  * These functions can be replaced via plugins. If plugins do not redefine these
  4.  * functions, then these will be used instead.
  5.  *
  6.  * @package WordPress
  7.  */
  8. if ( !function_exists('wp_set_current_user') ) :
  9. /**
  10.  * Changes the current user by ID or name.
  11.  *
  12.  * Set $id to null and specify a name if you do not know a user's ID.
  13.  *
  14.  * Some WordPress functionality is based on the current user and not based on
  15.  * the signed in user. Therefore, it opens the ability to edit and perform
  16.  * actions on users who aren't signed in.
  17.  *
  18.  * @since 2.0.3
  19.  * @global WP_User $current_user The current user object which holds the user data.
  20.  *
  21.  * @param int    $id   User ID
  22.  * @param string $name User's username
  23.  * @return WP_User Current user User object
  24.  */
  25. function wp_set_current_user($id, $name = '') {
  26.     global $current_user;
  27.  
  28.     if ( isset( $current_user ) && ( $current_user instanceof WP_User ) && ( $id == $current_user->ID ) )
  29.         return $current_user;
  30.  
  31.     $current_user = new WP_User( $id, $name );
  32.  
  33.     setup_userdata( $current_user->ID );
  34.  
  35.     /**
  36.      * Fires after the current user is set.
  37.      *
  38.      * @since 2.0.1
  39.      */
  40.     do_action( 'set_current_user' );
  41.  
  42.     return $current_user;
  43. }
  44. endif;
  45.  
  46. if ( !function_exists('wp_get_current_user') ) :
  47. /**
  48.  * Retrieve the current user object.
  49.  *
  50.  * @since 2.0.3
  51.  *
  52.  * @global WP_User $current_user
  53.  *
  54.  * @return WP_User Current user WP_User object
  55.  */
  56. function wp_get_current_user() {
  57.     global $current_user;
  58.  
  59.     get_currentuserinfo();
  60.  
  61.     return $current_user;
  62. }
  63. endif;
  64.  
  65. if ( !function_exists('get_currentuserinfo') ) :
  66. /**
  67.  * Populate global variables with information about the currently logged in user.
  68.  *
  69.  * Will set the current user, if the current user is not set. The current user
  70.  * will be set to the logged-in person. If no user is logged-in, then it will
  71.  * set the current user to 0, which is invalid and won't have any permissions.
  72.  *
  73.  * @since 0.71
  74.  *
  75.  * @global WP_User $current_user Checks if the current user is set
  76.  *
  77.  * @return false|void False on XML-RPC Request and invalid auth cookie.
  78.  */
  79. function get_currentuserinfo() {
  80.     global $current_user;
  81.  
  82.     if ( ! empty( $current_user ) ) {
  83.         if ( $current_user instanceof WP_User )
  84.             return;
  85.  
  86.         // Upgrade stdClass to WP_User
  87.         if ( is_object( $current_user ) && isset( $current_user->ID ) ) {
  88.             $cur_id = $current_user->ID;
  89.             $current_user = null;
  90.             wp_set_current_user( $cur_id );
  91.             return;
  92.         }
  93.  
  94.         // $current_user has a junk value. Force to WP_User with ID 0.
  95.         $current_user = null;
  96.         wp_set_current_user( 0 );
  97.         return false;
  98.     }
  99.  
  100.     if ( defined('XMLRPC_REQUEST') && XMLRPC_REQUEST ) {
  101.         wp_set_current_user( 0 );
  102.         return false;
  103.     }
  104.  
  105.     /**
  106.      * Filter the current user.
  107.      *
  108.      * The default filters use this to determine the current user from the
  109.      * request's cookies, if available.
  110.      *
  111.      * Returning a value of false will effectively short-circuit setting
  112.      * the current user.
  113.      *
  114.      * @since 3.9.0
  115.      *
  116.      * @param int|bool $user_id User ID if one has been determined, false otherwise.
  117.      */
  118.     $user_id = apply_filters( 'determine_current_user', false );
  119.     if ( ! $user_id ) {
  120.         wp_set_current_user( 0 );
  121.         return false;
  122.     }
  123.  
  124.     wp_set_current_user( $user_id );
  125. }
  126. endif;
  127.  
  128. if ( !function_exists('get_userdata') ) :
  129. /**
  130.  * Retrieve user info by user ID.
  131.  *
  132.  * @since 0.71
  133.  *
  134.  * @param int $user_id User ID
  135.  * @return WP_User|false WP_User object on success, false on failure.
  136.  */
  137. function get_userdata( $user_id ) {
  138.     return get_user_by( 'id', $user_id );
  139. }
  140. endif;
  141.  
  142. if ( !function_exists('get_user_by') ) :
  143. /**
  144.  * Retrieve user info by a given field
  145.  *
  146.  * @since 2.8.0
  147.  *
  148.  * @param string     $field The field to retrieve the user with. id | slug | email | login
  149.  * @param int|string $value A value for $field. A user ID, slug, email address, or login name.
  150.  * @return WP_User|false WP_User object on success, false on failure.
  151.  */
  152. function get_user_by( $field, $value ) {
  153.     $userdata = WP_User::get_data_by( $field, $value );
  154.  
  155.     if ( !$userdata )
  156.         return false;
  157.  
  158.     $user = new WP_User;
  159.     $user->init( $userdata );
  160.  
  161.     return $user;
  162. }
  163. endif;
  164.  
  165. if ( !function_exists('cache_users') ) :
  166. /**
  167.  * Retrieve info for user lists to prevent multiple queries by get_userdata()
  168.  *
  169.  * @since 3.0.0
  170.  *
  171.  * @global wpdb $wpdb
  172.  *
  173.  * @param array $user_ids User ID numbers list
  174.  */
  175. function cache_users( $user_ids ) {
  176.     global $wpdb;
  177.  
  178.     $clean = _get_non_cached_ids( $user_ids, 'users' );
  179.  
  180.     if ( empty( $clean ) )
  181.         return;
  182.  
  183.     $list = implode( ',', $clean );
  184.  
  185.     $users = $wpdb->get_results( "SELECT * FROM $wpdb->users WHERE ID IN ($list)" );
  186.  
  187.     $ids = array();
  188.     foreach ( $users as $user ) {
  189.         update_user_caches( $user );
  190.         $ids[] = $user->ID;
  191.     }
  192.     update_meta_cache( 'user', $ids );
  193. }
  194. endif;
  195.  
  196. if ( !function_exists( 'wp_mail' ) ) :
  197. /**
  198.  * Send mail, similar to PHP's mail
  199.  *
  200.  * A true return value does not automatically mean that the user received the
  201.  * email successfully. It just only means that the method used was able to
  202.  * process the request without any errors.
  203.  *
  204.  * Using the two 'wp_mail_from' and 'wp_mail_from_name' hooks allow from
  205.  * creating a from address like 'Name <email@address.com>' when both are set. If
  206.  * just 'wp_mail_from' is set, then just the email address will be used with no
  207.  * name.
  208.  *
  209.  * The default content type is 'text/plain' which does not allow using HTML.
  210.  * However, you can set the content type of the email by using the
  211.  * 'wp_mail_content_type' filter.
  212.  *
  213.  * The default charset is based on the charset used on the blog. The charset can
  214.  * be set using the 'wp_mail_charset' filter.
  215.  *
  216.  * @since 1.2.1
  217.  *
  218.  * @global PHPMailer $phpmailer
  219.  *
  220.  * @param string|array $to          Array or comma-separated list of email addresses to send message.
  221.  * @param string       $subject     Email subject
  222.  * @param string       $message     Message contents
  223.  * @param string|array $headers     Optional. Additional headers.
  224.  * @param string|array $attachments Optional. Files to attach.
  225.  * @return bool Whether the email contents were sent successfully.
  226.  */
  227. function wp_mail( $to, $subject, $message, $headers = '', $attachments = array() ) {
  228.     // Compact the input, apply the filters, and extract them back out
  229.  
  230.     /**
  231.      * Filter the wp_mail() arguments.
  232.      *
  233.      * @since 2.2.0
  234.      *
  235.      * @param array $args A compacted array of wp_mail() arguments, including the "to" email,
  236.      *                    subject, message, headers, and attachments values.
  237.      */
  238.     $atts = apply_filters( 'wp_mail', compact( 'to', 'subject', 'message', 'headers', 'attachments' ) );
  239.  
  240.     if ( isset( $atts['to'] ) ) {
  241.         $to = $atts['to'];
  242.     }
  243.  
  244.     if ( isset( $atts['subject'] ) ) {
  245.         $subject = $atts['subject'];
  246.     }
  247.  
  248.     if ( isset( $atts['message'] ) ) {
  249.         $message = $atts['message'];
  250.     }
  251.  
  252.     if ( isset( $atts['headers'] ) ) {
  253.         $headers = $atts['headers'];
  254.     }
  255.  
  256.     if ( isset( $atts['attachments'] ) ) {
  257.         $attachments = $atts['attachments'];
  258.     }
  259.  
  260.     if ( ! is_array( $attachments ) ) {
  261.         $attachments = explode( "\n", str_replace( "\r\n", "\n", $attachments ) );
  262.     }
  263.     global $phpmailer;
  264.  
  265.     // (Re)create it, if it's gone missing
  266.     if ( ! ( $phpmailer instanceof PHPMailer ) ) {
  267.         require_once ABSPATH . WPINC . '/class-phpmailer.php';
  268.         require_once ABSPATH . WPINC . '/class-smtp.php';
  269.         $phpmailer = new PHPMailer( true );
  270.     }
  271.  
  272.     // Headers
  273.     if ( empty( $headers ) ) {
  274.         $headers = array();
  275.     } else {
  276.         if ( !is_array( $headers ) ) {
  277.             // Explode the headers out, so this function can take both
  278.             // string headers and an array of headers.
  279.             $tempheaders = explode( "\n", str_replace( "\r\n", "\n", $headers ) );
  280.         } else {
  281.             $tempheaders = $headers;
  282.         }
  283.         $headers = array();
  284.         $cc = array();
  285.         $bcc = array();
  286.  
  287.         // If it's actually got contents
  288.         if ( !empty( $tempheaders ) ) {
  289.             // Iterate through the raw headers
  290.             foreach ( (array) $tempheaders as $header ) {
  291.                 if ( strpos($header, ':') === false ) {
  292.                     if ( false !== stripos( $header, 'boundary=' ) ) {
  293.                         $parts = preg_split('/boundary=/i', trim( $header ) );
  294.                         $boundary = trim( str_replace( array( "'", '"' ), '', $parts[1] ) );
  295.                     }
  296.                     continue;
  297.                 }
  298.                 // Explode them out
  299.                 list( $name, $content ) = explode( ':', trim( $header ), 2 );
  300.  
  301.                 // Cleanup crew
  302.                 $name    = trim( $name    );
  303.                 $content = trim( $content );
  304.  
  305.                 switch ( strtolower( $name ) ) {
  306.                     // Mainly for legacy -- process a From: header if it's there
  307.                     case 'from':
  308.                         $bracket_pos = strpos( $content, '<' );
  309.                         if ( $bracket_pos !== false ) {
  310.                             // Text before the bracketed email is the "From" name.
  311.                             if ( $bracket_pos > 0 ) {
  312.                                 $from_name = substr( $content, 0, $bracket_pos - 1 );
  313.                                 $from_name = str_replace( '"', '', $from_name );
  314.                                 $from_name = trim( $from_name );
  315.                             }
  316.  
  317.                             $from_email = substr( $content, $bracket_pos + 1 );
  318.                             $from_email = str_replace( '>', '', $from_email );
  319.                             $from_email = trim( $from_email );
  320.  
  321.                         // Avoid setting an empty $from_email.
  322.                         } elseif ( '' !== trim( $content ) ) {
  323.                             $from_email = trim( $content );
  324.                         }
  325.                         break;
  326.                     case 'content-type':
  327.                         if ( strpos( $content, ';' ) !== false ) {
  328.                             list( $type, $charset_content ) = explode( ';', $content );
  329.                             $content_type = trim( $type );
  330.                             if ( false !== stripos( $charset_content, 'charset=' ) ) {
  331.                                 $charset = trim( str_replace( array( 'charset=', '"' ), '', $charset_content ) );
  332.                             } elseif ( false !== stripos( $charset_content, 'boundary=' ) ) {
  333.                                 $boundary = trim( str_replace( array( 'BOUNDARY=', 'boundary=', '"' ), '', $charset_content ) );
  334.                                 $charset = '';
  335.                             }
  336.  
  337.                         // Avoid setting an empty $content_type.
  338.                         } elseif ( '' !== trim( $content ) ) {
  339.                             $content_type = trim( $content );
  340.                         }
  341.                         break;
  342.                     case 'cc':
  343.                         $cc = array_merge( (array) $cc, explode( ',', $content ) );
  344.                         break;
  345.                     case 'bcc':
  346.                         $bcc = array_merge( (array) $bcc, explode( ',', $content ) );
  347.                         break;
  348.                     default:
  349.                         // Add it to our grand headers array
  350.                         $headers[trim( $name )] = trim( $content );
  351.                         break;
  352.                 }
  353.             }
  354.         }
  355.     }
  356.  
  357.     // Empty out the values that may be set
  358.     $phpmailer->ClearAllRecipients();
  359.     $phpmailer->ClearAttachments();
  360.     $phpmailer->ClearCustomHeaders();
  361.     $phpmailer->ClearReplyTos();
  362.  
  363.     // From email and name
  364.     // If we don't have a name from the input headers
  365.     if ( !isset( $from_name ) )
  366.         $from_name = 'WordPress';
  367.  
  368.     /* If we don't have an email from the input headers default to wordpress@$sitename
  369.      * Some hosts will block outgoing mail from this address if it doesn't exist but
  370.      * there's no easy alternative. Defaulting to admin_email might appear to be another
  371.      * option but some hosts may refuse to relay mail from an unknown domain. See
  372.      * https://core.trac.wordpress.org/ticket/5007.
  373.      */
  374.  
  375.     if ( !isset( $from_email ) ) {
  376.         // Get the site domain and get rid of www.
  377.         $sitename = strtolower( $_SERVER['SERVER_NAME'] );
  378.         if ( substr( $sitename, 0, 4 ) == 'www.' ) {
  379.             $sitename = substr( $sitename, 4 );
  380.         }
  381.  
  382.         $from_email = 'wordpress@' . $sitename;
  383.     }
  384.  
  385.     /**
  386.      * Filter the email address to send from.
  387.      *
  388.      * @since 2.2.0
  389.      *
  390.      * @param string $from_email Email address to send from.
  391.      */
  392.     $phpmailer->From = apply_filters( 'wp_mail_from', $from_email );
  393.  
  394.     /**
  395.      * Filter the name to associate with the "from" email address.
  396.      *
  397.      * @since 2.3.0
  398.      *
  399.      * @param string $from_name Name associated with the "from" email address.
  400.      */
  401.     $phpmailer->FromName = apply_filters( 'wp_mail_from_name', $from_name );
  402.  
  403.     // Set destination addresses
  404.     if ( !is_array( $to ) )
  405.         $to = explode( ',', $to );
  406.  
  407.     foreach ( (array) $to as $recipient ) {
  408.         try {
  409.             // Break $recipient into name and address parts if in the format "Foo <bar@baz.com>"
  410.             $recipient_name = '';
  411.             if ( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) {
  412.                 if ( count( $matches ) == 3 ) {
  413.                     $recipient_name = $matches[1];
  414.                     $recipient = $matches[2];
  415.                 }
  416.             }
  417.             $phpmailer->AddAddress( $recipient, $recipient_name);
  418.         } catch ( phpmailerException $e ) {
  419.             continue;
  420.         }
  421.     }
  422.  
  423.     // Set mail's subject and body
  424.     $phpmailer->Subject = $subject;
  425.     $phpmailer->Body    = $message;
  426.  
  427.     // Add any CC and BCC recipients
  428.     if ( !empty( $cc ) ) {
  429.         foreach ( (array) $cc as $recipient ) {
  430.             try {
  431.                 // Break $recipient into name and address parts if in the format "Foo <bar@baz.com>"
  432.                 $recipient_name = '';
  433.                 if ( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) {
  434.                     if ( count( $matches ) == 3 ) {
  435.                         $recipient_name = $matches[1];
  436.                         $recipient = $matches[2];
  437.                     }
  438.                 }
  439.                 $phpmailer->AddCc( $recipient, $recipient_name );
  440.             } catch ( phpmailerException $e ) {
  441.                 continue;
  442.             }
  443.         }
  444.     }
  445.  
  446.     if ( !empty( $bcc ) ) {
  447.         foreach ( (array) $bcc as $recipient) {
  448.             try {
  449.                 // Break $recipient into name and address parts if in the format "Foo <bar@baz.com>"
  450.                 $recipient_name = '';
  451.                 if ( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) {
  452.                     if ( count( $matches ) == 3 ) {
  453.                         $recipient_name = $matches[1];
  454.                         $recipient = $matches[2];
  455.                     }
  456.                 }
  457.                 $phpmailer->AddBcc( $recipient, $recipient_name );
  458.             } catch ( phpmailerException $e ) {
  459.                 continue;
  460.             }
  461.         }
  462.     }
  463.  
  464.     // Set to use PHP's mail()
  465.     $phpmailer->IsMail();
  466.  
  467.     // Set Content-Type and charset
  468.     // If we don't have a content-type from the input headers
  469.     if ( !isset( $content_type ) )
  470.         $content_type = 'text/plain';
  471.  
  472.     /**
  473.      * Filter the wp_mail() content type.
  474.      *
  475.      * @since 2.3.0
  476.      *
  477.      * @param string $content_type Default wp_mail() content type.
  478.      */
  479.     $content_type = apply_filters( 'wp_mail_content_type', $content_type );
  480.  
  481.     $phpmailer->ContentType = $content_type;
  482.  
  483.     // Set whether it's plaintext, depending on $content_type
  484.     if ( 'text/html' == $content_type )
  485.         $phpmailer->IsHTML( true );
  486.  
  487.     // If we don't have a charset from the input headers
  488.     if ( !isset( $charset ) )
  489.         $charset = get_bloginfo( 'charset' );
  490.  
  491.     // Set the content-type and charset
  492.  
  493.     /**
  494.      * Filter the default wp_mail() charset.
  495.      *
  496.      * @since 2.3.0
  497.      *
  498.      * @param string $charset Default email charset.
  499.      */
  500.     $phpmailer->CharSet = apply_filters( 'wp_mail_charset', $charset );
  501.  
  502.     // Set custom headers
  503.     if ( !empty( $headers ) ) {
  504.         foreach( (array) $headers as $name => $content ) {
  505.             $phpmailer->AddCustomHeader( sprintf( '%1$s: %2$s', $name, $content ) );
  506.         }
  507.  
  508.         if ( false !== stripos( $content_type, 'multipart' ) && ! empty($boundary) )
  509.             $phpmailer->AddCustomHeader( sprintf( "Content-Type: %s;\n\t boundary=\"%s\"", $content_type, $boundary ) );
  510.     }
  511.  
  512.     if ( !empty( $attachments ) ) {
  513.         foreach ( $attachments as $attachment ) {
  514.             try {
  515.                 $phpmailer->AddAttachment($attachment);
  516.             } catch ( phpmailerException $e ) {
  517.                 continue;
  518.             }
  519.         }
  520.     }
  521.  
  522.     /**
  523.      * Fires after PHPMailer is initialized.
  524.      *
  525.      * @since 2.2.0
  526.      *
  527.      * @param PHPMailer &$phpmailer The PHPMailer instance, passed by reference.
  528.      */
  529.     do_action_ref_array( 'phpmailer_init', array( &$phpmailer ) );
  530.  
  531.     // Send!
  532.     try {
  533.         return $phpmailer->Send();
  534.     } catch ( phpmailerException $e ) {
  535.         return false;
  536.     }
  537. }
  538. endif;
  539.  
  540. if ( !function_exists('wp_authenticate') ) :
  541. /**
  542.  * Checks a user's login information and logs them in if it checks out.
  543.  *
  544.  * @since 2.5.0
  545.  *
  546.  * @param string $username User's username
  547.  * @param string $password User's password
  548.  * @return WP_User|WP_Error WP_User object if login successful, otherwise WP_Error object.
  549.  */
  550. function wp_authenticate($username, $password) {
  551.     $username = sanitize_user($username);
  552.     $password = trim($password);
  553.  
  554.     /**
  555.      * Filter the user to authenticate.
  556.      *
  557.      * If a non-null value is passed, the filter will effectively short-circuit
  558.      * authentication, returning an error instead.
  559.      *
  560.      * @since 2.8.0
  561.      *
  562.      * @param null|WP_User $user     User to authenticate.
  563.      * @param string       $username User login.
  564.      * @param string       $password User password
  565.      */
  566.     $user = apply_filters( 'authenticate', null, $username, $password );
  567.  
  568.     if ( $user == null ) {
  569.         // TODO what should the error message be? (Or would these even happen?)
  570.         // Only needed if all authentication handlers fail to return anything.
  571.         $user = new WP_Error('authentication_failed', __('<strong>ERROR</strong>: Invalid username or incorrect password.'));
  572.     }
  573.  
  574.     $ignore_codes = array('empty_username', 'empty_password');
  575.  
  576.     if (is_wp_error($user) && !in_array($user->get_error_code(), $ignore_codes) ) {
  577.         /**
  578.          * Fires after a user login has failed.
  579.          *
  580.          * @since 2.5.0
  581.          *
  582.          * @param string $username User login.
  583.          */
  584.         do_action( 'wp_login_failed', $username );
  585.     }
  586.  
  587.     return $user;
  588. }
  589. endif;
  590.  
  591. if ( !function_exists('wp_logout') ) :
  592. /**
  593.  * Log the current user out.
  594.  *
  595.  * @since 2.5.0
  596.  */
  597. function wp_logout() {
  598.     wp_destroy_current_session();
  599.     wp_clear_auth_cookie();
  600.  
  601.     /**
  602.      * Fires after a user is logged-out.
  603.      *
  604.      * @since 1.5.0
  605.      */
  606.     do_action( 'wp_logout' );
  607. }
  608. endif;
  609.  
  610. if ( !function_exists('wp_validate_auth_cookie') ) :
  611. /**
  612.  * Validates authentication cookie.
  613.  *
  614.  * The checks include making sure that the authentication cookie is set and
  615.  * pulling in the contents (if $cookie is not used).
  616.  *
  617.  * Makes sure the cookie is not expired. Verifies the hash in cookie is what is
  618.  * should be and compares the two.
  619.  *
  620.  * @since 2.5.0
  621.  *
  622.  * @global int $login_grace_period
  623.  *
  624.  * @param string $cookie Optional. If used, will validate contents instead of cookie's
  625.  * @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in
  626.  * @return false|int False if invalid cookie, User ID if valid.
  627.  */
  628. function wp_validate_auth_cookie($cookie = '', $scheme = '') {
  629.     if ( ! $cookie_elements = wp_parse_auth_cookie($cookie, $scheme) ) {
  630.         /**
  631.          * Fires if an authentication cookie is malformed.
  632.          *
  633.          * @since 2.7.0
  634.          *
  635.          * @param string $cookie Malformed auth cookie.
  636.          * @param string $scheme Authentication scheme. Values include 'auth', 'secure_auth',
  637.          *                       or 'logged_in'.
  638.          */
  639.         do_action( 'auth_cookie_malformed', $cookie, $scheme );
  640.         return false;
  641.     }
  642.  
  643.     $scheme = $cookie_elements['scheme'];
  644.     $username = $cookie_elements['username'];
  645.     $hmac = $cookie_elements['hmac'];
  646.     $token = $cookie_elements['token'];
  647.     $expired = $expiration = $cookie_elements['expiration'];
  648.  
  649.     // Allow a grace period for POST and AJAX requests
  650.     if ( defined('DOING_AJAX') || 'POST' == $_SERVER['REQUEST_METHOD'] ) {
  651.         $expired += HOUR_IN_SECONDS;
  652.     }
  653.  
  654.     // Quick check to see if an honest cookie has expired
  655.     if ( $expired < time() ) {
  656.         /**
  657.          * Fires once an authentication cookie has expired.
  658.          *
  659.          * @since 2.7.0
  660.          *
  661.          * @param array $cookie_elements An array of data for the authentication cookie.
  662.          */
  663.         do_action( 'auth_cookie_expired', $cookie_elements );
  664.         return false;
  665.     }
  666.  
  667.     $user = get_user_by('login', $username);
  668.     if ( ! $user ) {
  669.         /**
  670.          * Fires if a bad username is entered in the user authentication process.
  671.          *
  672.          * @since 2.7.0
  673.          *
  674.          * @param array $cookie_elements An array of data for the authentication cookie.
  675.          */
  676.         do_action( 'auth_cookie_bad_username', $cookie_elements );
  677.         return false;
  678.     }
  679.  
  680.     $pass_frag = substr($user->user_pass, 8, 4);
  681.  
  682.     $key = wp_hash( $username . '|' . $pass_frag . '|' . $expiration . '|' . $token, $scheme );
  683.  
  684.     // If ext/hash is not present, compat.php's hash_hmac() does not support sha256.
  685.     $algo = function_exists( 'hash' ) ? 'sha256' : 'sha1';
  686.     $hash = hash_hmac( $algo, $username . '|' . $expiration . '|' . $token, $key );
  687.  
  688.     if ( ! hash_equals( $hash, $hmac ) ) {
  689.         /**
  690.          * Fires if a bad authentication cookie hash is encountered.
  691.          *
  692.          * @since 2.7.0
  693.          *
  694.          * @param array $cookie_elements An array of data for the authentication cookie.
  695.          */
  696.         do_action( 'auth_cookie_bad_hash', $cookie_elements );
  697.         return false;
  698.     }
  699.  
  700.     $manager = WP_Session_Tokens::get_instance( $user->ID );
  701.     if ( ! $manager->verify( $token ) ) {
  702.         do_action( 'auth_cookie_bad_session_token', $cookie_elements );
  703.         return false;
  704.     }
  705.  
  706.     // AJAX/POST grace period set above
  707.     if ( $expiration < time() ) {
  708.         $GLOBALS['login_grace_period'] = 1;
  709.     }
  710.  
  711.     /**
  712.      * Fires once an authentication cookie has been validated.
  713.      *
  714.      * @since 2.7.0
  715.      *
  716.      * @param array   $cookie_elements An array of data for the authentication cookie.
  717.      * @param WP_User $user            User object.
  718.      */
  719.     do_action( 'auth_cookie_valid', $cookie_elements, $user );
  720.  
  721.     return $user->ID;
  722. }
  723. endif;
  724.  
  725. if ( !function_exists('wp_generate_auth_cookie') ) :
  726. /**
  727.  * Generate authentication cookie contents.
  728.  *
  729.  * @since 2.5.0
  730.  *
  731.  * @param int    $user_id    User ID
  732.  * @param int    $expiration Cookie expiration in seconds
  733.  * @param string $scheme     Optional. The cookie scheme to use: auth, secure_auth, or logged_in
  734.  * @param string $token      User's session token to use for this cookie
  735.  * @return string Authentication cookie contents. Empty string if user does not exist.
  736.  */
  737. function wp_generate_auth_cookie( $user_id, $expiration, $scheme = 'auth', $token = '' ) {
  738.     $user = get_userdata($user_id);
  739.     if ( ! $user ) {
  740.         return '';
  741.     }
  742.  
  743.     if ( ! $token ) {
  744.         $manager = WP_Session_Tokens::get_instance( $user_id );
  745.         $token = $manager->create( $expiration );
  746.     }
  747.  
  748.     $pass_frag = substr($user->user_pass, 8, 4);
  749.  
  750.     $key = wp_hash( $user->user_login . '|' . $pass_frag . '|' . $expiration . '|' . $token, $scheme );
  751.  
  752.     // If ext/hash is not present, compat.php's hash_hmac() does not support sha256.
  753.     $algo = function_exists( 'hash' ) ? 'sha256' : 'sha1';
  754.     $hash = hash_hmac( $algo, $user->user_login . '|' . $expiration . '|' . $token, $key );
  755.  
  756.     $cookie = $user->user_login . '|' . $expiration . '|' . $token . '|' . $hash;
  757.  
  758.     /**
  759.      * Filter the authentication cookie.
  760.      *
  761.      * @since 2.5.0
  762.      *
  763.      * @param string $cookie     Authentication cookie.
  764.      * @param int    $user_id    User ID.
  765.      * @param int    $expiration Authentication cookie expiration in seconds.
  766.      * @param string $scheme     Cookie scheme used. Accepts 'auth', 'secure_auth', or 'logged_in'.
  767.      * @param string $token      User's session token used.
  768.      */
  769.     return apply_filters( 'auth_cookie', $cookie, $user_id, $expiration, $scheme, $token );
  770. }
  771. endif;
  772.  
  773. if ( !function_exists('wp_parse_auth_cookie') ) :
  774. /**
  775.  * Parse a cookie into its components
  776.  *
  777.  * @since 2.7.0
  778.  *
  779.  * @param string $cookie
  780.  * @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in
  781.  * @return array|false Authentication cookie components
  782.  */
  783. function wp_parse_auth_cookie($cookie = '', $scheme = '') {
  784.     if ( empty($cookie) ) {
  785.         switch ($scheme){
  786.             case 'auth':
  787.                 $cookie_name = AUTH_COOKIE;
  788.                 break;
  789.             case 'secure_auth':
  790.                 $cookie_name = SECURE_AUTH_COOKIE;
  791.                 break;
  792.             case "logged_in":
  793.                 $cookie_name = LOGGED_IN_COOKIE;
  794.                 break;
  795.             default:
  796.                 if ( is_ssl() ) {
  797.                     $cookie_name = SECURE_AUTH_COOKIE;
  798.                     $scheme = 'secure_auth';
  799.                 } else {
  800.                     $cookie_name = AUTH_COOKIE;
  801.                     $scheme = 'auth';
  802.                 }
  803.         }
  804.  
  805.         if ( empty($_COOKIE[$cookie_name]) )
  806.             return false;
  807.         $cookie = $_COOKIE[$cookie_name];
  808.     }
  809.  
  810.     $cookie_elements = explode('|', $cookie);
  811.     if ( count( $cookie_elements ) !== 4 ) {
  812.         return false;
  813.     }
  814.  
  815.     list( $username, $expiration, $token, $hmac ) = $cookie_elements;
  816.  
  817.     return compact( 'username', 'expiration', 'token', 'hmac', 'scheme' );
  818. }
  819. endif;
  820.  
  821. if ( !function_exists('wp_set_auth_cookie') ) :
  822. /**
  823.  * Sets the authentication cookies based on user ID.
  824.  *
  825.  * The $remember parameter increases the time that the cookie will be kept. The
  826.  * default the cookie is kept without remembering is two days. When $remember is
  827.  * set, the cookies will be kept for 14 days or two weeks.
  828.  *
  829.  * @since 2.5.0
  830.  * @since 4.3.0 Added the `$token` parameter.
  831.  *
  832.  * @param int    $user_id  User ID
  833.  * @param bool   $remember Whether to remember the user
  834.  * @param mixed  $secure   Whether the admin cookies should only be sent over HTTPS.
  835.  *                         Default is_ssl().
  836.  * @param string $token    Optional. User's session token to use for this cookie.
  837.  */
  838. function wp_set_auth_cookie( $user_id, $remember = false, $secure = '', $token = '' ) {
  839.     if ( $remember ) {
  840.         /**
  841.          * Filter the duration of the authentication cookie expiration period.
  842.          *
  843.          * @since 2.8.0
  844.          *
  845.          * @param int  $length   Duration of the expiration period in seconds.
  846.          * @param int  $user_id  User ID.
  847.          * @param bool $remember Whether to remember the user login. Default false.
  848.          */
  849.         $expiration = time() + apply_filters( 'auth_cookie_expiration', 14 * DAY_IN_SECONDS, $user_id, $remember );
  850.  
  851.         /*
  852.          * Ensure the browser will continue to send the cookie after the expiration time is reached.
  853.          * Needed for the login grace period in wp_validate_auth_cookie().
  854.          */
  855.         $expire = $expiration + ( 12 * HOUR_IN_SECONDS );
  856.     } else {
  857.         /** This filter is documented in wp-includes/pluggable.php */
  858.         $expiration = time() + apply_filters( 'auth_cookie_expiration', 2 * DAY_IN_SECONDS, $user_id, $remember );
  859.         $expire = 0;
  860.     }
  861.  
  862.     if ( '' === $secure ) {
  863.         $secure = is_ssl();
  864.     }
  865.  
  866.     // Frontend cookie is secure when the auth cookie is secure and the site's home URL is forced HTTPS.
  867.     $secure_logged_in_cookie = $secure && 'https' === parse_url( get_option( 'home' ), PHP_URL_SCHEME );
  868.  
  869.     /**
  870.      * Filter whether the connection is secure.
  871.      *
  872.      * @since 3.1.0
  873.      *
  874.      * @param bool $secure  Whether the connection is secure.
  875.      * @param int  $user_id User ID.
  876.      */
  877.     $secure = apply_filters( 'secure_auth_cookie', $secure, $user_id );
  878.  
  879.     /**
  880.      * Filter whether to use a secure cookie when logged-in.
  881.      *
  882.      * @since 3.1.0
  883.      *
  884.      * @param bool $secure_logged_in_cookie Whether to use a secure cookie when logged-in.
  885.      * @param int  $user_id                 User ID.
  886.      * @param bool $secure                  Whether the connection is secure.
  887.      */
  888.     $secure_logged_in_cookie = apply_filters( 'secure_logged_in_cookie', $secure_logged_in_cookie, $user_id, $secure );
  889.  
  890.     if ( $secure ) {
  891.         $auth_cookie_name = SECURE_AUTH_COOKIE;
  892.         $scheme = 'secure_auth';
  893.     } else {
  894.         $auth_cookie_name = AUTH_COOKIE;
  895.         $scheme = 'auth';
  896.     }
  897.  
  898.     if ( '' === $token ) {
  899.         $manager = WP_Session_Tokens::get_instance( $user_id );
  900.         $token   = $manager->create( $expiration );
  901.     }
  902.  
  903.     $auth_cookie = wp_generate_auth_cookie( $user_id, $expiration, $scheme, $token );
  904.     $logged_in_cookie = wp_generate_auth_cookie( $user_id, $expiration, 'logged_in', $token );
  905.  
  906.     /**
  907.      * Fires immediately before the authentication cookie is set.
  908.      *
  909.      * @since 2.5.0
  910.      *
  911.      * @param string $auth_cookie Authentication cookie.
  912.      * @param int    $expire      Login grace period in seconds. Default 43,200 seconds, or 12 hours.
  913.      * @param int    $expiration  Duration in seconds the authentication cookie should be valid.
  914.      *                            Default 1,209,600 seconds, or 14 days.
  915.      * @param int    $user_id     User ID.
  916.      * @param string $scheme      Authentication scheme. Values include 'auth', 'secure_auth', or 'logged_in'.
  917.      */
  918.     do_action( 'set_auth_cookie', $auth_cookie, $expire, $expiration, $user_id, $scheme );
  919.  
  920.     /**
  921.      * Fires immediately before the secure authentication cookie is set.
  922.      *
  923.      * @since 2.6.0
  924.      *
  925.      * @param string $logged_in_cookie The logged-in cookie.
  926.      * @param int    $expire           Login grace period in seconds. Default 43,200 seconds, or 12 hours.
  927.      * @param int    $expiration       Duration in seconds the authentication cookie should be valid.
  928.      *                                 Default 1,209,600 seconds, or 14 days.
  929.      * @param int    $user_id          User ID.
  930.      * @param string $scheme           Authentication scheme. Default 'logged_in'.
  931.      */
  932.     do_action( 'set_logged_in_cookie', $logged_in_cookie, $expire, $expiration, $user_id, 'logged_in' );
  933.  
  934.     setcookie($auth_cookie_name, $auth_cookie, $expire, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN, $secure, true);
  935.     setcookie($auth_cookie_name, $auth_cookie, $expire, ADMIN_COOKIE_PATH, COOKIE_DOMAIN, $secure, true);
  936.     setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire, COOKIEPATH, COOKIE_DOMAIN, $secure_logged_in_cookie, true);
  937.     if ( COOKIEPATH != SITECOOKIEPATH )
  938.         setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire, SITECOOKIEPATH, COOKIE_DOMAIN, $secure_logged_in_cookie, true);
  939. }
  940. endif;
  941.  
  942. if ( !function_exists('wp_clear_auth_cookie') ) :
  943. /**
  944.  * Removes all of the cookies associated with authentication.
  945.  *
  946.  * @since 2.5.0
  947.  */
  948. function wp_clear_auth_cookie() {
  949.     /**
  950.      * Fires just before the authentication cookies are cleared.
  951.      *
  952.      * @since 2.7.0
  953.      */
  954.     do_action( 'clear_auth_cookie' );
  955.  
  956.     setcookie( AUTH_COOKIE,        ' ', time() - YEAR_IN_SECONDS, ADMIN_COOKIE_PATH,   COOKIE_DOMAIN );
  957.     setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, ADMIN_COOKIE_PATH,   COOKIE_DOMAIN );
  958.     setcookie( AUTH_COOKIE,        ' ', time() - YEAR_IN_SECONDS, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN );
  959.     setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN );
  960.     setcookie( LOGGED_IN_COOKIE,   ' ', time() - YEAR_IN_SECONDS, COOKIEPATH,          COOKIE_DOMAIN );
  961.     setcookie( LOGGED_IN_COOKIE,   ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH,      COOKIE_DOMAIN );
  962.  
  963.     // Old cookies
  964.     setcookie( AUTH_COOKIE,        ' ', time() - YEAR_IN_SECONDS, COOKIEPATH,     COOKIE_DOMAIN );
  965.     setcookie( AUTH_COOKIE,        ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
  966.     setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH,     COOKIE_DOMAIN );
  967.     setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
  968.  
  969.     // Even older cookies
  970.     setcookie( USER_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH,     COOKIE_DOMAIN );
  971.     setcookie( PASS_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH,     COOKIE_DOMAIN );
  972.     setcookie( USER_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
  973.     setcookie( PASS_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
  974. }
  975. endif;
  976.  
  977. if ( !function_exists('is_user_logged_in') ) :
  978. /**
  979.  * Checks if the current visitor is a logged in user.
  980.  *
  981.  * @since 2.0.0
  982.  *
  983.  * @return bool True if user is logged in, false if not logged in.
  984.  */
  985. function is_user_logged_in() {
  986.     $user = wp_get_current_user();
  987.  
  988.     return $user->exists();
  989. }
  990. endif;
  991.  
  992. if ( !function_exists('auth_redirect') ) :
  993. /**
  994.  * Checks if a user is logged in, if not it redirects them to the login page.
  995.  *
  996.  * @since 1.5.0
  997.  */
  998. function auth_redirect() {
  999.     // Checks if a user is logged in, if not redirects them to the login page
  1000.  
  1001.     $secure = ( is_ssl() || force_ssl_admin() );
  1002.  
  1003.     /**
  1004.      * Filter whether to use a secure authentication redirect.
  1005.      *
  1006.      * @since 3.1.0
  1007.      *
  1008.      * @param bool $secure Whether to use a secure authentication redirect. Default false.
  1009.      */
  1010.     $secure = apply_filters( 'secure_auth_redirect', $secure );
  1011.  
  1012.     // If https is required and request is http, redirect
  1013.     if ( $secure && !is_ssl() && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin') ) {
  1014.         if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) {
  1015.             wp_redirect( set_url_scheme( $_SERVER['REQUEST_URI'], 'https' ) );
  1016.             exit();
  1017.         } else {
  1018.             wp_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
  1019.             exit();
  1020.         }
  1021.     }
  1022.  
  1023.     if ( is_user_admin() ) {
  1024.         $scheme = 'logged_in';
  1025.     } else {
  1026.         /**
  1027.          * Filter the authentication redirect scheme.
  1028.          *
  1029.          * @since 2.9.0
  1030.          *
  1031.          * @param string $scheme Authentication redirect scheme. Default empty.
  1032.          */
  1033.         $scheme = apply_filters( 'auth_redirect_scheme', '' );
  1034.     }
  1035.  
  1036.     if ( $user_id = wp_validate_auth_cookie( '',  $scheme) ) {
  1037.         /**
  1038.          * Fires before the authentication redirect.
  1039.          *
  1040.          * @since 2.8.0
  1041.          *
  1042.          * @param int $user_id User ID.
  1043.          */
  1044.         do_action( 'auth_redirect', $user_id );
  1045.  
  1046.         // If the user wants ssl but the session is not ssl, redirect.
  1047.         if ( !$secure && get_user_option('use_ssl', $user_id) && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin') ) {
  1048.             if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) {
  1049.                 wp_redirect( set_url_scheme( $_SERVER['REQUEST_URI'], 'https' ) );
  1050.                 exit();
  1051.             } else {
  1052.                 wp_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
  1053.                 exit();
  1054.  
  1055.  
  1056.             }
  1057.         }
  1058.  
  1059.         return;  // The cookie is good so we're done
  1060.     }
  1061.  
  1062.     // The cookie is no good so force login
  1063.     nocache_headers();
  1064.  
  1065.     $redirect = ( strpos( $_SERVER['REQUEST_URI'], '/options.php' ) && wp_get_referer() ) ? wp_get_referer() : set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
  1066.  
  1067.     $login_url = wp_login_url($redirect, true);
  1068.  
  1069.     wp_redirect($login_url);
  1070.     exit();
  1071. }
  1072. endif;
  1073.  
  1074. if ( !function_exists('check_admin_referer') ) :
  1075. /**
  1076.  * Makes sure that a user was referred from another admin page.
  1077.  *
  1078.  * To avoid security exploits.
  1079.  *
  1080.  * @since 1.2.0
  1081.  *
  1082.  * @param int|string $action    Action nonce.
  1083.  * @param string     $query_arg Optional. Key to check for nonce in `$_REQUEST` (since 2.5).
  1084.  *                              Default '_wpnonce'.
  1085.  * @return false|int False if the nonce is invalid, 1 if the nonce is valid and generated between
  1086.  *                   0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.
  1087.  */
  1088. function check_admin_referer( $action = -1, $query_arg = '_wpnonce' ) {
  1089.     if ( -1 == $action )
  1090.         _doing_it_wrong( __FUNCTION__, __( 'You should specify a nonce action to be verified by using the first parameter.' ), '3.2' );
  1091.  
  1092.     $adminurl = strtolower(admin_url());
  1093.     $referer = strtolower(wp_get_referer());
  1094.     $result = isset($_REQUEST[$query_arg]) ? wp_verify_nonce($_REQUEST[$query_arg], $action) : false;
  1095.  
  1096.     /**
  1097.      * Fires once the admin request has been validated or not.
  1098.      *
  1099.      * @since 1.5.1
  1100.      *
  1101.      * @param string    $action The nonce action.
  1102.      * @param false|int $result False if the nonce is invalid, 1 if the nonce is valid and generated between
  1103.      *                          0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.
  1104.      */
  1105.     do_action( 'check_admin_referer', $action, $result );
  1106.  
  1107.     if ( ! $result && ! ( -1 == $action && strpos( $referer, $adminurl ) === 0 ) ) {
  1108.         wp_nonce_ays( $action );
  1109.         die();
  1110.     }
  1111.  
  1112.     return $result;
  1113. }
  1114. endif;
  1115.  
  1116. if ( !function_exists('check_ajax_referer') ) :
  1117. /**
  1118.  * Verifies the AJAX request to prevent processing requests external of the blog.
  1119.  *
  1120.  * @since 2.0.3
  1121.  *
  1122.  * @param int|string   $action    Action nonce.
  1123.  * @param false|string $query_arg Optional. Key to check for the nonce in `$_REQUEST` (since 2.5). If false,
  1124.  *                                `$_REQUEST` values will be evaluated for '_ajax_nonce', and '_wpnonce'
  1125.  *                                (in that order). Default false.
  1126.  * @param bool         $die       Optional. Whether to die early when the nonce cannot be verified.
  1127.  *                                Default true.
  1128.  * @return false|int False if the nonce is invalid, 1 if the nonce is valid and generated between
  1129.  *                   0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.
  1130.  */
  1131. function check_ajax_referer( $action = -1, $query_arg = false, $die = true ) {
  1132.     $nonce = '';
  1133.  
  1134.     if ( $query_arg && isset( $_REQUEST[ $query_arg ] ) )
  1135.         $nonce = $_REQUEST[ $query_arg ];
  1136.     elseif ( isset( $_REQUEST['_ajax_nonce'] ) )
  1137.         $nonce = $_REQUEST['_ajax_nonce'];
  1138.     elseif ( isset( $_REQUEST['_wpnonce'] ) )
  1139.         $nonce = $_REQUEST['_wpnonce'];
  1140.  
  1141.     $result = wp_verify_nonce( $nonce, $action );
  1142.  
  1143.     if ( $die && false === $result ) {
  1144.         if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
  1145.             wp_die( -1 );
  1146.         else
  1147.             die( '-1' );
  1148.     }
  1149.  
  1150.     /**
  1151.      * Fires once the AJAX request has been validated or not.
  1152.      *
  1153.      * @since 2.1.0
  1154.      *
  1155.      * @param string    $action The AJAX nonce action.
  1156.      * @param false|int $result False if the nonce is invalid, 1 if the nonce is valid and generated between
  1157.      *                          0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.
  1158.      */
  1159.     do_action( 'check_ajax_referer', $action, $result );
  1160.  
  1161.     return $result;
  1162. }
  1163. endif;
  1164.  
  1165. if ( !function_exists('wp_redirect') ) :
  1166. /**
  1167.  * Redirects to another page.
  1168.  *
  1169.  * @since 1.5.1
  1170.  *
  1171.  * @global bool $is_IIS
  1172.  *
  1173.  * @param string $location The path to redirect to.
  1174.  * @param int    $status   Status code to use.
  1175.  * @return bool False if $location is not provided, true otherwise.
  1176.  */
  1177. function wp_redirect($location, $status = 302) {
  1178.     global $is_IIS;
  1179.  
  1180.     /**
  1181.      * Filter the redirect location.
  1182.      *
  1183.      * @since 2.1.0
  1184.      *
  1185.      * @param string $location The path to redirect to.
  1186.      * @param int    $status   Status code to use.
  1187.      */
  1188.     $location = apply_filters( 'wp_redirect', $location, $status );
  1189.  
  1190.     /**
  1191.      * Filter the redirect status code.
  1192.      *
  1193.      * @since 2.3.0
  1194.      *
  1195.      * @param int    $status   Status code to use.
  1196.      * @param string $location The path to redirect to.
  1197.      */
  1198.     $status = apply_filters( 'wp_redirect_status', $status, $location );
  1199.  
  1200.     if ( ! $location )
  1201.         return false;
  1202.  
  1203.     $location = wp_sanitize_redirect($location);
  1204.  
  1205.     if ( !$is_IIS && PHP_SAPI != 'cgi-fcgi' )
  1206. status_header($status); // This causes problems on IIS and some FastCGI setups
  1207. header("Location: $location", true, $status);
  1208. return true;
  1209. }
  1210. endif;
  1211. if ( !function_exists('wp_sanitize_redirect') ) :
  1212. /**
  1213.  * Sanitizes a URL for use in a redirect.
  1214.  *
  1215.  * @since 2.3.0
  1216.  *
  1217.  * @return string redirect-sanitized URL
  1218.  **/
  1219. function wp_sanitize_redirect($location) {
  1220.     $regex = '/
  1221.         (
  1222.             (?: [\xC2-\xDF][\x80-\xBF]        # double-byte sequences   110xxxxx 10xxxxxx
  1223.             |   \xE0[\xA0-\xBF][\x80-\xBF]    # triple-byte sequences   1110xxxx 10xxxxxx * 2
  1224.             |   [\xE1-\xEC][\x80-\xBF]{2}
  1225.             |   \xED[\x80-\x9F][\x80-\xBF]
  1226.             |   [\xEE-\xEF][\x80-\xBF]{2}
  1227.             |   \xF0[\x90-\xBF][\x80-\xBF]{2} # four-byte sequences   11110xxx 10xxxxxx * 3
  1228.             |   [\xF1-\xF3][\x80-\xBF]{3}
  1229.             |   \xF4[\x80-\x8F][\x80-\xBF]{2}
  1230.         ){1,40}                              # ...one or more times
  1231.         )/x';
  1232.     $location = preg_replace_callback( $regex, '_wp_sanitize_utf8_in_redirect', $location );
  1233.     $location = preg_replace('|[^a-z0-9-~+_.?#=&;,/:%!*\[\]()]|i', '', $location);
  1234.     $location = wp_kses_no_null($location);
  1235.  
  1236.     // remove %0d and %0a from location
  1237.     $strip = array('%0d', '%0a', '%0D', '%0A');
  1238.     return _deep_replace( $strip, $location );
  1239. }
  1240.  
  1241. /**
  1242.  * URL encode UTF-8 characters in a URL.
  1243.  *
  1244.  * @ignore
  1245.  * @since 4.2.0
  1246.  * @access private
  1247.  *
  1248.  * @see wp_sanitize_redirect()
  1249.  */
  1250. function _wp_sanitize_utf8_in_redirect( $matches ) {
  1251.     return urlencode( $matches[0] );
  1252. }
  1253. endif;
  1254.  
  1255. if ( !function_exists('wp_safe_redirect') ) :
  1256. /**
  1257.  * Performs a safe (local) redirect, using wp_redirect().
  1258.  *
  1259.  * Checks whether the $location is using an allowed host, if it has an absolute
  1260.  * path. A plugin can therefore set or remove allowed host(s) to or from the
  1261.  * list.
  1262.  *
  1263.  * If the host is not allowed, then the redirect defaults to wp-admin on the siteurl
  1264.  * instead. This prevents malicious redirects which redirect to another host,
  1265.  * but only used in a few places.
  1266.  *
  1267.  * @since 2.3.0
  1268.  */
  1269. function wp_safe_redirect($location, $status = 302) {
  1270.  
  1271.     // Need to look at the URL the way it will end up in wp_redirect()
  1272.     $location = wp_sanitize_redirect($location);
  1273.  
  1274.     /**
  1275.      * Filter the redirect fallback URL for when the provided redirect is not safe (local).
  1276.      *
  1277.      * @since 4.3.0
  1278.      *
  1279.      * @param string $fallback_url The fallback URL to use by default.
  1280.      * @param int    $status       The redirect status.
  1281.      */
  1282.     $location = wp_validate_redirect( $location, apply_filters( 'wp_safe_redirect_fallback', admin_url(), $status ) );
  1283.  
  1284.     wp_redirect($location, $status);
  1285. }
  1286. endif;
  1287.  
  1288. if ( !function_exists('wp_validate_redirect') ) :
  1289. /**
  1290.  * Validates a URL for use in a redirect.
  1291.  *
  1292.  * Checks whether the $location is using an allowed host, if it has an absolute
  1293.  * path. A plugin can therefore set or remove allowed host(s) to or from the
  1294.  * list.
  1295.  *
  1296.  * If the host is not allowed, then the redirect is to $default supplied
  1297.  *
  1298.  * @since 2.8.1
  1299.  *
  1300.  * @param string $location The redirect to validate
  1301.  * @param string $default  The value to return if $location is not allowed
  1302.  * @return string redirect-sanitized URL
  1303.  **/
  1304. function wp_validate_redirect($location, $default = '') {
  1305.     $location = trim( $location );
  1306.     // browsers will assume 'http' is your protocol, and will obey a redirect to a URL starting with '//'
  1307.     if ( substr($location, 0, 2) == '//' )
  1308.         $location = 'http:' . $location;
  1309.  
  1310.     // In php 5 parse_url may fail if the URL query part contains http://, bug #38143
  1311.     $test = ( $cut = strpos($location, '?') ) ? substr( $location, 0, $cut ) : $location;
  1312.  
  1313.     $lp  = parse_url($test);
  1314.  
  1315.     // Give up if malformed URL
  1316.     if ( false === $lp )
  1317.         return $default;
  1318.  
  1319.     // Allow only http and https schemes. No data:, etc.
  1320.     if ( isset($lp['scheme']) && !('http' == $lp['scheme'] || 'https' == $lp['scheme']) )
  1321.         return $default;
  1322.  
  1323.     // Reject if scheme is set but host is not. This catches urls like https:host.com for which parse_url does not set the host field.
  1324.     if ( isset($lp['scheme'])  && !isset($lp['host']) )
  1325.         return $default;
  1326.  
  1327.     $wpp = parse_url(home_url());
  1328.  
  1329.     /**
  1330.      * Filter the whitelist of hosts to redirect to.
  1331.      *
  1332.      * @since 2.3.0
  1333.      *
  1334.      * @param array       $hosts An array of allowed hosts.
  1335.      * @param bool|string $host  The parsed host; empty if not isset.
  1336.      */
  1337.     $allowed_hosts = (array) apply_filters( 'allowed_redirect_hosts', array($wpp['host']), isset($lp['host']) ? $lp['host'] : '' );
  1338.  
  1339.     if ( isset($lp['host']) && ( !in_array($lp['host'], $allowed_hosts) && $lp['host'] != strtolower($wpp['host'])) )
  1340.         $location = $default;
  1341.  
  1342.     return $location;
  1343. }
  1344. endif;
  1345.  
  1346. if ( ! function_exists('wp_notify_postauthor') ) :
  1347. /**
  1348.  * Notify an author (and/or others) of a comment/trackback/pingback on a post.
  1349.  *
  1350.  * @since 1.0.0
  1351.  *
  1352.  * @param int    $comment_id Comment ID
  1353.  * @param string $deprecated Not used
  1354.  * @return bool True on completion. False if no email addresses were specified.
  1355.  */
  1356. function wp_notify_postauthor( $comment_id, $deprecated = null ) {
  1357.     if ( null !== $deprecated ) {
  1358.         _deprecated_argument( __FUNCTION__, '3.8' );
  1359.     }
  1360.  
  1361.     $comment = get_comment( $comment_id );
  1362.     if ( empty( $comment ) )
  1363.         return false;
  1364.  
  1365.     $post    = get_post( $comment->comment_post_ID );
  1366.     $author  = get_userdata( $post->post_author );
  1367.  
  1368.     // Who to notify? By default, just the post author, but others can be added.
  1369.     $emails = array();
  1370.     if ( $author ) {
  1371.         $emails[] = $author->user_email;
  1372.     }
  1373.  
  1374.     /**
  1375.      * Filter the list of email addresses to receive a comment notification.
  1376.      *
  1377.      * By default, only post authors are notified of comments. This filter allows
  1378.      * others to be added.
  1379.      *
  1380.      * @since 3.7.0
  1381.      *
  1382.      * @param array $emails     An array of email addresses to receive a comment notification.
  1383.      * @param int   $comment_id The comment ID.
  1384.      */
  1385.     $emails = apply_filters( 'comment_notification_recipients', $emails, $comment_id );
  1386.     $emails = array_filter( $emails );
  1387.  
  1388.     // If there are no addresses to send the comment to, bail.
  1389.     if ( ! count( $emails ) ) {
  1390.         return false;
  1391.     }
  1392.  
  1393.     // Facilitate unsetting below without knowing the keys.
  1394.     $emails = array_flip( $emails );
  1395.  
  1396.     /**
  1397.      * Filter whether to notify comment authors of their comments on their own posts.
  1398.      *
  1399.      * By default, comment authors aren't notified of their comments on their own
  1400.      * posts. This filter allows you to override that.
  1401.      *
  1402.      * @since 3.8.0
  1403.      *
  1404.      * @param bool $notify     Whether to notify the post author of their own comment.
  1405.      *                         Default false.
  1406.      * @param int  $comment_id The comment ID.
  1407.      */
  1408.     $notify_author = apply_filters( 'comment_notification_notify_author', false, $comment_id );
  1409.  
  1410.     // The comment was left by the author
  1411.     if ( $author && ! $notify_author && $comment->user_id == $post->post_author ) {
  1412.         unset( $emails[ $author->user_email ] );
  1413.     }
  1414.  
  1415.     // The author moderated a comment on their own post
  1416.     if ( $author && ! $notify_author && $post->post_author == get_current_user_id() ) {
  1417.         unset( $emails[ $author->user_email ] );
  1418.     }
  1419.  
  1420.     // The post author is no longer a member of the blog
  1421.     if ( $author && ! $notify_author && ! user_can( $post->post_author, 'read_post', $post->ID ) ) {
  1422.         unset( $emails[ $author->user_email ] );
  1423.     }
  1424.  
  1425.     // If there's no email to send the comment to, bail, otherwise flip array back around for use below
  1426.     if ( ! count( $emails ) ) {
  1427.         return false;
  1428.     } else {
  1429.         $emails = array_flip( $emails );
  1430.     }
  1431.  
  1432.     $comment_author_domain = @gethostbyaddr($comment->comment_author_IP);
  1433.  
  1434.     // The blogname option is escaped with esc_html on the way into the database in sanitize_option
  1435.     // we want to reverse this for the plain text arena of emails.
  1436.     $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
  1437.  
  1438.     switch ( $comment->comment_type ) {
  1439.         case 'trackback':
  1440.             $notify_message  = sprintf( __( 'New trackback on your post "%s"' ), $post->post_title ) . "\r\n";
  1441.             /* translators: 1: website name, 2: website IP, 3: website hostname */
  1442.             $notify_message .= sprintf( __('Website: %1$s (IP: %2$s, %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
  1443.             $notify_message .= sprintf( __( 'URL: %s' ), $comment->comment_author_url ) . "\r\n";
  1444.             $notify_message .= sprintf( __( 'Comment: %s' ), "\r\n" . $comment->comment_content ) . "\r\n\r\n";
  1445.             $notify_message .= __( 'You can see all trackbacks on this post here:' ) . "\r\n";
  1446.             /* translators: 1: blog name, 2: post title */
  1447.             $subject = sprintf( __('[%1$s] Trackback: "%2$s"'), $blogname, $post->post_title );
  1448.             break;
  1449.         case 'pingback':
  1450.             $notify_message  = sprintf( __( 'New pingback on your post "%s"' ), $post->post_title ) . "\r\n";
  1451.             /* translators: 1: website name, 2: website IP, 3: website hostname */
  1452.             $notify_message .= sprintf( __('Website: %1$s (IP: %2$s, %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
  1453.             $notify_message .= sprintf( __( 'URL: %s' ), $comment->comment_author_url ) . "\r\n";
  1454.             $notify_message .= sprintf( __( 'Comment: %s' ), "\r\n" . $comment->comment_content ) . "\r\n\r\n";
  1455.             $notify_message .= __( 'You can see all pingbacks on this post here:' ) . "\r\n";
  1456.             /* translators: 1: blog name, 2: post title */
  1457.             $subject = sprintf( __('[%1$s] Pingback: "%2$s"'), $blogname, $post->post_title );
  1458.             break;
  1459.         default: // Comments
  1460.             $notify_message  = sprintf( __( 'New comment on your post "%s"' ), $post->post_title ) . "\r\n";
  1461.             /* translators: 1: comment author, 2: author IP, 3: author domain */
  1462.             $notify_message .= sprintf( __( 'Author: %1$s (IP: %2$s, %3$s)' ), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
  1463.             $notify_message .= sprintf( __( 'E-mail: %s' ), $comment->comment_author_email ) . "\r\n";
  1464.             $notify_message .= sprintf( __( 'URL: %s' ), $comment->comment_author_url ) . "\r\n";
  1465.             $notify_message .= sprintf( __('Comment: %s' ), "\r\n" . $comment->comment_content ) . "\r\n\r\n";
  1466.             $notify_message .= __( 'You can see all comments on this post here:' ) . "\r\n";
  1467.             /* translators: 1: blog name, 2: post title */
  1468.             $subject = sprintf( __('[%1$s] Comment: "%2$s"'), $blogname, $post->post_title );
  1469.             break;
  1470.     }
  1471.     $notify_message .= get_permalink($comment->comment_post_ID) . "#comments\r\n\r\n";
  1472.     $notify_message .= sprintf( __('Permalink: %s'), get_comment_link( $comment_id ) ) . "\r\n";
  1473.  
  1474.     if ( user_can( $post->post_author, 'edit_comment', $comment_id ) ) {
  1475.         if ( EMPTY_TRASH_DAYS )
  1476.             $notify_message .= sprintf( __('Trash it: %s'), admin_url("comment.php?action=trash&c=$comment_id") ) . "\r\n";
  1477.         else
  1478.             $notify_message .= sprintf( __('Delete it: %s'), admin_url("comment.php?action=delete&c=$comment_id") ) . "\r\n";
  1479.         $notify_message .= sprintf( __('Spam it: %s'), admin_url("comment.php?action=spam&c=$comment_id") ) . "\r\n";
  1480.     }
  1481.  
  1482.     $wp_email = 'wordpress@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME']));
  1483.  
  1484.     if ( '' == $comment->comment_author ) {
  1485.         $from = "From: \"$blogname\" <$wp_email>";
  1486.         if ( '' != $comment->comment_author_email )
  1487.             $reply_to = "Reply-To: $comment->comment_author_email";
  1488.     } else {
  1489.         $from = "From: \"$comment->comment_author\" <$wp_email>";
  1490.         if ( '' != $comment->comment_author_email )
  1491.             $reply_to = "Reply-To: \"$comment->comment_author_email\" <$comment->comment_author_email>";
  1492.     }
  1493.  
  1494.     $message_headers = "$from\n"
  1495.         . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
  1496.  
  1497.     if ( isset($reply_to) )
  1498.         $message_headers .= $reply_to . "\n";
  1499.  
  1500.     /**
  1501.      * Filter the comment notification email text.
  1502.      *
  1503.      * @since 1.5.2
  1504.      *
  1505.      * @param string $notify_message The comment notification email text.
  1506.      * @param int    $comment_id     Comment ID.
  1507.      */
  1508.     $notify_message = apply_filters( 'comment_notification_text', $notify_message, $comment_id );
  1509.  
  1510.     /**
  1511.      * Filter the comment notification email subject.
  1512.      *
  1513.      * @since 1.5.2
  1514.      *
  1515.      * @param string $subject    The comment notification email subject.
  1516.      * @param int    $comment_id Comment ID.
  1517.      */
  1518.     $subject = apply_filters( 'comment_notification_subject', $subject, $comment_id );
  1519.  
  1520.     /**
  1521.      * Filter the comment notification email headers.
  1522.      *
  1523.      * @since 1.5.2
  1524.      *
  1525.      * @param string $message_headers Headers for the comment notification email.
  1526.      * @param int    $comment_id      Comment ID.
  1527.      */
  1528.     $message_headers = apply_filters( 'comment_notification_headers', $message_headers, $comment_id );
  1529.  
  1530.     foreach ( $emails as $email ) {
  1531.         @wp_mail( $email, wp_specialchars_decode( $subject ), $notify_message, $message_headers );
  1532.     }
  1533.  
  1534.     return true;
  1535. }
  1536. endif;
  1537.  
  1538. if ( !function_exists('wp_notify_moderator') ) :
  1539. /**
  1540.  * Notifies the moderator of the blog about a new comment that is awaiting approval.
  1541.  *
  1542.  * @since 1.0.0
  1543.  *
  1544.  * @global wpdb $wpdb WordPress database abstraction object.
  1545.  *
  1546.  * @param int $comment_id Comment ID
  1547.  * @return true Always returns true
  1548.  */
  1549. function wp_notify_moderator($comment_id) {
  1550.     global $wpdb;
  1551.  
  1552.     if ( 0 == get_option( 'moderation_notify' ) )
  1553.         return true;
  1554.  
  1555.     $comment = get_comment($comment_id);
  1556.     $post = get_post($comment->comment_post_ID);
  1557.     $user = get_userdata( $post->post_author );
  1558.     // Send to the administration and to the post author if the author can modify the comment.
  1559.     $emails = array( get_option( 'admin_email' ) );
  1560.     if ( $user && user_can( $user->ID, 'edit_comment', $comment_id ) && ! empty( $user->user_email ) ) {
  1561.         if ( 0 !== strcasecmp( $user->user_email, get_option( 'admin_email' ) ) )
  1562.             $emails[] = $user->user_email;
  1563.     }
  1564.  
  1565.     $comment_author_domain = @gethostbyaddr($comment->comment_author_IP);
  1566.     $comments_waiting = $wpdb->get_var("SELECT count(comment_ID) FROM $wpdb->comments WHERE comment_approved = '0'");
  1567.  
  1568.     // The blogname option is escaped with esc_html on the way into the database in sanitize_option
  1569.     // we want to reverse this for the plain text arena of emails.
  1570.     $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
  1571.  
  1572.     switch ( $comment->comment_type ) {
  1573.         case 'trackback':
  1574.             $notify_message  = sprintf( __('A new trackback on the post "%s" is waiting for your approval'), $post->post_title ) . "\r\n";
  1575.             $notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n";
  1576.             /* translators: 1: website name, 2: website IP, 3: website hostname */
  1577.             $notify_message .= sprintf( __( 'Website: %1$s (IP: %2$s, %3$s)' ), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
  1578.             $notify_message .= sprintf( __( 'URL: %s' ), $comment->comment_author_url ) . "\r\n";
  1579.             $notify_message .= __('Trackback excerpt: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
  1580.             break;
  1581.         case 'pingback':
  1582.             $notify_message  = sprintf( __('A new pingback on the post "%s" is waiting for your approval'), $post->post_title ) . "\r\n";
  1583.             $notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n";
  1584.             /* translators: 1: website name, 2: website IP, 3: website hostname */
  1585.             $notify_message .= sprintf( __( 'Website: %1$s (IP: %2$s, %3$s)' ), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
  1586.             $notify_message .= sprintf( __( 'URL: %s' ), $comment->comment_author_url ) . "\r\n";
  1587.             $notify_message .= __('Pingback excerpt: ') . "\r\n" . $comment->comment_content . "\r\n\r\n";
  1588.             break;
  1589.         default: // Comments
  1590.             $notify_message  = sprintf( __('A new comment on the post "%s" is waiting for your approval'), $post->post_title ) . "\r\n";
  1591.             $notify_message .= get_permalink($comment->comment_post_ID) . "\r\n\r\n";
  1592.             $notify_message .= sprintf( __( 'Author: %1$s (IP: %2$s, %3$s)' ), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
  1593.             $notify_message .= sprintf( __( 'E-mail: %s' ), $comment->comment_author_email ) . "\r\n";
  1594.             $notify_message .= sprintf( __( 'URL: %s' ), $comment->comment_author_url ) . "\r\n";
  1595.             $notify_message .= sprintf( __( 'Comment: %s' ), "\r\n" . $comment->comment_content ) . "\r\n\r\n";
  1596.             break;
  1597.     }
  1598.  
  1599.     $notify_message .= sprintf( __('Approve it: %s'),  admin_url("comment.php?action=approve&c=$comment_id") ) . "\r\n";
  1600.     if ( EMPTY_TRASH_DAYS )
  1601.         $notify_message .= sprintf( __('Trash it: %s'), admin_url("comment.php?action=trash&c=$comment_id") ) . "\r\n";
  1602.     else
  1603.         $notify_message .= sprintf( __('Delete it: %s'), admin_url("comment.php?action=delete&c=$comment_id") ) . "\r\n";
  1604.     $notify_message .= sprintf( __('Spam it: %s'), admin_url("comment.php?action=spam&c=$comment_id") ) . "\r\n";
  1605.  
  1606.     $notify_message .= sprintf( _n('Currently %s comment is waiting for approval. Please visit the moderation panel:',
  1607.         'Currently %s comments are waiting for approval. Please visit the moderation panel:', $comments_waiting), number_format_i18n($comments_waiting) ) . "\r\n";
  1608.     $notify_message .= admin_url("edit-comments.php?comment_status=moderated") . "\r\n";
  1609.  
  1610.     $subject = sprintf( __('[%1$s] Please moderate: "%2$s"'), $blogname, $post->post_title );
  1611.     $message_headers = '';
  1612.  
  1613.     /**
  1614.      * Filter the list of recipients for comment moderation emails.
  1615.      *
  1616.      * @since 3.7.0
  1617.      *
  1618.      * @param array $emails     List of email addresses to notify for comment moderation.
  1619.      * @param int   $comment_id Comment ID.
  1620.      */
  1621.     $emails = apply_filters( 'comment_moderation_recipients', $emails, $comment_id );
  1622.  
  1623.     /**
  1624.      * Filter the comment moderation email text.
  1625.      *
  1626.      * @since 1.5.2
  1627.      *
  1628.      * @param string $notify_message Text of the comment moderation email.
  1629.      * @param int    $comment_id     Comment ID.
  1630.      */
  1631.     $notify_message = apply_filters( 'comment_moderation_text', $notify_message, $comment_id );
  1632.  
  1633.     /**
  1634.      * Filter the comment moderation email subject.
  1635.      *
  1636.      * @since 1.5.2
  1637.      *
  1638.      * @param string $subject    Subject of the comment moderation email.
  1639.      * @param int    $comment_id Comment ID.
  1640.      */
  1641.     $subject = apply_filters( 'comment_moderation_subject', $subject, $comment_id );
  1642.  
  1643.     /**
  1644.      * Filter the comment moderation email headers.
  1645.      *
  1646.      * @since 2.8.0
  1647.      *
  1648.      * @param string $message_headers Headers for the comment moderation email.
  1649.      * @param int    $comment_id      Comment ID.
  1650.      */
  1651.     $message_headers = apply_filters( 'comment_moderation_headers', $message_headers, $comment_id );
  1652.  
  1653.     foreach ( $emails as $email ) {
  1654.         @wp_mail( $email, wp_specialchars_decode( $subject ), $notify_message, $message_headers );
  1655.     }
  1656.  
  1657.     return true;
  1658. }
  1659. endif;
  1660.  
  1661. if ( !function_exists('wp_password_change_notification') ) :
  1662. /**
  1663.  * Notify the blog admin of a user changing password, normally via email.
  1664.  *
  1665.  * @since 2.7.0
  1666.  *
  1667.  * @param object $user User Object
  1668.  */
  1669. function wp_password_change_notification(&$user) {
  1670.     // send a copy of password change notification to the admin
  1671.     // but check to see if it's the admin whose password we're changing, and skip this
  1672.     if ( 0 !== strcasecmp( $user->user_email, get_option( 'admin_email' ) ) ) {
  1673.         $message = sprintf(__('Password Lost and Changed for user: %s'), $user->user_login) . "\r\n";
  1674.         // The blogname option is escaped with esc_html on the way into the database in sanitize_option
  1675.         // we want to reverse this for the plain text arena of emails.
  1676.         $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
  1677.         wp_mail(get_option('admin_email'), sprintf(__('[%s] Password Lost/Changed'), $blogname), $message);
  1678.     }
  1679. }
  1680. endif;
  1681.  
  1682. if ( !function_exists('wp_new_user_notification') ) :
  1683. /**
  1684.  * Email login credentials to a newly-registered user.
  1685.  *
  1686.  * A new user registration notification is also sent to admin email.
  1687.  *
  1688.  * @since 2.0.0
  1689.  * @since 4.3.0 The `$plaintext_pass` parameter was changed to `$notify`.
  1690.  * @since 4.3.1 The `$plaintext_pass` parameter was deprecated. `$notify` added as a third parameter.
  1691.  *
  1692.  * @global wpdb         $wpdb      WordPress database object for queries.
  1693.  * @global PasswordHash $wp_hasher Portable PHP password hashing framework instance.
  1694.  *
  1695.  * @param int    $user_id    User ID.
  1696.  * @param null   $deprecated Not used (argument deprecated).
  1697.  * @param string $notify     Optional. Type of notification that should happen. Accepts 'admin' or an empty
  1698.  *                           string (admin only), or 'both' (admin and user). The empty string value was kept
  1699.  *                           for backward-compatibility purposes with the renamed parameter. Default empty.
  1700.  */
  1701. function wp_new_user_notification( $user_id, $deprecated = null, $notify = '' ) {
  1702.     if ( $deprecated !== null ) {
  1703.         _deprecated_argument( __FUNCTION__, '4.3.1' );
  1704.     }
  1705.  
  1706.     global $wpdb, $wp_hasher;
  1707.     $user = get_userdata( $user_id );
  1708.  
  1709.     // The blogname option is escaped with esc_html on the way into the database in sanitize_option
  1710.     // we want to reverse this for the plain text arena of emails.
  1711.     $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
  1712.  
  1713.     $message  = sprintf(__('New user registration on your site %s:'), $blogname) . "\r\n\r\n";
  1714.     $message .= sprintf(__('Username: %s'), $user->user_login) . "\r\n\r\n";
  1715.     $message .= sprintf(__('E-mail: %s'), $user->user_email) . "\r\n";
  1716.  
  1717.     @wp_mail(get_option('admin_email'), sprintf(__('[%s] New User Registration'), $blogname), $message);
  1718.  
  1719.     if ( 'admin' === $notify || empty( $notify ) ) {
  1720.         return;
  1721.     }
  1722.  
  1723.     // Generate something random for a password reset key.
  1724.     $key = wp_generate_password( 20, false );
  1725.  
  1726.     /** This action is documented in wp-login.php */
  1727.     do_action( 'retrieve_password_key', $user->user_login, $key );
  1728.  
  1729.     // Now insert the key, hashed, into the DB.
  1730.     if ( empty( $wp_hasher ) ) {
  1731.         require_once ABSPATH . WPINC . '/class-phpass.php';
  1732.         $wp_hasher = new PasswordHash( 8, true );
  1733.     }
  1734.     $hashed = time() . ':' . $wp_hasher->HashPassword( $key );
  1735.     $wpdb->update( $wpdb->users, array( 'user_activation_key' => $hashed ), array( 'user_login' => $user->user_login ) );
  1736.  
  1737.     $message = sprintf(__('Username: %s'), $user->user_login) . "\r\n\r\n";
  1738.     $message .= __('To set your password, visit the following address:') . "\r\n\r\n";
  1739.     $message .= '<' . network_site_url("wp-login.php?action=rp&key=$key&login=" . rawurlencode($user->user_login), 'login') . ">\r\n\r\n";
  1740.  
  1741.     $message .= wp_login_url() . "\r\n";
  1742.  
  1743.     wp_mail($user->user_email, sprintf(__('[%s] Your username and password info'), $blogname), $message);
  1744. }
  1745. endif;
  1746.  
  1747. if ( !function_exists('wp_nonce_tick') ) :
  1748. /**
  1749.  * Get the time-dependent variable for nonce creation.
  1750.  *
  1751.  * A nonce has a lifespan of two ticks. Nonces in their second tick may be
  1752.  * updated, e.g. by autosave.
  1753.  *
  1754.  * @since 2.5.0
  1755.  *
  1756.  * @return float Float value rounded up to the next highest integer.
  1757.  */
  1758. function wp_nonce_tick() {
  1759.     /**
  1760.      * Filter the lifespan of nonces in seconds.
  1761.      *
  1762.      * @since 2.5.0
  1763.      *
  1764.      * @param int $lifespan Lifespan of nonces in seconds. Default 86,400 seconds, or one day.
  1765.      */
  1766.     $nonce_life = apply_filters( 'nonce_life', DAY_IN_SECONDS );
  1767.  
  1768.     return ceil(time() / ( $nonce_life / 2 ));
  1769. }
  1770. endif;
  1771.  
  1772. if ( !function_exists('wp_verify_nonce') ) :
  1773. /**
  1774.  * Verify that correct nonce was used with time limit.
  1775.  *
  1776.  * The user is given an amount of time to use the token, so therefore, since the
  1777.  * UID and $action remain the same, the independent variable is the time.
  1778.  *
  1779.  * @since 2.0.3
  1780.  *
  1781.  * @param string     $nonce  Nonce that was used in the form to verify
  1782.  * @param string|int $action Should give context to what is taking place and be the same when nonce was created.
  1783.  * @return false|int False if the nonce is invalid, 1 if the nonce is valid and generated between
  1784.  *                   0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.
  1785.  */
  1786. function wp_verify_nonce( $nonce, $action = -1 ) {
  1787.     $nonce = (string) $nonce;
  1788.     $user = wp_get_current_user();
  1789.     $uid = (int) $user->ID;
  1790.     if ( ! $uid ) {
  1791.         /**
  1792.          * Filter whether the user who generated the nonce is logged out.
  1793.          *
  1794.          * @since 3.5.0
  1795.          *
  1796.          * @param int    $uid    ID of the nonce-owning user.
  1797.          * @param string $action The nonce action.
  1798.          */
  1799.         $uid = apply_filters( 'nonce_user_logged_out', $uid, $action );
  1800.     }
  1801.  
  1802.     if ( empty( $nonce ) ) {
  1803.         return false;
  1804.     }
  1805.  
  1806.     $token = wp_get_session_token();
  1807.     $i = wp_nonce_tick();
  1808.  
  1809.     // Nonce generated 0-12 hours ago
  1810.     $expected = substr( wp_hash( $i . '|' . $action . '|' . $uid . '|' . $token, 'nonce'), -12, 10 );
  1811.     if ( hash_equals( $expected, $nonce ) ) {
  1812.         return 1;
  1813.     }
  1814.  
  1815.     // Nonce generated 12-24 hours ago
  1816.     $expected = substr( wp_hash( ( $i - 1 ) . '|' . $action . '|' . $uid . '|' . $token, 'nonce' ), -12, 10 );
  1817.     if ( hash_equals( $expected, $nonce ) ) {
  1818.         return 2;
  1819.     }
  1820.  
  1821.     // Invalid nonce
  1822.     return false;
  1823. }
  1824. endif;
  1825.  
  1826. if ( !function_exists('wp_create_nonce') ) :
  1827. /**
  1828.  * Creates a cryptographic token tied to a specific action, user, and window of time.
  1829.  *
  1830.  * @since 2.0.3
  1831.  *
  1832.  * @param string|int $action Scalar value to add context to the nonce.
  1833.  * @return string The token.
  1834.  */
  1835. function wp_create_nonce($action = -1) {
  1836.     $user = wp_get_current_user();
  1837.     $uid = (int) $user->ID;
  1838.     if ( ! $uid ) {
  1839.         /** This filter is documented in wp-includes/pluggable.php */
  1840.         $uid = apply_filters( 'nonce_user_logged_out', $uid, $action );
  1841.     }
  1842.  
  1843.     $token = wp_get_session_token();
  1844.     $i = wp_nonce_tick();
  1845.  
  1846.     return substr( wp_hash( $i . '|' . $action . '|' . $uid . '|' . $token, 'nonce' ), -12, 10 );
  1847. }
  1848. endif;
  1849.  
  1850. if ( !function_exists('wp_salt') ) :
  1851. /**
  1852.  * Get salt to add to hashes.
  1853.  *
  1854.  * Salts are created using secret keys. Secret keys are located in two places:
  1855.  * in the database and in the wp-config.php file. The secret key in the database
  1856.  * is randomly generated and will be appended to the secret keys in wp-config.php.
  1857.  *
  1858.  * The secret keys in wp-config.php should be updated to strong, random keys to maximize
  1859.  * security. Below is an example of how the secret key constants are defined.
  1860.  * Do not paste this example directly into wp-config.php. Instead, have a
  1861.  * {@link https://api.wordpress.org/secret-key/1.1/salt/ secret key created} just
  1862.  * for you.
  1863.  *
  1864.  *     define('AUTH_KEY',         ' Xakm<o xQy rw4EMsLKM-?!T+,PFF})H4lzcW57AF0U@N@< >M%G4Yt>f`z]MON');
  1865.  *     define('SECURE_AUTH_KEY',  'LzJ}op]mr|6+![P}Ak:uNdJCJZd>(Hx.-Mh#Tz)pCIU#uGEnfFz|f ;;eU%/U^O~');
  1866.  *     define('LOGGED_IN_KEY',    '|i|Ux`9<p-h$aFf(qnT:sDO:D1P^wZ$$/Ra@miTJi9G;ddp_<q}6H1)o|a +&JCM');
  1867.  *     define('NONCE_KEY',        '%:R{[P|,s.KuMltH5}cI;/k<Gx~j!f0I)m_sIyu+&NJZ)-iO>z7X>QYR0Z_XnZ@|');
  1868.  *     define('AUTH_SALT',        'eZyT)-Naw]F8CwA*VaW#q*|.)g@o}||wf~@C-YSt}(dh_r6EbI#A,y|nU2{B#JBW');
  1869.  *     define('SECURE_AUTH_SALT', '!=oLUTXh,QW=H `}`L|9/^4-3 STz},T(w}W<I`.JjPi)<Bmf1v,HpGe}T1:Xt7n');
  1870.  *     define('LOGGED_IN_SALT',   '+XSqHc;@Q*K_b|Z?NC[3H!!EONbh.n<+=uKR:>*c(u`g~EJBf#8u#R{mUEZrozmm');
  1871.  *     define('NONCE_SALT',       'h`GXHhD>SLWVfg1(1(N{;.V!MoE(SfbA_ksP@&`+AycHcAV$+?@3q+rxV{%^VyKT');
  1872.  *
  1873.  * Salting passwords helps against tools which has stored hashed values of
  1874.  * common dictionary strings. The added values makes it harder to crack.
  1875.  *
  1876.  * @since 2.5.0
  1877.  *
  1878.  * @link https://api.wordpress.org/secret-key/1.1/salt/ Create secrets for wp-config.php
  1879.  *
  1880.  * @staticvar array $cached_salts
  1881.  * @staticvar array $duplicated_keys
  1882.  *
  1883.  * @param string $scheme Authentication scheme (auth, secure_auth, logged_in, nonce)
  1884.  * @return string Salt value
  1885.  */
  1886. function wp_salt( $scheme = 'auth' ) {
  1887.     static $cached_salts = array();
  1888.     if ( isset( $cached_salts[ $scheme ] ) ) {
  1889.         /**
  1890.          * Filter the WordPress salt.
  1891.          *
  1892.          * @since 2.5.0
  1893.          *
  1894.          * @param string $cached_salt Cached salt for the given scheme.
  1895.          * @param string $scheme      Authentication scheme. Values include 'auth',
  1896.          *                            'secure_auth', 'logged_in', and 'nonce'.
  1897.          */
  1898.         return apply_filters( 'salt', $cached_salts[ $scheme ], $scheme );
  1899.     }
  1900.  
  1901.     static $duplicated_keys;
  1902.     if ( null === $duplicated_keys ) {
  1903.         $duplicated_keys = array( 'put your unique phrase here' => true );
  1904.         foreach ( array( 'AUTH', 'SECURE_AUTH', 'LOGGED_IN', 'NONCE', 'SECRET' ) as $first ) {
  1905.             foreach ( array( 'KEY', 'SALT' ) as $second ) {
  1906.                 if ( ! defined( "{$first}_{$second}" ) ) {
  1907.                     continue;
  1908.                 }
  1909.                 $value = constant( "{$first}_{$second}" );
  1910.                 $duplicated_keys[ $value ] = isset( $duplicated_keys[ $value ] );
  1911.             }
  1912.         }
  1913.     }
  1914.  
  1915.     $values = array(
  1916.         'key' => '',
  1917.         'salt' => ''
  1918.     );
  1919.     if ( defined( 'SECRET_KEY' ) && SECRET_KEY && empty( $duplicated_keys[ SECRET_KEY ] ) ) {
  1920.         $values['key'] = SECRET_KEY;
  1921.     }
  1922.     if ( 'auth' == $scheme && defined( 'SECRET_SALT' ) && SECRET_SALT && empty( $duplicated_keys[ SECRET_SALT ] ) ) {
  1923.         $values['salt'] = SECRET_SALT;
  1924.     }
  1925.  
  1926.     if ( in_array( $scheme, array( 'auth', 'secure_auth', 'logged_in', 'nonce' ) ) ) {
  1927.         foreach ( array( 'key', 'salt' ) as $type ) {
  1928.             $const = strtoupper( "{$scheme}_{$type}" );
  1929.             if ( defined( $const ) && constant( $const ) && empty( $duplicated_keys[ constant( $const ) ] ) ) {
  1930.                 $values[ $type ] = constant( $const );
  1931.             } elseif ( ! $values[ $type ] ) {
  1932.                 $values[ $type ] = get_site_option( "{$scheme}_{$type}" );
  1933.                 if ( ! $values[ $type ] ) {
  1934.                     $values[ $type ] = wp_generate_password( 64, true, true );
  1935.                     update_site_option( "{$scheme}_{$type}", $values[ $type ] );
  1936.                 }
  1937.             }
  1938.         }
  1939.     } else {
  1940.         if ( ! $values['key'] ) {
  1941.             $values['key'] = get_site_option( 'secret_key' );
  1942.             if ( ! $values['key'] ) {
  1943.                 $values['key'] = wp_generate_password( 64, true, true );
  1944.                 update_site_option( 'secret_key', $values['key'] );
  1945.             }
  1946.         }
  1947.         $values['salt'] = hash_hmac( 'md5', $scheme, $values['key'] );
  1948.     }
  1949.  
  1950.     $cached_salts[ $scheme ] = $values['key'] . $values['salt'];
  1951.  
  1952.     /** This filter is documented in wp-includes/pluggable.php */
  1953.     return apply_filters( 'salt', $cached_salts[ $scheme ], $scheme );
  1954. }
  1955. endif;
  1956.  
  1957. if ( !function_exists('wp_hash') ) :
  1958. /**
  1959.  * Get hash of given string.
  1960.  *
  1961.  * @since 2.0.3
  1962.  *
  1963.  * @param string $data Plain text to hash
  1964.  * @return string Hash of $data
  1965.  */
  1966. function wp_hash($data, $scheme = 'auth') {
  1967.     $salt = wp_salt($scheme);
  1968.  
  1969.     return hash_hmac('md5', $data, $salt);
  1970. }
  1971. endif;
  1972.  
  1973. if ( !function_exists('wp_hash_password') ) :
  1974. /**
  1975.  * Create a hash (encrypt) of a plain text password.
  1976.  *
  1977.  * For integration with other applications, this function can be overwritten to
  1978.  * instead use the other package password checking algorithm.
  1979.  *
  1980.  * @since 2.5.0
  1981.  *
  1982.  * @global PasswordHash $wp_hasher PHPass object
  1983.  *
  1984.  * @param string $password Plain text user password to hash
  1985.  * @return string The hash string of the password
  1986.  */
  1987. function wp_hash_password($password) {
  1988.     global $wp_hasher;
  1989.  
  1990.     if ( empty($wp_hasher) ) {
  1991.         require_once( ABSPATH . WPINC . '/class-phpass.php');
  1992.         // By default, use the portable hash from phpass
  1993.         $wp_hasher = new PasswordHash(8, true);
  1994.     }
  1995.  
  1996.     return $wp_hasher->HashPassword( trim( $password ) );
  1997. }
  1998. endif;
  1999.  
  2000. if ( !function_exists('wp_check_password') ) :
  2001. /**
  2002.  * Checks the plaintext password against the encrypted Password.
  2003.  *
  2004.  * Maintains compatibility between old version and the new cookie authentication
  2005.  * protocol using PHPass library. The $hash parameter is the encrypted password
  2006.  * and the function compares the plain text password when encrypted similarly
  2007.  * against the already encrypted password to see if they match.
  2008.  *
  2009.  * For integration with other applications, this function can be overwritten to
  2010.  * instead use the other package password checking algorithm.
  2011.  *
  2012.  * @since 2.5.0
  2013.  *
  2014.  * @global PasswordHash $wp_hasher PHPass object used for checking the password
  2015.  *  against the $hash + $password
  2016.  * @uses PasswordHash::CheckPassword
  2017.  *
  2018.  * @param string $password Plaintext user's password
  2019.  * @param string $hash     Hash of the user's password to check against.
  2020.  * @return bool False, if the $password does not match the hashed password
  2021.  */
  2022. function wp_check_password($password, $hash, $user_id = '') {
  2023.     global $wp_hasher;
  2024.  
  2025.     // If the hash is still md5...
  2026.     if ( strlen($hash) <= 32 ) {
  2027.         $check = hash_equals( $hash, md5( $password ) );
  2028.         if ( $check && $user_id ) {
  2029.             // Rehash using new hash.
  2030.             wp_set_password($password, $user_id);
  2031.             $hash = wp_hash_password($password);
  2032.         }
  2033.  
  2034.         /**
  2035.          * Filter whether the plaintext password matches the encrypted password.
  2036.          *
  2037.          * @since 2.5.0
  2038.          *
  2039.          * @param bool   $check    Whether the passwords match.
  2040.          * @param string $password The plaintext password.
  2041.          * @param string $hash     The hashed password.
  2042.          * @param int    $user_id  User ID.
  2043.          */
  2044.         return apply_filters( 'check_password', $check, $password, $hash, $user_id );
  2045.     }
  2046.  
  2047.     // If the stored hash is longer than an MD5, presume the
  2048.     // new style phpass portable hash.
  2049.     if ( empty($wp_hasher) ) {
  2050.         require_once( ABSPATH . WPINC . '/class-phpass.php');
  2051.         // By default, use the portable hash from phpass
  2052.         $wp_hasher = new PasswordHash(8, true);
  2053.     }
  2054.  
  2055.     $check = $wp_hasher->CheckPassword($password, $hash);
  2056.  
  2057.     /** This filter is documented in wp-includes/pluggable.php */
  2058.     return apply_filters( 'check_password', $check, $password, $hash, $user_id );
  2059. }
  2060. endif;
  2061.  
  2062. if ( !function_exists('wp_generate_password') ) :
  2063. /**
  2064.  * Generates a random password drawn from the defined set of characters.
  2065.  *
  2066.  * @since 2.5.0
  2067.  *
  2068.  * @param int  $length              Optional. The length of password to generate. Default 12.
  2069.  * @param bool $special_chars       Optional. Whether to include standard special characters.
  2070.  *                                  Default true.
  2071.  * @param bool $extra_special_chars Optional. Whether to include other special characters.
  2072.  *                                  Used when generating secret keys and salts. Default false.
  2073.  * @return string The random password.
  2074.  */
  2075. function wp_generate_password( $length = 12, $special_chars = true, $extra_special_chars = false ) {
  2076.     $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  2077.     if ( $special_chars )
  2078.         $chars .= '!@#$%^&*()';
  2079.     if ( $extra_special_chars )
  2080.         $chars .= '-_ []{}<>~`+=,.;:/?|';
  2081.  
  2082.     $password = '';
  2083.     for ( $i = 0; $i < $length; $i++ ) {
  2084.         $password .= substr($chars, wp_rand(0, strlen($chars) - 1), 1);
  2085.     }
  2086.  
  2087.     /**
  2088.      * Filter the randomly-generated password.
  2089.      *
  2090.      * @since 3.0.0
  2091.      *
  2092.      * @param string $password The generated password.
  2093.      */
  2094.     return apply_filters( 'random_password', $password );
  2095. }
  2096. endif;
  2097.  
  2098. if ( !function_exists('wp_rand') ) :
  2099. /**
  2100.  * Generates a random number
  2101.  *
  2102.  * @since 2.6.2
  2103.  *
  2104.  * @global string $rnd_value
  2105.  * @staticvar string $seed
  2106.  *
  2107.  * @param int $min Lower limit for the generated number
  2108.  * @param int $max Upper limit for the generated number
  2109.  * @return int A random number between min and max
  2110.  */
  2111. function wp_rand( $min = 0, $max = 0 ) {
  2112.     global $rnd_value;
  2113.  
  2114.     // Reset $rnd_value after 14 uses
  2115.     // 32(md5) + 40(sha1) + 40(sha1) / 8 = 14 random numbers from $rnd_value
  2116.     if ( strlen($rnd_value) < 8 ) {
  2117.         if ( defined( 'WP_SETUP_CONFIG' ) )
  2118.             static $seed = '';
  2119.         else
  2120.             $seed = get_transient('random_seed');
  2121.         $rnd_value = md5( uniqid(microtime() . mt_rand(), true ) . $seed );
  2122.         $rnd_value .= sha1($rnd_value);
  2123.         $rnd_value .= sha1($rnd_value . $seed);
  2124.         $seed = md5($seed . $rnd_value);
  2125.         if ( ! defined( 'WP_SETUP_CONFIG' ) && ! defined( 'WP_INSTALLING' ) ) {
  2126.             set_transient( 'random_seed', $seed );
  2127.         }
  2128.     }
  2129.  
  2130.     // Take the first 8 digits for our value
  2131.     $value = substr($rnd_value, 0, 8);
  2132.  
  2133.     // Strip the first eight, leaving the remainder for the next call to wp_rand().
  2134.     $rnd_value = substr($rnd_value, 8);
  2135.  
  2136.     $value = abs(hexdec($value));
  2137.  
  2138.     // Some misconfigured 32bit environments (Entropy PHP, for example) truncate integers larger than PHP_INT_MAX to PHP_INT_MAX rather than overflowing them to floats.
  2139.     $max_random_number = 3000000000 === 2147483647 ? (float) "4294967295" : 4294967295; // 4294967295 = 0xffffffff
  2140.  
  2141.     // Reduce the value to be within the min - max range
  2142.     if ( $max != 0 )
  2143.         $value = $min + ( $max - $min + 1 ) * $value / ( $max_random_number + 1 );
  2144.  
  2145.     return abs(intval($value));
  2146. }
  2147. endif;
  2148.  
  2149. if ( !function_exists('wp_set_password') ) :
  2150. /**
  2151.  * Updates the user's password with a new encrypted one.
  2152.  *
  2153.  * For integration with other applications, this function can be overwritten to
  2154.  * instead use the other package password checking algorithm.
  2155.  *
  2156.  * Please note: This function should be used sparingly and is really only meant for single-time
  2157.  * application. Leveraging this improperly in a plugin or theme could result in an endless loop
  2158.  * of password resets if precautions are not taken to ensure it does not execute on every page load.
  2159.  *
  2160.  * @since 2.5.0
  2161.  *
  2162.  * @global wpdb $wpdb WordPress database abstraction object.
  2163.  *
  2164.  * @param string $password The plaintext new user password
  2165.  * @param int    $user_id  User ID
  2166.  */
  2167. function wp_set_password( $password, $user_id ) {
  2168.     global $wpdb;
  2169.  
  2170.     $hash = wp_hash_password( $password );
  2171.     $wpdb->update($wpdb->users, array('user_pass' => $hash, 'user_activation_key' => ''), array('ID' => $user_id) );
  2172.  
  2173.     wp_cache_delete($user_id, 'users');
  2174. }
  2175. endif;
  2176.  
  2177. if ( !function_exists( 'get_avatar' ) ) :
  2178. /**
  2179.  * Retrieve the avatar `<img>` tag for a user, email address, MD5 hash, comment, or post.
  2180.  *
  2181.  * @since 2.5.0
  2182.  * @since 4.2.0 Optional `$args` parameter added.
  2183.  *
  2184.  * @param mixed $id_or_email The Gravatar to retrieve. Accepts a user_id, gravatar md5 hash,
  2185.  *                           user email, WP_User object, WP_Post object, or comment object.
  2186.  * @param int    $size       Optional. Height and width of the avatar image file in pixels. Default 96.
  2187.  * @param string $default    Optional. URL for the default image or a default type. Accepts '404'
  2188.  *                           (return a 404 instead of a default image), 'retro' (8bit), 'monsterid'
  2189.  *                           (monster), 'wavatar' (cartoon face), 'indenticon' (the "quilt"),
  2190.  *                           'mystery', 'mm', or 'mysterman' (The Oyster Man), 'blank' (transparent GIF),
  2191.  *                           or 'gravatar_default' (the Gravatar logo). Default is the value of the
  2192.  *                           'avatar_default' option, with a fallback of 'mystery'.
  2193.  * @param string $alt        Optional. Alternative text to use in &lt;img&gt; tag. Default empty.
  2194.  * @param array  $args       {
  2195.  *     Optional. Extra arguments to retrieve the avatar.
  2196.  *
  2197.  *     @type int          $height        Display height of the avatar in pixels. Defaults to $size.
  2198.  *     @type int          $width         Display width of the avatar in pixels. Defaults to $size.
  2199.  *     @type bool         $force_default Whether to always show the default image, never the Gravatar. Default false.
  2200.  *     @type string       $rating        What rating to display avatars up to. Accepts 'G', 'PG', 'R', 'X', and are
  2201.  *                                       judged in that order. Default is the value of the 'avatar_rating' option.
  2202.  *     @type string       $scheme        URL scheme to use. See set_url_scheme() for accepted values.
  2203.  *                                       Default null.
  2204.  *     @type array|string $class         Array or string of additional classes to add to the &lt;img&gt; element.
  2205.  *                                       Default null.
  2206.  *     @type bool         $force_display Whether to always show the avatar - ignores the show_avatars option.
  2207.  *                                       Default false.
  2208.  *     @type string       $extra_attr    HTML attributes to insert in the IMG element. Is not sanitized. Default empty.
  2209.  * }
  2210.  * @return false|string `<img>` tag for the user's avatar. False on failure.
  2211.  */
  2212. function get_avatar( $id_or_email, $size = 96, $default = '', $alt = '', $args = null ) {
  2213.     $defaults = array(
  2214.         // get_avatar_data() args.
  2215.         'size'          => 96,
  2216.         'height'        => null,
  2217.         'width'         => null,
  2218.         'default'       => get_option( 'avatar_default', 'mystery' ),
  2219.         'force_default' => false,
  2220.         'rating'        => get_option( 'avatar_rating' ),
  2221.         'scheme'        => null,
  2222.         'alt'           => '',
  2223.         'class'         => null,
  2224.         'force_display' => false,
  2225.         'extra_attr'    => '',
  2226.     );
  2227.  
  2228.  
  2229.     if ( empty( $args ) ) {
  2230.         $args = array();
  2231.     }
  2232.  
  2233.     $args['size']    = (int) $size;
  2234.     $args['default'] = $default;
  2235.     $args['alt']     = $alt;
  2236.  
  2237.     $args = wp_parse_args( $args, $defaults );
  2238.  
  2239.     if ( empty( $args['height'] ) ) {
  2240.         $args['height'] = $args['size'];
  2241.     }
  2242.     if ( empty( $args['width'] ) ) {
  2243.         $args['width'] = $args['size'];
  2244.     }
  2245.  
  2246.     /**
  2247.      * Filter whether to retrieve the avatar URL early.
  2248.      *
  2249.      * Passing a non-null value will effectively short-circuit get_avatar(), passing
  2250.      * the value through the {@see 'pre_get_avatar'} filter and returning early.
  2251.      *
  2252.      * @since 4.2.0
  2253.      *
  2254.      * @param string            $avatar      HTML for the user's avatar. Default null.
  2255.      * @param int|object|string $id_or_email A user ID, email address, or comment object.
  2256.      * @param array             $args        Arguments passed to get_avatar_url(), after processing.
  2257.      */
  2258.     $avatar = apply_filters( 'pre_get_avatar', null, $id_or_email, $args );
  2259.  
  2260.     if ( ! is_null( $avatar ) ) {
  2261.         /** This filter is documented in wp-includes/pluggable.php */
  2262.         return apply_filters( 'get_avatar', $avatar, $id_or_email, $args['size'], $args['default'], $args['alt'], $args );
  2263.     }
  2264.  
  2265.     if ( ! $args['force_display'] && ! get_option( 'show_avatars' ) ) {
  2266.         return false;
  2267.     }
  2268.  
  2269.     $url2x = get_avatar_url( $id_or_email, array_merge( $args, array( 'size' => $args['size'] * 2 ) ) );
  2270.  
  2271.     $args = get_avatar_data( $id_or_email, $args );
  2272.  
  2273.     $url = $args['url'];
  2274.  
  2275.     if ( ! $url || is_wp_error( $url ) ) {
  2276.         return false;
  2277.     }
  2278.  
  2279.     $class = array( 'avatar', 'avatar-' . (int) $args['size'], 'photo' );
  2280.  
  2281.     if ( ! $args['found_avatar'] || $args['force_default'] ) {
  2282.         $class[] = 'avatar-default';
  2283.     }
  2284.  
  2285.     if ( $args['class'] ) {
  2286.         if ( is_array( $args['class'] ) ) {
  2287.             $class = array_merge( $class, $args['class'] );
  2288.         } else {
  2289.             $class[] = $args['class'];
  2290.         }
  2291.     }
  2292.  
  2293.     $avatar = sprintf(
  2294.         "<img alt='%s' src='%s' srcset='%s' class='%s' height='%d' width='%d' %s/>",
  2295.         esc_attr( $args['alt'] ),
  2296.         esc_url( $url ),
  2297.         esc_attr( "$url2x 2x" ),
  2298.         esc_attr( join( ' ', $class ) ),
  2299.         (int) $args['height'],
  2300.         (int) $args['width'],
  2301.         $args['extra_attr']
  2302.     );
  2303.  
  2304.     /**
  2305.      * Filter the avatar to retrieve.
  2306.      *
  2307.      * @since 2.5.0
  2308.      * @since 4.2.0 The `$args` parameter was added.
  2309.      *
  2310.      * @param string            $avatar      &lt;img&gt; tag for the user's avatar.
  2311.      * @param int|object|string $id_or_email A user ID, email address, or comment object.
  2312.      * @param int               $size        Square avatar width and height in pixels to retrieve.
  2313.      * @param string            $alt         Alternative text to use in the avatar image tag.
  2314.      *                                       Default empty.
  2315.      * @param array             $args        Arguments passed to get_avatar_data(), after processing.
  2316.      */
  2317.     return apply_filters( 'get_avatar', $avatar, $id_or_email, $args['size'], $args['default'], $args['alt'], $args );
  2318. }
  2319. endif;
  2320.  
  2321. if ( !function_exists( 'wp_text_diff' ) ) :
  2322. /**
  2323.  * Displays a human readable HTML representation of the difference between two strings.
  2324.  *
  2325.  * The Diff is available for getting the changes between versions. The output is
  2326.  * HTML, so the primary use is for displaying the changes. If the two strings
  2327.  * are equivalent, then an empty string will be returned.
  2328.  *
  2329.  * The arguments supported and can be changed are listed below.
  2330.  *
  2331.  * 'title' : Default is an empty string. Titles the diff in a manner compatible
  2332.  *      with the output.
  2333.  * 'title_left' : Default is an empty string. Change the HTML to the left of the
  2334.  *      title.
  2335.  * 'title_right' : Default is an empty string. Change the HTML to the right of
  2336.  *      the title.
  2337.  *
  2338.  * @since 2.6.0
  2339.  *
  2340.  * @see wp_parse_args() Used to change defaults to user defined settings.
  2341.  * @uses Text_Diff
  2342.  * @uses WP_Text_Diff_Renderer_Table
  2343.  *
  2344.  * @param string       $left_string  "old" (left) version of string
  2345.  * @param string       $right_string "new" (right) version of string
  2346.  * @param string|array $args         Optional. Change 'title', 'title_left', and 'title_right' defaults.
  2347.  * @return string Empty string if strings are equivalent or HTML with differences.
  2348.  */
  2349. function wp_text_diff( $left_string, $right_string, $args = null ) {
  2350.     $defaults = array( 'title' => '', 'title_left' => '', 'title_right' => '' );
  2351.     $args = wp_parse_args( $args, $defaults );
  2352.  
  2353.     if ( !class_exists( 'WP_Text_Diff_Renderer_Table' ) )
  2354.         require( ABSPATH . WPINC . '/wp-diff.php' );
  2355.  
  2356.     $left_string  = normalize_whitespace($left_string);
  2357.     $right_string = normalize_whitespace($right_string);
  2358.  
  2359.     $left_lines  = explode("\n", $left_string);
  2360.     $right_lines = explode("\n", $right_string);
  2361.     $text_diff = new Text_Diff($left_lines, $right_lines);
  2362.     $renderer  = new WP_Text_Diff_Renderer_Table( $args );
  2363.     $diff = $renderer->render($text_diff);
  2364.     if ( !$diff )
  2365.         return '';
  2366.  
  2367.     $r  = "<table class='diff'>\n";
  2368.  
  2369.     if ( ! empty( $args[ 'show_split_view' ] ) ) {
  2370.         $r .= "<col class='content diffsplit left' /><col class='content diffsplit middle' /><col class='content diffsplit right' />";
  2371.     } else {
  2372.         $r .= "<col class='content' />";
  2373.     }
  2374.  
  2375.     if ( $args['title'] || $args['title_left'] || $args['title_right'] )
  2376.         $r .= "<thead>";
  2377.     if ( $args['title'] )
  2378.         $r .= "<tr class='diff-title'><th colspan='4'>$args[title]</th></tr>\n";
  2379.     if ( $args['title_left'] || $args['title_right'] ) {
  2380.         $r .= "<tr class='diff-sub-title'>\n";
  2381.         $r .= "\t<td></td><th>$args[title_left]</th>\n";
  2382.         $r .= "\t<td></td><th>$args[title_right]</th>\n";
  2383.         $r .= "</tr>\n";
  2384.     }
  2385.     if ( $args['title'] || $args['title_left'] || $args['title_right'] )
  2386.         $r .= "</thead>\n";
  2387.     $r .= "<tbody>\n$diff\n</tbody>\n";
  2388.     $r .= "</table>";
  2389.     return $r;
  2390. }
  2391. endif;
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top