[ Index ]

PHP Cross Reference of WordPress

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


Generated: Sun May 31 01:00:03 2020 Cross-referenced by PHPXref 0.7.1