[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

   1  <?php
   2  /**
   3   * These functions can be replaced via plugins. If plugins do not redefine these
   4   * functions, then these will be used instead.
   5   *
   6   * @package WordPress
   7   */
   8  
   9  if ( ! function_exists( 'wp_set_current_user' ) ) :
  10      /**
  11       * Changes the current user by ID or name.
  12       *
  13       * Set $id to null and specify a name if you do not know a user's ID.
  14       *
  15       * Some WordPress functionality is based on the current user and not based on
  16       * the signed in user. Therefore, it opens the ability to edit and perform
  17       * actions on users who aren't signed in.
  18       *
  19       * @since 2.0.3
  20       *
  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       * Retrieve 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       * Retrieve 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       * Retrieve 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       * Retrieve 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          $clean = _get_non_cached_ids( $user_ids, 'users' );
 136  
 137          if ( empty( $clean ) ) {
 138              return;
 139          }
 140  
 141          $list = implode( ',', $clean );
 142  
 143          $users = $wpdb->get_results( "SELECT * FROM $wpdb->users WHERE ID IN ($list)" );
 144  
 145          $ids = array();
 146          foreach ( $users as $user ) {
 147              update_user_caches( $user );
 148              $ids[] = $user->ID;
 149          }
 150          update_meta_cache( 'user', $ids );
 151      }
 152  endif;
 153  
 154  if ( ! function_exists( 'wp_mail' ) ) :
 155      /**
 156       * Sends an email, similar to PHP's mail function.
 157       *
 158       * A true return value does not automatically mean that the user received the
 159       * email successfully. It just only means that the method used was able to
 160       * process the request without any errors.
 161       *
 162       * The default content type is `text/plain` which does not allow using HTML.
 163       * However, you can set the content type of the email by using the
 164       * {@see 'wp_mail_content_type'} filter.
 165       *
 166       * The default charset is based on the charset used on the blog. The charset can
 167       * be set using the {@see 'wp_mail_charset'} filter.
 168       *
 169       * @since 1.2.1
 170       * @since 5.5.0 is_email() is used for email validation,
 171       *              instead of PHPMailer's default validator.
 172       *
 173       * @global PHPMailer\PHPMailer\PHPMailer $phpmailer
 174       *
 175       * @param string|string[] $to          Array or comma-separated list of email addresses to send message.
 176       * @param string          $subject     Email subject.
 177       * @param string          $message     Message contents.
 178       * @param string|string[] $headers     Optional. Additional headers.
 179       * @param string|string[] $attachments Optional. Paths to files to attach.
 180       * @return bool Whether the email was sent successfully.
 181       */
 182  	function wp_mail( $to, $subject, $message, $headers = '', $attachments = array() ) {
 183          // Compact the input, apply the filters, and extract them back out.
 184  
 185          /**
 186           * Filters the wp_mail() arguments.
 187           *
 188           * @since 2.2.0
 189           *
 190           * @param array $args {
 191           *     Array of the `wp_mail()` arguments.
 192           *
 193           *     @type string|string[] $to          Array or comma-separated list of email addresses to send message.
 194           *     @type string          $subject     Email subject.
 195           *     @type string          $message     Message contents.
 196           *     @type string|string[] $headers     Additional headers.
 197           *     @type string|string[] $attachments Paths to files to attach.
 198           * }
 199           */
 200          $atts = apply_filters( 'wp_mail', compact( 'to', 'subject', 'message', 'headers', 'attachments' ) );
 201  
 202          /**
 203           * Filters whether to preempt sending an email.
 204           *
 205           * Returning a non-null value will short-circuit {@see wp_mail()}, returning
 206           * that value instead. A boolean return value should be used to indicate whether
 207           * the email was successfully sent.
 208           *
 209           * @since 5.7.0
 210           *
 211           * @param null|bool $return Short-circuit return value.
 212           * @param array     $atts {
 213           *     Array of the `wp_mail()` arguments.
 214           *
 215           *     @type string|string[] $to          Array or comma-separated list of email addresses to send message.
 216           *     @type string          $subject     Email subject.
 217           *     @type string          $message     Message contents.
 218           *     @type string|string[] $headers     Additional headers.
 219           *     @type string|string[] $attachments Paths to files to attach.
 220           * }
 221           */
 222          $pre_wp_mail = apply_filters( 'pre_wp_mail', null, $atts );
 223  
 224          if ( null !== $pre_wp_mail ) {
 225              return $pre_wp_mail;
 226          }
 227  
 228          if ( isset( $atts['to'] ) ) {
 229              $to = $atts['to'];
 230          }
 231  
 232          if ( ! is_array( $to ) ) {
 233              $to = explode( ',', $to );
 234          }
 235  
 236          if ( isset( $atts['subject'] ) ) {
 237              $subject = $atts['subject'];
 238          }
 239  
 240          if ( isset( $atts['message'] ) ) {
 241              $message = $atts['message'];
 242          }
 243  
 244          if ( isset( $atts['headers'] ) ) {
 245              $headers = $atts['headers'];
 246          }
 247  
 248          if ( isset( $atts['attachments'] ) ) {
 249              $attachments = $atts['attachments'];
 250          }
 251  
 252          if ( ! is_array( $attachments ) ) {
 253              $attachments = explode( "\n", str_replace( "\r\n", "\n", $attachments ) );
 254          }
 255          global $phpmailer;
 256  
 257          // (Re)create it, if it's gone missing.
 258          if ( ! ( $phpmailer instanceof PHPMailer\PHPMailer\PHPMailer ) ) {
 259              require_once  ABSPATH . WPINC . '/PHPMailer/PHPMailer.php';
 260              require_once  ABSPATH . WPINC . '/PHPMailer/SMTP.php';
 261              require_once  ABSPATH . WPINC . '/PHPMailer/Exception.php';
 262              $phpmailer = new PHPMailer\PHPMailer\PHPMailer( true );
 263  
 264              $phpmailer::$validator = static function ( $email ) {
 265                  return (bool) is_email( $email );
 266              };
 267          }
 268  
 269          // Headers.
 270          $cc       = array();
 271          $bcc      = array();
 272          $reply_to = array();
 273  
 274          if ( empty( $headers ) ) {
 275              $headers = array();
 276          } else {
 277              if ( ! is_array( $headers ) ) {
 278                  // Explode the headers out, so this function can take
 279                  // both string headers and an array of headers.
 280                  $tempheaders = explode( "\n", str_replace( "\r\n", "\n", $headers ) );
 281              } else {
 282                  $tempheaders = $headers;
 283              }
 284              $headers = array();
 285  
 286              // If it's actually got contents.
 287              if ( ! empty( $tempheaders ) ) {
 288                  // Iterate through the raw headers.
 289                  foreach ( (array) $tempheaders as $header ) {
 290                      if ( strpos( $header, ':' ) === false ) {
 291                          if ( false !== stripos( $header, 'boundary=' ) ) {
 292                              $parts    = preg_split( '/boundary=/i', trim( $header ) );
 293                              $boundary = trim( str_replace( array( "'", '"' ), '', $parts[1] ) );
 294                          }
 295                          continue;
 296                      }
 297                      // Explode them out.
 298                      list( $name, $content ) = explode( ':', trim( $header ), 2 );
 299  
 300                      // Cleanup crew.
 301                      $name    = trim( $name );
 302                      $content = trim( $content );
 303  
 304                      switch ( strtolower( $name ) ) {
 305                          // Mainly for legacy -- process a "From:" header if it's there.
 306                          case 'from':
 307                              $bracket_pos = strpos( $content, '<' );
 308                              if ( false !== $bracket_pos ) {
 309                                  // Text before the bracketed email is the "From" name.
 310                                  if ( $bracket_pos > 0 ) {
 311                                      $from_name = substr( $content, 0, $bracket_pos - 1 );
 312                                      $from_name = str_replace( '"', '', $from_name );
 313                                      $from_name = trim( $from_name );
 314                                  }
 315  
 316                                  $from_email = substr( $content, $bracket_pos + 1 );
 317                                  $from_email = str_replace( '>', '', $from_email );
 318                                  $from_email = trim( $from_email );
 319  
 320                                  // Avoid setting an empty $from_email.
 321                              } elseif ( '' !== trim( $content ) ) {
 322                                  $from_email = trim( $content );
 323                              }
 324                              break;
 325                          case 'content-type':
 326                              if ( strpos( $content, ';' ) !== false ) {
 327                                  list( $type, $charset_content ) = explode( ';', $content );
 328                                  $content_type                   = trim( $type );
 329                                  if ( false !== stripos( $charset_content, 'charset=' ) ) {
 330                                      $charset = trim( str_replace( array( 'charset=', '"' ), '', $charset_content ) );
 331                                  } elseif ( false !== stripos( $charset_content, 'boundary=' ) ) {
 332                                      $boundary = trim( str_replace( array( 'BOUNDARY=', 'boundary=', '"' ), '', $charset_content ) );
 333                                      $charset  = '';
 334                                  }
 335  
 336                                  // Avoid setting an empty $content_type.
 337                              } elseif ( '' !== trim( $content ) ) {
 338                                  $content_type = trim( $content );
 339                              }
 340                              break;
 341                          case 'cc':
 342                              $cc = array_merge( (array) $cc, explode( ',', $content ) );
 343                              break;
 344                          case 'bcc':
 345                              $bcc = array_merge( (array) $bcc, explode( ',', $content ) );
 346                              break;
 347                          case 'reply-to':
 348                              $reply_to = array_merge( (array) $reply_to, explode( ',', $content ) );
 349                              break;
 350                          default:
 351                              // Add it to our grand headers array.
 352                              $headers[ trim( $name ) ] = trim( $content );
 353                              break;
 354                      }
 355                  }
 356              }
 357          }
 358  
 359          // Empty out the values that may be set.
 360          $phpmailer->clearAllRecipients();
 361          $phpmailer->clearAttachments();
 362          $phpmailer->clearCustomHeaders();
 363          $phpmailer->clearReplyTos();
 364  
 365          // Set "From" name and email.
 366  
 367          // If we don't have a name from the input headers.
 368          if ( ! isset( $from_name ) ) {
 369              $from_name = 'WordPress';
 370          }
 371  
 372          /*
 373           * If we don't have an email from the input headers, default to wordpress@$sitename
 374           * Some hosts will block outgoing mail from this address if it doesn't exist,
 375           * but there's no easy alternative. Defaulting to admin_email might appear to be
 376           * another option, but some hosts may refuse to relay mail from an unknown domain.
 377           * See https://core.trac.wordpress.org/ticket/5007.
 378           */
 379          if ( ! isset( $from_email ) ) {
 380              // Get the site domain and get rid of www.
 381              $sitename   = wp_parse_url( network_home_url(), PHP_URL_HOST );
 382              $from_email = 'wordpress@';
 383  
 384              if ( null !== $sitename ) {
 385                  if ( 'www.' === substr( $sitename, 0, 4 ) ) {
 386                      $sitename = substr( $sitename, 4 );
 387                  }
 388  
 389                  $from_email .= $sitename;
 390              }
 391          }
 392  
 393          /**
 394           * Filters the email address to send from.
 395           *
 396           * @since 2.2.0
 397           *
 398           * @param string $from_email Email address to send from.
 399           */
 400          $from_email = apply_filters( 'wp_mail_from', $from_email );
 401  
 402          /**
 403           * Filters the name to associate with the "from" email address.
 404           *
 405           * @since 2.3.0
 406           *
 407           * @param string $from_name Name associated with the "from" email address.
 408           */
 409          $from_name = apply_filters( 'wp_mail_from_name', $from_name );
 410  
 411          try {
 412              $phpmailer->setFrom( $from_email, $from_name, false );
 413          } catch ( PHPMailer\PHPMailer\Exception $e ) {
 414              $mail_error_data                             = compact( 'to', 'subject', 'message', 'headers', 'attachments' );
 415              $mail_error_data['phpmailer_exception_code'] = $e->getCode();
 416  
 417              /** This filter is documented in wp-includes/pluggable.php */
 418              do_action( 'wp_mail_failed', new WP_Error( 'wp_mail_failed', $e->getMessage(), $mail_error_data ) );
 419  
 420              return false;
 421          }
 422  
 423          // Set mail's subject and body.
 424          $phpmailer->Subject = $subject;
 425          $phpmailer->Body    = $message;
 426  
 427          // Set destination addresses, using appropriate methods for handling addresses.
 428          $address_headers = compact( 'to', 'cc', 'bcc', 'reply_to' );
 429  
 430          foreach ( $address_headers as $address_header => $addresses ) {
 431              if ( empty( $addresses ) ) {
 432                  continue;
 433              }
 434  
 435              foreach ( (array) $addresses as $address ) {
 436                  try {
 437                      // Break $recipient into name and address parts if in the format "Foo <bar@baz.com>".
 438                      $recipient_name = '';
 439  
 440                      if ( preg_match( '/(.*)<(.+)>/', $address, $matches ) ) {
 441                          if ( count( $matches ) == 3 ) {
 442                              $recipient_name = $matches[1];
 443                              $address        = $matches[2];
 444                          }
 445                      }
 446  
 447                      switch ( $address_header ) {
 448                          case 'to':
 449                              $phpmailer->addAddress( $address, $recipient_name );
 450                              break;
 451                          case 'cc':
 452                              $phpmailer->addCc( $address, $recipient_name );
 453                              break;
 454                          case 'bcc':
 455                              $phpmailer->addBcc( $address, $recipient_name );
 456                              break;
 457                          case 'reply_to':
 458                              $phpmailer->addReplyTo( $address, $recipient_name );
 459                              break;
 460                      }
 461                  } catch ( PHPMailer\PHPMailer\Exception $e ) {
 462                      continue;
 463                  }
 464              }
 465          }
 466  
 467          // Set to use PHP's mail().
 468          $phpmailer->isMail();
 469  
 470          // Set Content-Type and charset.
 471  
 472          // If we don't have a content-type from the input headers.
 473          if ( ! isset( $content_type ) ) {
 474              $content_type = 'text/plain';
 475          }
 476  
 477          /**
 478           * Filters the wp_mail() content type.
 479           *
 480           * @since 2.3.0
 481           *
 482           * @param string $content_type Default wp_mail() content type.
 483           */
 484          $content_type = apply_filters( 'wp_mail_content_type', $content_type );
 485  
 486          $phpmailer->ContentType = $content_type;
 487  
 488          // Set whether it's plaintext, depending on $content_type.
 489          if ( 'text/html' === $content_type ) {
 490              $phpmailer->isHTML( true );
 491          }
 492  
 493          // If we don't have a charset from the input headers.
 494          if ( ! isset( $charset ) ) {
 495              $charset = get_bloginfo( 'charset' );
 496          }
 497  
 498          /**
 499           * Filters the default wp_mail() charset.
 500           *
 501           * @since 2.3.0
 502           *
 503           * @param string $charset Default email charset.
 504           */
 505          $phpmailer->CharSet = apply_filters( 'wp_mail_charset', $charset );
 506  
 507          // Set custom headers.
 508          if ( ! empty( $headers ) ) {
 509              foreach ( (array) $headers as $name => $content ) {
 510                  // Only add custom headers not added automatically by PHPMailer.
 511                  if ( ! in_array( $name, array( 'MIME-Version', 'X-Mailer' ), true ) ) {
 512                      try {
 513                          $phpmailer->addCustomHeader( sprintf( '%1$s: %2$s', $name, $content ) );
 514                      } catch ( PHPMailer\PHPMailer\Exception $e ) {
 515                          continue;
 516                      }
 517                  }
 518              }
 519  
 520              if ( false !== stripos( $content_type, 'multipart' ) && ! empty( $boundary ) ) {
 521                  $phpmailer->addCustomHeader( sprintf( 'Content-Type: %s; boundary="%s"', $content_type, $boundary ) );
 522              }
 523          }
 524  
 525          if ( ! empty( $attachments ) ) {
 526              foreach ( $attachments as $attachment ) {
 527                  try {
 528                      $phpmailer->addAttachment( $attachment );
 529                  } catch ( PHPMailer\PHPMailer\Exception $e ) {
 530                      continue;
 531                  }
 532              }
 533          }
 534  
 535          /**
 536           * Fires after PHPMailer is initialized.
 537           *
 538           * @since 2.2.0
 539           *
 540           * @param PHPMailer $phpmailer The PHPMailer instance (passed by reference).
 541           */
 542          do_action_ref_array( 'phpmailer_init', array( &$phpmailer ) );
 543  
 544          $mail_data = compact( 'to', 'subject', 'message', 'headers', 'attachments' );
 545  
 546          // Send!
 547          try {
 548              $send = $phpmailer->send();
 549  
 550              /**
 551               * Fires after PHPMailer has successfully sent an email.
 552               *
 553               * The firing of this action does not necessarily mean that the recipient(s) received the
 554               * email successfully. It only means that the `send` method above was able to
 555               * process the request without any errors.
 556               *
 557               * @since 5.9.0
 558               *
 559               * @param array $mail_data {
 560               *     An array containing the email recipient(s), subject, message, headers, and attachments.
 561               *
 562               *     @type string[] $to          Email addresses to send message.
 563               *     @type string   $subject     Email subject.
 564               *     @type string   $message     Message contents.
 565               *     @type string[] $headers     Additional headers.
 566               *     @type string[] $attachments Paths to files to attach.
 567               * }
 568               */
 569              do_action( 'wp_mail_succeeded', $mail_data );
 570  
 571              return $send;
 572          } catch ( PHPMailer\PHPMailer\Exception $e ) {
 573              $mail_data['phpmailer_exception_code'] = $e->getCode();
 574  
 575              /**
 576               * Fires after a PHPMailer\PHPMailer\Exception is caught.
 577               *
 578               * @since 4.4.0
 579               *
 580               * @param WP_Error $error A WP_Error object with the PHPMailer\PHPMailer\Exception message, and an array
 581               *                        containing the mail recipient, subject, message, headers, and attachments.
 582               */
 583              do_action( 'wp_mail_failed', new WP_Error( 'wp_mail_failed', $e->getMessage(), $mail_data ) );
 584  
 585              return false;
 586          }
 587      }
 588  endif;
 589  
 590  if ( ! function_exists( 'wp_authenticate' ) ) :
 591      /**
 592       * Authenticate a user, confirming the login credentials are valid.
 593       *
 594       * @since 2.5.0
 595       * @since 4.5.0 `$username` now accepts an email address.
 596       *
 597       * @param string $username User's username or email address.
 598       * @param string $password User's password.
 599       * @return WP_User|WP_Error WP_User object if the credentials are valid,
 600       *                          otherwise WP_Error.
 601       */
 602  	function wp_authenticate( $username, $password ) {
 603          $username = sanitize_user( $username );
 604          $password = trim( $password );
 605  
 606          /**
 607           * Filters whether a set of user login credentials are valid.
 608           *
 609           * A WP_User object is returned if the credentials authenticate a user.
 610           * WP_Error or null otherwise.
 611           *
 612           * @since 2.8.0
 613           * @since 4.5.0 `$username` now accepts an email address.
 614           *
 615           * @param null|WP_User|WP_Error $user     WP_User if the user is authenticated.
 616           *                                        WP_Error or null otherwise.
 617           * @param string                $username Username or email address.
 618           * @param string                $password User password
 619           */
 620          $user = apply_filters( 'authenticate', null, $username, $password );
 621  
 622          if ( null == $user ) {
 623              // TODO: What should the error message be? (Or would these even happen?)
 624              // Only needed if all authentication handlers fail to return anything.
 625              $user = new WP_Error( 'authentication_failed', __( '<strong>Error</strong>: Invalid username, email address or incorrect password.' ) );
 626          }
 627  
 628          $ignore_codes = array( 'empty_username', 'empty_password' );
 629  
 630          if ( is_wp_error( $user ) && ! in_array( $user->get_error_code(), $ignore_codes, true ) ) {
 631              $error = $user;
 632  
 633              /**
 634               * Fires after a user login has failed.
 635               *
 636               * @since 2.5.0
 637               * @since 4.5.0 The value of `$username` can now be an email address.
 638               * @since 5.4.0 The `$error` parameter was added.
 639               *
 640               * @param string   $username Username or email address.
 641               * @param WP_Error $error    A WP_Error object with the authentication failure details.
 642               */
 643              do_action( 'wp_login_failed', $username, $error );
 644          }
 645  
 646          return $user;
 647      }
 648  endif;
 649  
 650  if ( ! function_exists( 'wp_logout' ) ) :
 651      /**
 652       * Log the current user out.
 653       *
 654       * @since 2.5.0
 655       */
 656  	function wp_logout() {
 657          $user_id = get_current_user_id();
 658  
 659          wp_destroy_current_session();
 660          wp_clear_auth_cookie();
 661          wp_set_current_user( 0 );
 662  
 663          /**
 664           * Fires after a user is logged out.
 665           *
 666           * @since 1.5.0
 667           * @since 5.5.0 Added the `$user_id` parameter.
 668           *
 669           * @param int $user_id ID of the user that was logged out.
 670           */
 671          do_action( 'wp_logout', $user_id );
 672      }
 673  endif;
 674  
 675  if ( ! function_exists( 'wp_validate_auth_cookie' ) ) :
 676      /**
 677       * Validates authentication cookie.
 678       *
 679       * The checks include making sure that the authentication cookie is set and
 680       * pulling in the contents (if $cookie is not used).
 681       *
 682       * Makes sure the cookie is not expired. Verifies the hash in cookie is what is
 683       * should be and compares the two.
 684       *
 685       * @since 2.5.0
 686       *
 687       * @global int $login_grace_period
 688       *
 689       * @param string $cookie Optional. If used, will validate contents instead of cookie's.
 690       * @param string $scheme Optional. The cookie scheme to use: 'auth', 'secure_auth', or 'logged_in'.
 691       * @return int|false User ID if valid cookie, false if invalid.
 692       */
 693  	function wp_validate_auth_cookie( $cookie = '', $scheme = '' ) {
 694          $cookie_elements = wp_parse_auth_cookie( $cookie, $scheme );
 695          if ( ! $cookie_elements ) {
 696              /**
 697               * Fires if an authentication cookie is malformed.
 698               *
 699               * @since 2.7.0
 700               *
 701               * @param string $cookie Malformed auth cookie.
 702               * @param string $scheme Authentication scheme. Values include 'auth', 'secure_auth',
 703               *                       or 'logged_in'.
 704               */
 705              do_action( 'auth_cookie_malformed', $cookie, $scheme );
 706              return false;
 707          }
 708  
 709          $scheme     = $cookie_elements['scheme'];
 710          $username   = $cookie_elements['username'];
 711          $hmac       = $cookie_elements['hmac'];
 712          $token      = $cookie_elements['token'];
 713          $expired    = $cookie_elements['expiration'];
 714          $expiration = $cookie_elements['expiration'];
 715  
 716          // Allow a grace period for POST and Ajax requests.
 717          if ( wp_doing_ajax() || 'POST' === $_SERVER['REQUEST_METHOD'] ) {
 718              $expired += HOUR_IN_SECONDS;
 719          }
 720  
 721          // Quick check to see if an honest cookie has expired.
 722          if ( $expired < time() ) {
 723              /**
 724               * Fires once an authentication cookie has expired.
 725               *
 726               * @since 2.7.0
 727               *
 728               * @param string[] $cookie_elements {
 729               *     Authentication cookie components. None of the components should be assumed
 730               *     to be valid as they come directly from a client-provided cookie value.
 731               *
 732               *     @type string $username   User's username.
 733               *     @type string $expiration The time the cookie expires as a UNIX timestamp.
 734               *     @type string $token      User's session token used.
 735               *     @type string $hmac       The security hash for the cookie.
 736               *     @type string $scheme     The cookie scheme to use.
 737               * }
 738               */
 739              do_action( 'auth_cookie_expired', $cookie_elements );
 740              return false;
 741          }
 742  
 743          $user = get_user_by( 'login', $username );
 744          if ( ! $user ) {
 745              /**
 746               * Fires if a bad username is entered in the user authentication process.
 747               *
 748               * @since 2.7.0
 749               *
 750               * @param string[] $cookie_elements {
 751               *     Authentication cookie components. None of the components should be assumed
 752               *     to be valid as they come directly from a client-provided cookie value.
 753               *
 754               *     @type string $username   User's username.
 755               *     @type string $expiration The time the cookie expires as a UNIX timestamp.
 756               *     @type string $token      User's session token used.
 757               *     @type string $hmac       The security hash for the cookie.
 758               *     @type string $scheme     The cookie scheme to use.
 759               * }
 760               */
 761              do_action( 'auth_cookie_bad_username', $cookie_elements );
 762              return false;
 763          }
 764  
 765          $pass_frag = substr( $user->user_pass, 8, 4 );
 766  
 767          $key = wp_hash( $username . '|' . $pass_frag . '|' . $expiration . '|' . $token, $scheme );
 768  
 769          // If ext/hash is not present, compat.php's hash_hmac() does not support sha256.
 770          $algo = function_exists( 'hash' ) ? 'sha256' : 'sha1';
 771          $hash = hash_hmac( $algo, $username . '|' . $expiration . '|' . $token, $key );
 772  
 773          if ( ! hash_equals( $hash, $hmac ) ) {
 774              /**
 775               * Fires if a bad authentication cookie hash is encountered.
 776               *
 777               * @since 2.7.0
 778               *
 779               * @param string[] $cookie_elements {
 780               *     Authentication cookie components. None of the components should be assumed
 781               *     to be valid as they come directly from a client-provided cookie value.
 782               *
 783               *     @type string $username   User's username.
 784               *     @type string $expiration The time the cookie expires as a UNIX timestamp.
 785               *     @type string $token      User's session token used.
 786               *     @type string $hmac       The security hash for the cookie.
 787               *     @type string $scheme     The cookie scheme to use.
 788               * }
 789               */
 790              do_action( 'auth_cookie_bad_hash', $cookie_elements );
 791              return false;
 792          }
 793  
 794          $manager = WP_Session_Tokens::get_instance( $user->ID );
 795          if ( ! $manager->verify( $token ) ) {
 796              /**
 797               * Fires if a bad session token is encountered.
 798               *
 799               * @since 4.0.0
 800               *
 801               * @param string[] $cookie_elements {
 802               *     Authentication cookie components. None of the components should be assumed
 803               *     to be valid as they come directly from a client-provided cookie value.
 804               *
 805               *     @type string $username   User's username.
 806               *     @type string $expiration The time the cookie expires as a UNIX timestamp.
 807               *     @type string $token      User's session token used.
 808               *     @type string $hmac       The security hash for the cookie.
 809               *     @type string $scheme     The cookie scheme to use.
 810               * }
 811               */
 812              do_action( 'auth_cookie_bad_session_token', $cookie_elements );
 813              return false;
 814          }
 815  
 816          // Ajax/POST grace period set above.
 817          if ( $expiration < time() ) {
 818              $GLOBALS['login_grace_period'] = 1;
 819          }
 820  
 821          /**
 822           * Fires once an authentication cookie has been validated.
 823           *
 824           * @since 2.7.0
 825           *
 826           * @param string[] $cookie_elements {
 827           *     Authentication cookie components.
 828           *
 829           *     @type string $username   User's username.
 830           *     @type string $expiration The time the cookie expires as a UNIX timestamp.
 831           *     @type string $token      User's session token used.
 832           *     @type string $hmac       The security hash for the cookie.
 833           *     @type string $scheme     The cookie scheme to use.
 834           * }
 835           * @param WP_User  $user            User object.
 836           */
 837          do_action( 'auth_cookie_valid', $cookie_elements, $user );
 838  
 839          return $user->ID;
 840      }
 841  endif;
 842  
 843  if ( ! function_exists( 'wp_generate_auth_cookie' ) ) :
 844      /**
 845       * Generates authentication cookie contents.
 846       *
 847       * @since 2.5.0
 848       * @since 4.0.0 The `$token` parameter was added.
 849       *
 850       * @param int    $user_id    User ID.
 851       * @param int    $expiration The time the cookie expires as a UNIX timestamp.
 852       * @param string $scheme     Optional. The cookie scheme to use: 'auth', 'secure_auth', or 'logged_in'.
 853       *                           Default 'auth'.
 854       * @param string $token      User's session token to use for this cookie.
 855       * @return string Authentication cookie contents. Empty string if user does not exist.
 856       */
 857  	function wp_generate_auth_cookie( $user_id, $expiration, $scheme = 'auth', $token = '' ) {
 858          $user = get_userdata( $user_id );
 859          if ( ! $user ) {
 860              return '';
 861          }
 862  
 863          if ( ! $token ) {
 864              $manager = WP_Session_Tokens::get_instance( $user_id );
 865              $token   = $manager->create( $expiration );
 866          }
 867  
 868          $pass_frag = substr( $user->user_pass, 8, 4 );
 869  
 870          $key = wp_hash( $user->user_login . '|' . $pass_frag . '|' . $expiration . '|' . $token, $scheme );
 871  
 872          // If ext/hash is not present, compat.php's hash_hmac() does not support sha256.
 873          $algo = function_exists( 'hash' ) ? 'sha256' : 'sha1';
 874          $hash = hash_hmac( $algo, $user->user_login . '|' . $expiration . '|' . $token, $key );
 875  
 876          $cookie = $user->user_login . '|' . $expiration . '|' . $token . '|' . $hash;
 877  
 878          /**
 879           * Filters the authentication cookie.
 880           *
 881           * @since 2.5.0
 882           * @since 4.0.0 The `$token` parameter was added.
 883           *
 884           * @param string $cookie     Authentication cookie.
 885           * @param int    $user_id    User ID.
 886           * @param int    $expiration The time the cookie expires as a UNIX timestamp.
 887           * @param string $scheme     Cookie scheme used. Accepts 'auth', 'secure_auth', or 'logged_in'.
 888           * @param string $token      User's session token used.
 889           */
 890          return apply_filters( 'auth_cookie', $cookie, $user_id, $expiration, $scheme, $token );
 891      }
 892  endif;
 893  
 894  if ( ! function_exists( 'wp_parse_auth_cookie' ) ) :
 895      /**
 896       * Parses a cookie into its components.
 897       *
 898       * @since 2.7.0
 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 encode 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       * Notify 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       * Notify 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       * Email 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          if ( 'user' !== $notify ) {
2115              $switched_locale = switch_to_locale( get_locale() );
2116  
2117              /* translators: %s: Site title. */
2118              $message = sprintf( __( 'New user registration on your site %s:' ), $blogname ) . "\r\n\r\n";
2119              /* translators: %s: User login. */
2120              $message .= sprintf( __( 'Username: %s' ), $user->user_login ) . "\r\n\r\n";
2121              /* translators: %s: User email address. */
2122              $message .= sprintf( __( 'Email: %s' ), $user->user_email ) . "\r\n";
2123  
2124              $wp_new_user_notification_email_admin = array(
2125                  'to'      => get_option( 'admin_email' ),
2126                  /* translators: New user registration notification email subject. %s: Site title. */
2127                  'subject' => __( '[%s] New User Registration' ),
2128                  'message' => $message,
2129                  'headers' => '',
2130              );
2131  
2132              /**
2133               * Filters the contents of the new user notification email sent to the site admin.
2134               *
2135               * @since 4.9.0
2136               *
2137               * @param array   $wp_new_user_notification_email_admin {
2138               *     Used to build wp_mail().
2139               *
2140               *     @type string $to      The intended recipient - site admin email address.
2141               *     @type string $subject The subject of the email.
2142               *     @type string $message The body of the email.
2143               *     @type string $headers The headers of the email.
2144               * }
2145               * @param WP_User $user     User object for new user.
2146               * @param string  $blogname The site title.
2147               */
2148              $wp_new_user_notification_email_admin = apply_filters( 'wp_new_user_notification_email_admin', $wp_new_user_notification_email_admin, $user, $blogname );
2149  
2150              wp_mail(
2151                  $wp_new_user_notification_email_admin['to'],
2152                  wp_specialchars_decode( sprintf( $wp_new_user_notification_email_admin['subject'], $blogname ) ),
2153                  $wp_new_user_notification_email_admin['message'],
2154                  $wp_new_user_notification_email_admin['headers']
2155              );
2156  
2157              if ( $switched_locale ) {
2158                  restore_previous_locale();
2159              }
2160          }
2161  
2162          // `$deprecated` was pre-4.3 `$plaintext_pass`. An empty `$plaintext_pass` didn't sent a user notification.
2163          if ( 'admin' === $notify || ( empty( $deprecated ) && empty( $notify ) ) ) {
2164              return;
2165          }
2166  
2167          $key = get_password_reset_key( $user );
2168          if ( is_wp_error( $key ) ) {
2169              return;
2170          }
2171  
2172          $switched_locale = switch_to_locale( get_user_locale( $user ) );
2173  
2174          /* translators: %s: User login. */
2175          $message  = sprintf( __( 'Username: %s' ), $user->user_login ) . "\r\n\r\n";
2176          $message .= __( 'To set your password, visit the following address:' ) . "\r\n\r\n";
2177          $message .= network_site_url( "wp-login.php?action=rp&key=$key&login=" . rawurlencode( $user->user_login ), 'login' ) . "\r\n\r\n";
2178  
2179          $message .= wp_login_url() . "\r\n";
2180  
2181          $wp_new_user_notification_email = array(
2182              'to'      => $user->user_email,
2183              /* translators: Login details notification email subject. %s: Site title. */
2184              'subject' => __( '[%s] Login Details' ),
2185              'message' => $message,
2186              'headers' => '',
2187          );
2188  
2189          /**
2190           * Filters the contents of the new user notification email sent to the new user.
2191           *
2192           * @since 4.9.0
2193           *
2194           * @param array   $wp_new_user_notification_email {
2195           *     Used to build wp_mail().
2196           *
2197           *     @type string $to      The intended recipient - New user email address.
2198           *     @type string $subject The subject of the email.
2199           *     @type string $message The body of the email.
2200           *     @type string $headers The headers of the email.
2201           * }
2202           * @param WP_User $user     User object for new user.
2203           * @param string  $blogname The site title.
2204           */
2205          $wp_new_user_notification_email = apply_filters( 'wp_new_user_notification_email', $wp_new_user_notification_email, $user, $blogname );
2206  
2207          wp_mail(
2208              $wp_new_user_notification_email['to'],
2209              wp_specialchars_decode( sprintf( $wp_new_user_notification_email['subject'], $blogname ) ),
2210              $wp_new_user_notification_email['message'],
2211              $wp_new_user_notification_email['headers']
2212          );
2213  
2214          if ( $switched_locale ) {
2215              restore_previous_locale();
2216          }
2217      }
2218  endif;
2219  
2220  if ( ! function_exists( 'wp_nonce_tick' ) ) :
2221      /**
2222       * Returns the time-dependent variable for nonce creation.
2223       *
2224       * A nonce has a lifespan of two ticks. Nonces in their second tick may be
2225       * updated, e.g. by autosave.
2226       *
2227       * @since 2.5.0
2228       *
2229       * @return float Float value rounded up to the next highest integer.
2230       */
2231  	function wp_nonce_tick() {
2232          /**
2233           * Filters the lifespan of nonces in seconds.
2234           *
2235           * @since 2.5.0
2236           *
2237           * @param int $lifespan Lifespan of nonces in seconds. Default 86,400 seconds, or one day.
2238           */
2239          $nonce_life = apply_filters( 'nonce_life', DAY_IN_SECONDS );
2240  
2241          return ceil( time() / ( $nonce_life / 2 ) );
2242      }
2243  endif;
2244  
2245  if ( ! function_exists( 'wp_verify_nonce' ) ) :
2246      /**
2247       * Verifies that a correct security nonce was used with time limit.
2248       *
2249       * A nonce is valid for 24 hours (by default).
2250       *
2251       * @since 2.0.3
2252       *
2253       * @param string     $nonce  Nonce value that was used for verification, usually via a form field.
2254       * @param string|int $action Should give context to what is taking place and be the same when nonce was created.
2255       * @return int|false 1 if the nonce is valid and generated between 0-12 hours ago,
2256       *                   2 if the nonce is valid and generated between 12-24 hours ago.
2257       *                   False if the nonce is invalid.
2258       */
2259  	function wp_verify_nonce( $nonce, $action = -1 ) {
2260          $nonce = (string) $nonce;
2261          $user  = wp_get_current_user();
2262          $uid   = (int) $user->ID;
2263          if ( ! $uid ) {
2264              /**
2265               * Filters whether the user who generated the nonce is logged out.
2266               *
2267               * @since 3.5.0
2268               *
2269               * @param int    $uid    ID of the nonce-owning user.
2270               * @param string $action The nonce action.
2271               */
2272              $uid = apply_filters( 'nonce_user_logged_out', $uid, $action );
2273          }
2274  
2275          if ( empty( $nonce ) ) {
2276              return false;
2277          }
2278  
2279          $token = wp_get_session_token();
2280          $i     = wp_nonce_tick();
2281  
2282          // Nonce generated 0-12 hours ago.
2283          $expected = substr( wp_hash( $i . '|' . $action . '|' . $uid . '|' . $token, 'nonce' ), -12, 10 );
2284          if ( hash_equals( $expected, $nonce ) ) {
2285              return 1;
2286          }
2287  
2288          // Nonce generated 12-24 hours ago.
2289          $expected = substr( wp_hash( ( $i - 1 ) . '|' . $action . '|' . $uid . '|' . $token, 'nonce' ), -12, 10 );
2290          if ( hash_equals( $expected, $nonce ) ) {
2291              return 2;
2292          }
2293  
2294          /**
2295           * Fires when nonce verification fails.
2296           *
2297           * @since 4.4.0
2298           *
2299           * @param string     $nonce  The invalid nonce.
2300           * @param string|int $action The nonce action.
2301           * @param WP_User    $user   The current user object.
2302           * @param string     $token  The user's session token.
2303           */
2304          do_action( 'wp_verify_nonce_failed', $nonce, $action, $user, $token );
2305  
2306          // Invalid nonce.
2307          return false;
2308      }
2309  endif;
2310  
2311  if ( ! function_exists( 'wp_create_nonce' ) ) :
2312      /**
2313       * Creates a cryptographic token tied to a specific action, user, user session,
2314       * and window of time.
2315       *
2316       * @since 2.0.3
2317       * @since 4.0.0 Session tokens were integrated with nonce creation
2318       *
2319       * @param string|int $action Scalar value to add context to the nonce.
2320       * @return string The token.
2321       */
2322  	function wp_create_nonce( $action = -1 ) {
2323          $user = wp_get_current_user();
2324          $uid  = (int) $user->ID;
2325          if ( ! $uid ) {
2326              /** This filter is documented in wp-includes/pluggable.php */
2327              $uid = apply_filters( 'nonce_user_logged_out', $uid, $action );
2328          }
2329  
2330          $token = wp_get_session_token();
2331          $i     = wp_nonce_tick();
2332  
2333          return substr( wp_hash( $i . '|' . $action . '|' . $uid . '|' . $token, 'nonce' ), -12, 10 );
2334      }
2335  endif;
2336  
2337  if ( ! function_exists( 'wp_salt' ) ) :
2338      /**
2339       * Returns a salt to add to hashes.
2340       *
2341       * Salts are created using secret keys. Secret keys are located in two places:
2342       * in the database and in the wp-config.php file. The secret key in the database
2343       * is randomly generated and will be appended to the secret keys in wp-config.php.
2344       *
2345       * The secret keys in wp-config.php should be updated to strong, random keys to maximize
2346       * security. Below is an example of how the secret key constants are defined.
2347       * Do not paste this example directly into wp-config.php. Instead, have a
2348       * {@link https://api.wordpress.org/secret-key/1.1/salt/ secret key created} just
2349       * for you.
2350       *
2351       *     define('AUTH_KEY',         ' Xakm<o xQy rw4EMsLKM-?!T+,PFF})H4lzcW57AF0U@N@< >M%G4Yt>f`z]MON');
2352       *     define('SECURE_AUTH_KEY',  'LzJ}op]mr|6+![P}Ak:uNdJCJZd>(Hx.-Mh#Tz)pCIU#uGEnfFz|f ;;eU%/U^O~');
2353       *     define('LOGGED_IN_KEY',    '|i|Ux`9<p-h$aFf(qnT:sDO:D1P^wZ$$/Ra@miTJi9G;ddp_<q}6H1)o|a +&JCM');
2354       *     define('NONCE_KEY',        '%:R{[P|,s.KuMltH5}cI;/k<Gx~j!f0I)m_sIyu+&NJZ)-iO>z7X>QYR0Z_XnZ@|');
2355       *     define('AUTH_SALT',        'eZyT)-Naw]F8CwA*VaW#q*|.)g@o}||wf~@C-YSt}(dh_r6EbI#A,y|nU2{B#JBW');
2356       *     define('SECURE_AUTH_SALT', '!=oLUTXh,QW=H `}`L|9/^4-3 STz},T(w}W<I`.JjPi)<Bmf1v,HpGe}T1:Xt7n');
2357       *     define('LOGGED_IN_SALT',   '+XSqHc;@Q*K_b|Z?NC[3H!!EONbh.n<+=uKR:>*c(u`g~EJBf#8u#R{mUEZrozmm');
2358       *     define('NONCE_SALT',       'h`GXHhD>SLWVfg1(1(N{;.V!MoE(SfbA_ksP@&`+AycHcAV$+?@3q+rxV{%^VyKT');
2359       *
2360       * Salting passwords helps against tools which has stored hashed values of
2361       * common dictionary strings. The added values makes it harder to crack.
2362       *
2363       * @since 2.5.0
2364       *
2365       * @link https://api.wordpress.org/secret-key/1.1/salt/ Create secrets for wp-config.php
2366       *
2367       * @param string $scheme Authentication scheme (auth, secure_auth, logged_in, nonce)
2368       * @return string Salt value
2369       */
2370  	function wp_salt( $scheme = 'auth' ) {
2371          static $cached_salts = array();
2372          if ( isset( $cached_salts[ $scheme ] ) ) {
2373              /**
2374               * Filters the WordPress salt.
2375               *
2376               * @since 2.5.0
2377               *
2378               * @param string $cached_salt Cached salt for the given scheme.
2379               * @param string $scheme      Authentication scheme. Values include 'auth',
2380               *                            'secure_auth', 'logged_in', and 'nonce'.
2381               */
2382              return apply_filters( 'salt', $cached_salts[ $scheme ], $scheme );
2383          }
2384  
2385          static $duplicated_keys;
2386          if ( null === $duplicated_keys ) {
2387              $duplicated_keys = array( 'put your unique phrase here' => true );
2388              foreach ( array( 'AUTH', 'SECURE_AUTH', 'LOGGED_IN', 'NONCE', 'SECRET' ) as $first ) {
2389                  foreach ( array( 'KEY', 'SALT' ) as $second ) {
2390                      if ( ! defined( "{$first}_{$second}" ) ) {
2391                          continue;
2392                      }
2393                      $value                     = constant( "{$first}_{$second}" );
2394                      $duplicated_keys[ $value ] = isset( $duplicated_keys[ $value ] );
2395                  }
2396              }
2397          }
2398  
2399          $values = array(
2400              'key'  => '',
2401              'salt' => '',
2402          );
2403          if ( defined( 'SECRET_KEY' ) && SECRET_KEY && empty( $duplicated_keys[ SECRET_KEY ] ) ) {
2404              $values['key'] = SECRET_KEY;
2405          }
2406          if ( 'auth' === $scheme && defined( 'SECRET_SALT' ) && SECRET_SALT && empty( $duplicated_keys[ SECRET_SALT ] ) ) {
2407              $values['salt'] = SECRET_SALT;
2408          }
2409  
2410          if ( in_array( $scheme, array( 'auth', 'secure_auth', 'logged_in', 'nonce' ), true ) ) {
2411              foreach ( array( 'key', 'salt' ) as $type ) {
2412                  $const = strtoupper( "{$scheme}_{$type}" );
2413                  if ( defined( $const ) && constant( $const ) && empty( $duplicated_keys[ constant( $const ) ] ) ) {
2414                      $values[ $type ] = constant( $const );
2415                  } elseif ( ! $values[ $type ] ) {
2416                      $values[ $type ] = get_site_option( "{$scheme}_{$type}" );
2417                      if ( ! $values[ $type ] ) {
2418                          $values[ $type ] = wp_generate_password( 64, true, true );
2419                          update_site_option( "{$scheme}_{$type}", $values[ $type ] );
2420                      }
2421                  }
2422              }
2423          } else {
2424              if ( ! $values['key'] ) {
2425                  $values['key'] = get_site_option( 'secret_key' );
2426                  if ( ! $values['key'] ) {
2427                      $values['key'] = wp_generate_password( 64, true, true );
2428                      update_site_option( 'secret_key', $values['key'] );
2429                  }
2430              }
2431              $values['salt'] = hash_hmac( 'md5', $scheme, $values['key'] );
2432          }
2433  
2434          $cached_salts[ $scheme ] = $values['key'] . $values['salt'];
2435  
2436          /** This filter is documented in wp-includes/pluggable.php */
2437          return apply_filters( 'salt', $cached_salts[ $scheme ], $scheme );
2438      }
2439  endif;
2440  
2441  if ( ! function_exists( 'wp_hash' ) ) :
2442      /**
2443       * Get hash of given string.
2444       *
2445       * @since 2.0.3
2446       *
2447       * @param string $data   Plain text to hash
2448       * @param string $scheme Authentication scheme (auth, secure_auth, logged_in, nonce)
2449       * @return string Hash of $data
2450       */
2451  	function wp_hash( $data, $scheme = 'auth' ) {
2452          $salt = wp_salt( $scheme );
2453  
2454          return hash_hmac( 'md5', $data, $salt );
2455      }
2456  endif;
2457  
2458  if ( ! function_exists( 'wp_hash_password' ) ) :
2459      /**
2460       * Create a hash (encrypt) of a plain text password.
2461       *
2462       * For integration with other applications, this function can be overwritten to
2463       * instead use the other package password checking algorithm.
2464       *
2465       * @since 2.5.0
2466       *
2467       * @global PasswordHash $wp_hasher PHPass object
2468       *
2469       * @param string $password Plain text user password to hash
2470       * @return string The hash string of the password
2471       */
2472  	function wp_hash_password( $password ) {
2473          global $wp_hasher;
2474  
2475          if ( empty( $wp_hasher ) ) {
2476              require_once  ABSPATH . WPINC . '/class-phpass.php';
2477              // By default, use the portable hash from phpass.
2478              $wp_hasher = new PasswordHash( 8, true );
2479          }
2480  
2481          return $wp_hasher->HashPassword( trim( $password ) );
2482      }
2483  endif;
2484  
2485  if ( ! function_exists( 'wp_check_password' ) ) :
2486      /**
2487       * Checks the plaintext password against the encrypted Password.
2488       *
2489       * Maintains compatibility between old version and the new cookie authentication
2490       * protocol using PHPass library. The $hash parameter is the encrypted password
2491       * and the function compares the plain text password when encrypted similarly
2492       * against the already encrypted password to see if they match.
2493       *
2494       * For integration with other applications, this function can be overwritten to
2495       * instead use the other package password checking algorithm.
2496       *
2497       * @since 2.5.0
2498       *
2499       * @global PasswordHash $wp_hasher PHPass object used for checking the password
2500       *                                 against the $hash + $password
2501       * @uses PasswordHash::CheckPassword
2502       *
2503       * @param string     $password Plaintext user's password
2504       * @param string     $hash     Hash of the user's password to check against.
2505       * @param string|int $user_id  Optional. User ID.
2506       * @return bool False, if the $password does not match the hashed password
2507       */
2508  	function wp_check_password( $password, $hash, $user_id = '' ) {
2509          global $wp_hasher;
2510  
2511          // If the hash is still md5...
2512          if ( strlen( $hash ) <= 32 ) {
2513              $check = hash_equals( $hash, md5( $password ) );
2514              if ( $check && $user_id ) {
2515                  // Rehash using new hash.
2516                  wp_set_password( $password, $user_id );
2517                  $hash = wp_hash_password( $password );
2518              }
2519  
2520              /**
2521               * Filters whether the plaintext password matches the encrypted password.
2522               *
2523               * @since 2.5.0
2524               *
2525               * @param bool       $check    Whether the passwords match.
2526               * @param string     $password The plaintext password.
2527               * @param string     $hash     The hashed password.
2528               * @param string|int $user_id  User ID. Can be empty.
2529               */
2530              return apply_filters( 'check_password', $check, $password, $hash, $user_id );
2531          }
2532  
2533          // If the stored hash is longer than an MD5,
2534          // presume the new style phpass portable hash.
2535          if ( empty( $wp_hasher ) ) {
2536              require_once  ABSPATH . WPINC . '/class-phpass.php';
2537              // By default, use the portable hash from phpass.
2538              $wp_hasher = new PasswordHash( 8, true );
2539          }
2540  
2541          $check = $wp_hasher->CheckPassword( $password, $hash );
2542  
2543          /** This filter is documented in wp-includes/pluggable.php */
2544          return apply_filters( 'check_password', $check, $password, $hash, $user_id );
2545      }
2546  endif;
2547  
2548  if ( ! function_exists( 'wp_generate_password' ) ) :
2549      /**
2550       * Generates a random password drawn from the defined set of characters.
2551       *
2552       * Uses wp_rand() is used to create passwords with far less predictability
2553       * than similar native PHP functions like `rand()` or `mt_rand()`.
2554       *
2555       * @since 2.5.0
2556       *
2557       * @param int  $length              Optional. The length of password to generate. Default 12.
2558       * @param bool $special_chars       Optional. Whether to include standard special characters.
2559       *                                  Default true.
2560       * @param bool $extra_special_chars Optional. Whether to include other special characters.
2561       *                                  Used when generating secret keys and salts. Default false.
2562       * @return string The random password.
2563       */
2564  	function wp_generate_password( $length = 12, $special_chars = true, $extra_special_chars = false ) {
2565          $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
2566          if ( $special_chars ) {
2567              $chars .= '!@#$%^&*()';
2568          }
2569          if ( $extra_special_chars ) {
2570              $chars .= '-_ []{}<>~`+=,.;:/?|';
2571          }
2572  
2573          $password = '';
2574          for ( $i = 0; $i < $length; $i++ ) {
2575              $password .= substr( $chars, wp_rand( 0, strlen( $chars ) - 1 ), 1 );
2576          }
2577  
2578          /**
2579           * Filters the randomly-generated password.
2580           *
2581           * @since 3.0.0
2582           * @since 5.3.0 Added the `$length`, `$special_chars`, and `$extra_special_chars` parameters.
2583           *
2584           * @param string $password            The generated password.
2585           * @param int    $length              The length of password to generate.
2586           * @param bool   $special_chars       Whether to include standard special characters.
2587           * @param bool   $extra_special_chars Whether to include other special characters.
2588           */
2589          return apply_filters( 'random_password', $password, $length, $special_chars, $extra_special_chars );
2590      }
2591  endif;
2592  
2593  if ( ! function_exists( 'wp_rand' ) ) :
2594      /**
2595       * Generates a random number.
2596       *
2597       * @since 2.6.2
2598       * @since 4.4.0 Uses PHP7 random_int() or the random_compat library if available.
2599       *
2600       * @global string $rnd_value
2601       *
2602       * @param int $min Lower limit for the generated number
2603       * @param int $max Upper limit for the generated number
2604       * @return int A random number between min and max
2605       */
2606  	function wp_rand( $min = 0, $max = 0 ) {
2607          global $rnd_value;
2608  
2609          // Some misconfigured 32-bit environments (Entropy PHP, for example)
2610          // truncate integers larger than PHP_INT_MAX to PHP_INT_MAX rather than overflowing them to floats.
2611          $max_random_number = 3000000000 === 2147483647 ? (float) '4294967295' : 4294967295; // 4294967295 = 0xffffffff
2612  
2613          // We only handle ints, floats are truncated to their integer value.
2614          $min = (int) $min;
2615          $max = (int) $max;
2616  
2617          // Use PHP's CSPRNG, or a compatible method.
2618          static $use_random_int_functionality = true;
2619          if ( $use_random_int_functionality ) {
2620              try {
2621                  $_max = ( 0 != $max ) ? $max : $max_random_number;
2622                  // wp_rand() can accept arguments in either order, PHP cannot.
2623                  $_max = max( $min, $_max );
2624                  $_min = min( $min, $_max );
2625                  $val  = random_int( $_min, $_max );
2626                  if ( false !== $val ) {
2627                      return absint( $val );
2628                  } else {
2629                      $use_random_int_functionality = false;
2630                  }
2631              } catch ( Error $e ) {
2632                  $use_random_int_functionality = false;
2633              } catch ( Exception $e ) {
2634                  $use_random_int_functionality = false;
2635              }
2636          }
2637  
2638          // Reset $rnd_value after 14 uses.
2639          // 32 (md5) + 40 (sha1) + 40 (sha1) / 8 = 14 random numbers from $rnd_value.
2640          if ( strlen( $rnd_value ) < 8 ) {
2641              if ( defined( 'WP_SETUP_CONFIG' ) ) {
2642                  static $seed = '';
2643              } else {
2644                  $seed = get_transient( 'random_seed' );
2645              }
2646              $rnd_value  = md5( uniqid( microtime() . mt_rand(), true ) . $seed );
2647              $rnd_value .= sha1( $rnd_value );
2648              $rnd_value .= sha1( $rnd_value . $seed );
2649              $seed       = md5( $seed . $rnd_value );
2650              if ( ! defined( 'WP_SETUP_CONFIG' ) && ! defined( 'WP_INSTALLING' ) ) {
2651                  set_transient( 'random_seed', $seed );
2652              }
2653          }
2654  
2655          // Take the first 8 digits for our value.
2656          $value = substr( $rnd_value, 0, 8 );
2657  
2658          // Strip the first eight, leaving the remainder for the next call to wp_rand().
2659          $rnd_value = substr( $rnd_value, 8 );
2660  
2661          $value = abs( hexdec( $value ) );
2662  
2663          // Reduce the value to be within the min - max range.
2664          if ( 0 != $max ) {
2665              $value = $min + ( $max - $min + 1 ) * $value / ( $max_random_number + 1 );
2666          }
2667  
2668          return abs( (int) $value );
2669      }
2670  endif;
2671  
2672  if ( ! function_exists( 'wp_set_password' ) ) :
2673      /**
2674       * Updates the user's password with a new encrypted one.
2675       *
2676       * For integration with other applications, this function can be overwritten to
2677       * instead use the other package password checking algorithm.
2678       *
2679       * Please note: This function should be used sparingly and is really only meant for single-time
2680       * application. Leveraging this improperly in a plugin or theme could result in an endless loop
2681       * of password resets if precautions are not taken to ensure it does not execute on every page load.
2682       *
2683       * @since 2.5.0
2684       *
2685       * @global wpdb $wpdb WordPress database abstraction object.
2686       *
2687       * @param string $password The plaintext new user password
2688       * @param int    $user_id  User ID
2689       */
2690  	function wp_set_password( $password, $user_id ) {
2691          global $wpdb;
2692  
2693          $hash = wp_hash_password( $password );
2694          $wpdb->update(
2695              $wpdb->users,
2696              array(
2697                  'user_pass'           => $hash,
2698                  'user_activation_key' => '',
2699              ),
2700              array( 'ID' => $user_id )
2701          );
2702  
2703          clean_user_cache( $user_id );
2704      }
2705  endif;
2706  
2707  if ( ! function_exists( 'get_avatar' ) ) :
2708      /**
2709       * Retrieve the avatar `<img>` tag for a user, email address, MD5 hash, comment, or post.
2710       *
2711       * @since 2.5.0
2712       * @since 4.2.0 Optional `$args` parameter added.
2713       *
2714       * @param mixed  $id_or_email The Gravatar to retrieve. Accepts a user_id, gravatar md5 hash,
2715       *                            user email, WP_User object, WP_Post object, or WP_Comment object.
2716       * @param int    $size        Optional. Height and width of the avatar image file in pixels. Default 96.
2717       * @param string $default     Optional. URL for the default image or a default type. Accepts '404'
2718       *                            (return a 404 instead of a default image), 'retro' (8bit), 'monsterid'
2719       *                            (monster), 'wavatar' (cartoon face), 'indenticon' (the "quilt"),
2720       *                            'mystery', 'mm', or 'mysteryman' (The Oyster Man), 'blank' (transparent GIF),
2721       *                            or 'gravatar_default' (the Gravatar logo). Default is the value of the
2722       *                            'avatar_default' option, with a fallback of 'mystery'.
2723       * @param string $alt         Optional. Alternative text to use in img tag. Default empty.
2724       * @param array  $args {
2725       *     Optional. Extra arguments to retrieve the avatar.
2726       *
2727       *     @type int          $height        Display height of the avatar in pixels. Defaults to $size.
2728       *     @type int          $width         Display width of the avatar in pixels. Defaults to $size.
2729       *     @type bool         $force_default Whether to always show the default image, never the Gravatar. Default false.
2730       *     @type string       $rating        What rating to display avatars up to. Accepts 'G', 'PG', 'R', 'X', and are
2731       *                                       judged in that order. Default is the value of the 'avatar_rating' option.
2732       *     @type string       $scheme        URL scheme to use. See set_url_scheme() for accepted values.
2733       *                                       Default null.
2734       *     @type array|string $class         Array or string of additional classes to add to the img element.
2735       *                                       Default null.
2736       *     @type bool         $force_display Whether to always show the avatar - ignores the show_avatars option.
2737       *                                       Default false.
2738       *     @type string       $loading       Value for the `loading` attribute.
2739       *                                       Default null.
2740       *     @type string       $extra_attr    HTML attributes to insert in the IMG element. Is not sanitized. Default empty.
2741       * }
2742       * @return string|false `<img>` tag for the user's avatar. False on failure.
2743       */
2744  	function get_avatar( $id_or_email, $size = 96, $default = '', $alt = '', $args = null ) {
2745          $defaults = array(
2746              // get_avatar_data() args.
2747              'size'          => 96,
2748              'height'        => null,
2749              'width'         => null,
2750              'default'       => get_option( 'avatar_default', 'mystery' ),
2751              'force_default' => false,
2752              'rating'        => get_option( 'avatar_rating' ),
2753              'scheme'        => null,
2754              'alt'           => '',
2755              'class'         => null,
2756              'force_display' => false,
2757              'loading'       => null,
2758              'extra_attr'    => '',
2759          );
2760  
2761          if ( wp_lazy_loading_enabled( 'img', 'get_avatar' ) ) {
2762              $defaults['loading'] = wp_get_loading_attr_default( 'get_avatar' );
2763          }
2764  
2765          if ( empty( $args ) ) {
2766              $args = array();
2767          }
2768  
2769          $args['size']    = (int) $size;
2770          $args['default'] = $default;
2771          $args['alt']     = $alt;
2772  
2773          $args = wp_parse_args( $args, $defaults );
2774  
2775          if ( empty( $args['height'] ) ) {
2776              $args['height'] = $args['size'];
2777          }
2778          if ( empty( $args['width'] ) ) {
2779              $args['width'] = $args['size'];
2780          }
2781  
2782          if ( is_object( $id_or_email ) && isset( $id_or_email->comment_ID ) ) {
2783              $id_or_email = get_comment( $id_or_email );
2784          }
2785  
2786          /**
2787           * Allows the HTML for a user's avatar to be returned early.
2788           *
2789           * Returning a non-null value will effectively short-circuit get_avatar(), passing
2790           * the value through the {@see 'get_avatar'} filter and returning early.
2791           *
2792           * @since 4.2.0
2793           *
2794           * @param string|null $avatar      HTML for the user's avatar. Default null.
2795           * @param mixed       $id_or_email The avatar to retrieve. Accepts a user_id, Gravatar MD5 hash,
2796           *                                 user email, WP_User object, WP_Post object, or WP_Comment object.
2797           * @param array       $args        Arguments passed to get_avatar_url(), after processing.
2798           */
2799          $avatar = apply_filters( 'pre_get_avatar', null, $id_or_email, $args );
2800  
2801          if ( ! is_null( $avatar ) ) {
2802              /** This filter is documented in wp-includes/pluggable.php */
2803              return apply_filters( 'get_avatar', $avatar, $id_or_email, $args['size'], $args['default'], $args['alt'], $args );
2804          }
2805  
2806          if ( ! $args['force_display'] && ! get_option( 'show_avatars' ) ) {
2807              return false;
2808          }
2809  
2810          $url2x = get_avatar_url( $id_or_email, array_merge( $args, array( 'size' => $args['size'] * 2 ) ) );
2811  
2812          $args = get_avatar_data( $id_or_email, $args );
2813  
2814          $url = $args['url'];
2815  
2816          if ( ! $url || is_wp_error( $url ) ) {
2817              return false;
2818          }
2819  
2820          $class = array( 'avatar', 'avatar-' . (int) $args['size'], 'photo' );
2821  
2822          if ( ! $args['found_avatar'] || $args['force_default'] ) {
2823              $class[] = 'avatar-default';
2824          }
2825  
2826          if ( $args['class'] ) {
2827              if ( is_array( $args['class'] ) ) {
2828                  $class = array_merge( $class, $args['class'] );
2829              } else {
2830                  $class[] = $args['class'];
2831              }
2832          }
2833  
2834          // Add `loading` attribute.
2835          $extra_attr = $args['extra_attr'];
2836          $loading    = $args['loading'];
2837  
2838          if ( in_array( $loading, array( 'lazy', 'eager' ), true ) && ! preg_match( '/\bloading\s*=/', $extra_attr ) ) {
2839              if ( ! empty( $extra_attr ) ) {
2840                  $extra_attr .= ' ';
2841              }
2842  
2843              $extra_attr .= "loading='{$loading}'";
2844          }
2845  
2846          $avatar = sprintf(
2847              "<img alt='%s' src='%s' srcset='%s' class='%s' height='%d' width='%d' %s/>",
2848              esc_attr( $args['alt'] ),
2849              esc_url( $url ),
2850              esc_url( $url2x ) . ' 2x',
2851              esc_attr( implode( ' ', $class ) ),
2852              (int) $args['height'],
2853              (int) $args['width'],
2854              $extra_attr
2855          );
2856  
2857          /**
2858           * Filters the HTML for a user's avatar.
2859           *
2860           * @since 2.5.0
2861           * @since 4.2.0 The `$args` parameter was added.
2862           *
2863           * @param string $avatar      HTML for the user's avatar.
2864           * @param mixed  $id_or_email The avatar to retrieve. Accepts a user_id, Gravatar MD5 hash,
2865           *                            user email, WP_User object, WP_Post object, or WP_Comment object.
2866           * @param int    $size        Square avatar width and height in pixels to retrieve.
2867           * @param string $default     URL for the default image or a default type. Accepts '404', 'retro', 'monsterid',
2868           *                            'wavatar', 'indenticon', 'mystery', 'mm', 'mysteryman', 'blank', or 'gravatar_default'.
2869           * @param string $alt         Alternative text to use in the avatar image tag.
2870           * @param array  $args        Arguments passed to get_avatar_data(), after processing.
2871           */
2872          return apply_filters( 'get_avatar', $avatar, $id_or_email, $args['size'], $args['default'], $args['alt'], $args );
2873      }
2874  endif;
2875  
2876  if ( ! function_exists( 'wp_text_diff' ) ) :
2877      /**
2878       * Displays a human readable HTML representation of the difference between two strings.
2879       *
2880       * The Diff is available for getting the changes between versions. The output is
2881       * HTML, so the primary use is for displaying the changes. If the two strings
2882       * are equivalent, then an empty string will be returned.
2883       *
2884       * @since 2.6.0
2885       *
2886       * @see wp_parse_args() Used to change defaults to user defined settings.
2887       * @uses Text_Diff
2888       * @uses WP_Text_Diff_Renderer_Table
2889       *
2890       * @param string       $left_string  "old" (left) version of string
2891       * @param string       $right_string "new" (right) version of string
2892       * @param string|array $args {
2893       *     Associative array of options to pass to WP_Text_Diff_Renderer_Table().
2894       *
2895       *     @type string $title           Titles the diff in a manner compatible
2896       *                                   with the output. Default empty.
2897       *     @type string $title_left      Change the HTML to the left of the title.
2898       *                                   Default empty.
2899       *     @type string $title_right     Change the HTML to the right of the title.
2900       *                                   Default empty.
2901       *     @type bool   $show_split_view True for split view (two columns), false for
2902       *                                   un-split view (single column). Default true.
2903       * }
2904       * @return string Empty string if strings are equivalent or HTML with differences.
2905       */
2906  	function wp_text_diff( $left_string, $right_string, $args = null ) {
2907          $defaults = array(
2908              'title'           => '',
2909              'title_left'      => '',
2910              'title_right'     => '',
2911              'show_split_view' => true,
2912          );
2913          $args     = wp_parse_args( $args, $defaults );
2914  
2915          if ( ! class_exists( 'WP_Text_Diff_Renderer_Table', false ) ) {
2916              require  ABSPATH . WPINC . '/wp-diff.php';
2917          }
2918  
2919          $left_string  = normalize_whitespace( $left_string );
2920          $right_string = normalize_whitespace( $right_string );
2921  
2922          $left_lines  = explode( "\n", $left_string );
2923          $right_lines = explode( "\n", $right_string );
2924          $text_diff   = new Text_Diff( $left_lines, $right_lines );
2925          $renderer    = new WP_Text_Diff_Renderer_Table( $args );
2926          $diff        = $renderer->render( $text_diff );
2927  
2928          if ( ! $diff ) {
2929              return '';
2930          }
2931  
2932          $is_split_view       = ! empty( $args['show_split_view'] );
2933          $is_split_view_class = $is_split_view ? ' is-split-view' : '';
2934  
2935          $r = "<table class='diff$is_split_view_class'>\n";
2936  
2937          if ( $args['title'] ) {
2938              $r .= "<caption class='diff-title'>$args[title]</caption>\n";
2939          }
2940  
2941          if ( $args['title_left'] || $args['title_right'] ) {
2942              $r .= '<thead>';
2943          }
2944  
2945          if ( $args['title_left'] || $args['title_right'] ) {
2946              $th_or_td_left  = empty( $args['title_left'] ) ? 'td' : 'th';
2947              $th_or_td_right = empty( $args['title_right'] ) ? 'td' : 'th';
2948  
2949              $r .= "<tr class='diff-sub-title'>\n";
2950              $r .= "\t<$th_or_td_left>$args[title_left]</$th_or_td_left>\n";
2951              if ( $is_split_view ) {
2952                  $r .= "\t<$th_or_td_right>$args[title_right]</$th_or_td_right>\n";
2953              }
2954              $r .= "</tr>\n";
2955          }
2956  
2957          if ( $args['title_left'] || $args['title_right'] ) {
2958              $r .= "</thead>\n";
2959          }
2960  
2961          $r .= "<tbody>\n$diff\n</tbody>\n";
2962          $r .= '</table>';
2963  
2964          return $r;
2965      }
2966  endif;


Generated: Thu Nov 21 01:00:03 2024 Cross-referenced by PHPXref 0.7.1