[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

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


Generated: Sat Sep 21 01:00:03 2019 Cross-referenced by PHPXref 0.7.1