PageRenderTime 62ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/pluggable.php

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