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


Generated: Mon Jul 22 01:00:03 2019 Cross-referenced by PHPXref 0.7.1