[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

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

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


Generated : Fri Aug 19 08:20:02 2022 Cross-referenced by PHPXref