[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

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


Generated: Mon Jun 17 08:20:02 2019 Cross-referenced by PHPXref 0.7