[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> pluggable.php (source)

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


Generated : Fri Oct 30 08:20:01 2020 Cross-referenced by PHPXref