PageRenderTime 32ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

/htdocs/wp-includes/pluggable.php

https://gitlab.com/VTTE/sitios-vtte
PHP | 1508 lines | 641 code | 180 blank | 687 comment | 156 complexity | c7b9ce8c335493cb6943a6ae30ab485e MD5 | raw file
  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' ) ) ) {
  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 ) ) {
  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. wp_destroy_current_session();
  501. wp_clear_auth_cookie();
  502. wp_set_current_user( 0 );
  503. /**
  504. * Fires after a user is logged-out.
  505. *
  506. * @since 1.5.0
  507. */
  508. do_action( 'wp_logout' );
  509. }
  510. endif;
  511. if ( ! function_exists( 'wp_validate_auth_cookie' ) ) :
  512. /**
  513. * Validates authentication cookie.
  514. *
  515. * The checks include making sure that the authentication cookie is set and
  516. * pulling in the contents (if $cookie is not used).
  517. *
  518. * Makes sure the cookie is not expired. Verifies the hash in cookie is what is
  519. * should be and compares the two.
  520. *
  521. * @since 2.5.0
  522. *
  523. * @global int $login_grace_period
  524. *
  525. * @param string $cookie Optional. If used, will validate contents instead of cookie's.
  526. * @param string $scheme Optional. The cookie scheme to use: 'auth', 'secure_auth', or 'logged_in'.
  527. * @return int|false User ID if valid cookie, false if invalid.
  528. */
  529. function wp_validate_auth_cookie( $cookie = '', $scheme = '' ) {
  530. $cookie_elements = wp_parse_auth_cookie( $cookie, $scheme );
  531. if ( ! $cookie_elements ) {
  532. /**
  533. * Fires if an authentication cookie is malformed.
  534. *
  535. * @since 2.7.0
  536. *
  537. * @param string $cookie Malformed auth cookie.
  538. * @param string $scheme Authentication scheme. Values include 'auth', 'secure_auth',
  539. * or 'logged_in'.
  540. */
  541. do_action( 'auth_cookie_malformed', $cookie, $scheme );
  542. return false;
  543. }
  544. $scheme = $cookie_elements['scheme'];
  545. $username = $cookie_elements['username'];
  546. $hmac = $cookie_elements['hmac'];
  547. $token = $cookie_elements['token'];
  548. $expired = $cookie_elements['expiration'];
  549. $expiration = $cookie_elements['expiration'];
  550. // Allow a grace period for POST and Ajax requests.
  551. if ( wp_doing_ajax() || 'POST' == $_SERVER['REQUEST_METHOD'] ) {
  552. $expired += HOUR_IN_SECONDS;
  553. }
  554. // Quick check to see if an honest cookie has expired.
  555. if ( $expired < time() ) {
  556. /**
  557. * Fires once an authentication cookie has expired.
  558. *
  559. * @since 2.7.0
  560. *
  561. * @param string[] $cookie_elements An array of data for the authentication cookie.
  562. */
  563. do_action( 'auth_cookie_expired', $cookie_elements );
  564. return false;
  565. }
  566. $user = get_user_by( 'login', $username );
  567. if ( ! $user ) {
  568. /**
  569. * Fires if a bad username is entered in the user authentication process.
  570. *
  571. * @since 2.7.0
  572. *
  573. * @param string[] $cookie_elements An array of data for the authentication cookie.
  574. */
  575. do_action( 'auth_cookie_bad_username', $cookie_elements );
  576. return false;
  577. }
  578. $pass_frag = substr( $user->user_pass, 8, 4 );
  579. $key = wp_hash( $username . '|' . $pass_frag . '|' . $expiration . '|' . $token, $scheme );
  580. // If ext/hash is not present, compat.php's hash_hmac() does not support sha256.
  581. $algo = function_exists( 'hash' ) ? 'sha256' : 'sha1';
  582. $hash = hash_hmac( $algo, $username . '|' . $expiration . '|' . $token, $key );
  583. if ( ! hash_equals( $hash, $hmac ) ) {
  584. /**
  585. * Fires if a bad authentication cookie hash is encountered.
  586. *
  587. * @since 2.7.0
  588. *
  589. * @param string[] $cookie_elements An array of data for the authentication cookie.
  590. */
  591. do_action( 'auth_cookie_bad_hash', $cookie_elements );
  592. return false;
  593. }
  594. $manager = WP_Session_Tokens::get_instance( $user->ID );
  595. if ( ! $manager->verify( $token ) ) {
  596. /**
  597. * Fires if a bad session token is encountered.
  598. *
  599. * @since 4.0.0
  600. *
  601. * @param string[] $cookie_elements An array of data for the authentication cookie.
  602. */
  603. do_action( 'auth_cookie_bad_session_token', $cookie_elements );
  604. return false;
  605. }
  606. // Ajax/POST grace period set above.
  607. if ( $expiration < time() ) {
  608. $GLOBALS['login_grace_period'] = 1;
  609. }
  610. /**
  611. * Fires once an authentication cookie has been validated.
  612. *
  613. * @since 2.7.0
  614. *
  615. * @param string[] $cookie_elements An array of data for the authentication cookie.
  616. * @param WP_User $user User object.
  617. */
  618. do_action( 'auth_cookie_valid', $cookie_elements, $user );
  619. return $user->ID;
  620. }
  621. endif;
  622. if ( ! function_exists( 'wp_generate_auth_cookie' ) ) :
  623. /**
  624. * Generates authentication cookie contents.
  625. *
  626. * @since 2.5.0
  627. * @since 4.0.0 The `$token` parameter was added.
  628. *
  629. * @param int $user_id User ID.
  630. * @param int $expiration The time the cookie expires as a UNIX timestamp.
  631. * @param string $scheme Optional. The cookie scheme to use: 'auth', 'secure_auth', or 'logged_in'.
  632. * Default 'auth'.
  633. * @param string $token User's session token to use for this cookie.
  634. * @return string Authentication cookie contents. Empty string if user does not exist.
  635. */
  636. function wp_generate_auth_cookie( $user_id, $expiration, $scheme = 'auth', $token = '' ) {
  637. $user = get_userdata( $user_id );
  638. if ( ! $user ) {
  639. return '';
  640. }
  641. if ( ! $token ) {
  642. $manager = WP_Session_Tokens::get_instance( $user_id );
  643. $token = $manager->create( $expiration );
  644. }
  645. $pass_frag = substr( $user->user_pass, 8, 4 );
  646. $key = wp_hash( $user->user_login . '|' . $pass_frag . '|' . $expiration . '|' . $token, $scheme );
  647. // If ext/hash is not present, compat.php's hash_hmac() does not support sha256.
  648. $algo = function_exists( 'hash' ) ? 'sha256' : 'sha1';
  649. $hash = hash_hmac( $algo, $user->user_login . '|' . $expiration . '|' . $token, $key );
  650. $cookie = $user->user_login . '|' . $expiration . '|' . $token . '|' . $hash;
  651. /**
  652. * Filters the authentication cookie.
  653. *
  654. * @since 2.5.0
  655. * @since 4.0.0 The `$token` parameter was added.
  656. *
  657. * @param string $cookie Authentication cookie.
  658. * @param int $user_id User ID.
  659. * @param int $expiration The time the cookie expires as a UNIX timestamp.
  660. * @param string $scheme Cookie scheme used. Accepts 'auth', 'secure_auth', or 'logged_in'.
  661. * @param string $token User's session token used.
  662. */
  663. return apply_filters( 'auth_cookie', $cookie, $user_id, $expiration, $scheme, $token );
  664. }
  665. endif;
  666. if ( ! function_exists( 'wp_parse_auth_cookie' ) ) :
  667. /**
  668. * Parses a cookie into its components.
  669. *
  670. * @since 2.7.0
  671. *
  672. * @param string $cookie Authentication cookie.
  673. * @param string $scheme Optional. The cookie scheme to use: 'auth', 'secure_auth', or 'logged_in'.
  674. * @return string[]|false Authentication cookie components.
  675. */
  676. function wp_parse_auth_cookie( $cookie = '', $scheme = '' ) {
  677. if ( empty( $cookie ) ) {
  678. switch ( $scheme ) {
  679. case 'auth':
  680. $cookie_name = AUTH_COOKIE;
  681. break;
  682. case 'secure_auth':
  683. $cookie_name = SECURE_AUTH_COOKIE;
  684. break;
  685. case 'logged_in':
  686. $cookie_name = LOGGED_IN_COOKIE;
  687. break;
  688. default:
  689. if ( is_ssl() ) {
  690. $cookie_name = SECURE_AUTH_COOKIE;
  691. $scheme = 'secure_auth';
  692. } else {
  693. $cookie_name = AUTH_COOKIE;
  694. $scheme = 'auth';
  695. }
  696. }
  697. if ( empty( $_COOKIE[ $cookie_name ] ) ) {
  698. return false;
  699. }
  700. $cookie = $_COOKIE[ $cookie_name ];
  701. }
  702. $cookie_elements = explode( '|', $cookie );
  703. if ( count( $cookie_elements ) !== 4 ) {
  704. return false;
  705. }
  706. list( $username, $expiration, $token, $hmac ) = $cookie_elements;
  707. return compact( 'username', 'expiration', 'token', 'hmac', 'scheme' );
  708. }
  709. endif;
  710. if ( ! function_exists( 'wp_set_auth_cookie' ) ) :
  711. /**
  712. * Sets the authentication cookies based on user ID.
  713. *
  714. * The $remember parameter increases the time that the cookie will be kept. The
  715. * default the cookie is kept without remembering is two days. When $remember is
  716. * set, the cookies will be kept for 14 days or two weeks.
  717. *
  718. * @since 2.5.0
  719. * @since 4.3.0 Added the `$token` parameter.
  720. *
  721. * @param int $user_id User ID.
  722. * @param bool $remember Whether to remember the user.
  723. * @param bool|string $secure Whether the auth cookie should only be sent over HTTPS. Default is an empty
  724. * string which means the value of `is_ssl()` will be used.
  725. * @param string $token Optional. User's session token to use for this cookie.
  726. */
  727. function wp_set_auth_cookie( $user_id, $remember = false, $secure = '', $token = '' ) {
  728. if ( $remember ) {
  729. /**
  730. * Filters the duration of the authentication cookie expiration period.
  731. *
  732. * @since 2.8.0
  733. *
  734. * @param int $length Duration of the expiration period in seconds.
  735. * @param int $user_id User ID.
  736. * @param bool $remember Whether to remember the user login. Default false.
  737. */
  738. $expiration = time() + apply_filters( 'auth_cookie_expiration', 14 * DAY_IN_SECONDS, $user_id, $remember );
  739. /*
  740. * Ensure the browser will continue to send the cookie after the expiration time is reached.
  741. * Needed for the login grace period in wp_validate_auth_cookie().
  742. */
  743. $expire = $expiration + ( 12 * HOUR_IN_SECONDS );
  744. } else {
  745. /** This filter is documented in wp-includes/pluggable.php */
  746. $expiration = time() + apply_filters( 'auth_cookie_expiration', 2 * DAY_IN_SECONDS, $user_id, $remember );
  747. $expire = 0;
  748. }
  749. if ( '' === $secure ) {
  750. $secure = is_ssl();
  751. }
  752. // Front-end cookie is secure when the auth cookie is secure and the site's home URL uses HTTPS.
  753. $secure_logged_in_cookie = $secure && 'https' === parse_url( get_option( 'home' ), PHP_URL_SCHEME );
  754. /**
  755. * Filters whether the auth cookie should only be sent over HTTPS.
  756. *
  757. * @since 3.1.0
  758. *
  759. * @param bool $secure Whether the cookie should only be sent over HTTPS.
  760. * @param int $user_id User ID.
  761. */
  762. $secure = apply_filters( 'secure_auth_cookie', $secure, $user_id );
  763. /**
  764. * Filters whether the logged in cookie should only be sent over HTTPS.
  765. *
  766. * @since 3.1.0
  767. *
  768. * @param bool $secure_logged_in_cookie Whether the logged in cookie should only be sent over HTTPS.
  769. * @param int $user_id User ID.
  770. * @param bool $secure Whether the auth cookie should only be sent over HTTPS.
  771. */
  772. $secure_logged_in_cookie = apply_filters( 'secure_logged_in_cookie', $secure_logged_in_cookie, $user_id, $secure );
  773. if ( $secure ) {
  774. $auth_cookie_name = SECURE_AUTH_COOKIE;
  775. $scheme = 'secure_auth';
  776. } else {
  777. $auth_cookie_name = AUTH_COOKIE;
  778. $scheme = 'auth';
  779. }
  780. if ( '' === $token ) {
  781. $manager = WP_Session_Tokens::get_instance( $user_id );
  782. $token = $manager->create( $expiration );
  783. }
  784. $auth_cookie = wp_generate_auth_cookie( $user_id, $expiration, $scheme, $token );
  785. $logged_in_cookie = wp_generate_auth_cookie( $user_id, $expiration, 'logged_in', $token );
  786. /**
  787. * Fires immediately before the authentication cookie is set.
  788. *
  789. * @since 2.5.0
  790. * @since 4.9.0 The `$token` parameter was added.
  791. *
  792. * @param string $auth_cookie Authentication cookie value.
  793. * @param int $expire The time the login grace period expires as a UNIX timestamp.
  794. * Default is 12 hours past the cookie's expiration time.
  795. * @param int $expiration The time when the authentication cookie expires as a UNIX timestamp.
  796. * Default is 14 days from now.
  797. * @param int $user_id User ID.
  798. * @param string $scheme Authentication scheme. Values include 'auth' or 'secure_auth'.
  799. * @param string $token User's session token to use for this cookie.
  800. */
  801. do_action( 'set_auth_cookie', $auth_cookie, $expire, $expiration, $user_id, $scheme, $token );
  802. /**
  803. * Fires immediately before the logged-in authentication cookie is set.
  804. *
  805. * @since 2.6.0
  806. * @since 4.9.0 The `$token` parameter was added.
  807. *
  808. * @param string $logged_in_cookie The logged-in cookie value.
  809. * @param int $expire The time the login grace period expires as a UNIX timestamp.
  810. * Default is 12 hours past the cookie's expiration time.
  811. * @param int $expiration The time when the logged-in authentication cookie expires as a UNIX timestamp.
  812. * Default is 14 days from now.
  813. * @param int $user_id User ID.
  814. * @param string $scheme Authentication scheme. Default 'logged_in'.
  815. * @param string $token User's session token to use for this cookie.
  816. */
  817. do_action( 'set_logged_in_cookie', $logged_in_cookie, $expire, $expiration, $user_id, 'logged_in', $token );
  818. /**
  819. * Allows preventing auth cookies from actually being sent to the client.
  820. *
  821. * @since 4.7.4
  822. *
  823. * @param bool $send Whether to send auth cookies to the client.
  824. */
  825. if ( ! apply_filters( 'send_auth_cookies', true ) ) {
  826. return;
  827. }
  828. setcookie( $auth_cookie_name, $auth_cookie, $expire, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN, $secure, true );
  829. setcookie( $auth_cookie_name, $auth_cookie, $expire, ADMIN_COOKIE_PATH, COOKIE_DOMAIN, $secure, true );
  830. setcookie( LOGGED_IN_COOKIE, $logged_in_cookie, $expire, COOKIEPATH, COOKIE_DOMAIN, $secure_logged_in_cookie, true );
  831. if ( COOKIEPATH != SITECOOKIEPATH ) {
  832. setcookie( LOGGED_IN_COOKIE, $logged_in_cookie, $expire, SITECOOKIEPATH, COOKIE_DOMAIN, $secure_logged_in_cookie, true );
  833. }
  834. }
  835. endif;
  836. if ( ! function_exists( 'wp_clear_auth_cookie' ) ) :
  837. /**
  838. * Removes all of the cookies associated with authentication.
  839. *
  840. * @since 2.5.0
  841. */
  842. function wp_clear_auth_cookie() {
  843. /**
  844. * Fires just before the authentication cookies are cleared.
  845. *
  846. * @since 2.7.0
  847. */
  848. do_action( 'clear_auth_cookie' );
  849. /** This filter is documented in wp-includes/pluggable.php */
  850. if ( ! apply_filters( 'send_auth_cookies', true ) ) {
  851. return;
  852. }
  853. // Auth cookies.
  854. setcookie( AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, ADMIN_COOKIE_PATH, COOKIE_DOMAIN );
  855. setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, ADMIN_COOKIE_PATH, COOKIE_DOMAIN );
  856. setcookie( AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN );
  857. setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN );
  858. setcookie( LOGGED_IN_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
  859. setcookie( LOGGED_IN_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
  860. // Settings cookies.
  861. setcookie( 'wp-settings-' . get_current_user_id(), ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH );
  862. setcookie( 'wp-settings-time-' . get_current_user_id(), ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH );
  863. // Old cookies.
  864. setcookie( AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
  865. setcookie( AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
  866. setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
  867. setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
  868. // Even older cookies.
  869. setcookie( USER_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
  870. setcookie( PASS_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
  871. setcookie( USER_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
  872. setcookie( PASS_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
  873. // Post password cookie.
  874. setcookie( 'wp-postpass_' . COOKIEHASH, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
  875. }
  876. endif;
  877. if ( ! function_exists( 'is_user_logged_in' ) ) :
  878. /**
  879. * Determines whether the current visitor is a logged in user.
  880. *
  881. * For more information on this and similar theme functions, check out
  882. * the {@link https://developer.wordpress.org/themes/basics/conditional-tags/
  883. * Conditional Tags} article in the Theme Developer Handbook.
  884. *
  885. * @since 2.0.0
  886. *
  887. * @return bool True if user is logged in, false if not logged in.
  888. */
  889. function is_user_logged_in() {
  890. $user = wp_get_current_user();
  891. return $user->exists();
  892. }
  893. endif;
  894. if ( ! function_exists( 'auth_redirect' ) ) :
  895. /**
  896. * Checks if a user is logged in, if not it redirects them to the login page.
  897. *
  898. * When this code is called from a page, it checks to see if the user viewing the page is logged in.
  899. * If the user is not logged in, they are redirected to the login page. The user is redirected
  900. * in such a way that, upon logging in, they will be sent directly to the page they were originally
  901. * trying to access.
  902. *
  903. * @since 1.5.0
  904. */
  905. function auth_redirect() {
  906. $secure = ( is_ssl() || force_ssl_admin() );
  907. /**
  908. * Filters whether to use a secure authentication redirect.
  909. *
  910. * @since 3.1.0
  911. *
  912. * @param bool $secure Whether to use a secure authentication redirect. Default false.
  913. */
  914. $secure = apply_filters( 'secure_auth_redirect', $secure );
  915. // If https is required and request is http, redirect.
  916. if ( $secure && ! is_ssl() && false !== strpos( $_SERVER['REQUEST_URI'], 'wp-admin' ) ) {
  917. if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) {
  918. wp_redirect( set_url_scheme( $_SERVER['REQUEST_URI'], 'https' ) );
  919. exit();
  920. } else {
  921. wp_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
  922. exit();
  923. }
  924. }
  925. /**
  926. * Filters the authentication redirect scheme.
  927. *
  928. * @since 2.9.0
  929. *
  930. * @param string $scheme Authentication redirect scheme. Default empty.
  931. */
  932. $scheme = apply_filters( 'auth_redirect_scheme', '' );
  933. $user_id = wp_validate_auth_cookie( '', $scheme );
  934. if ( $user_id ) {
  935. /**
  936. * Fires before the authentication redirect.
  937. *
  938. * @since 2.8.0
  939. *
  940. * @param int $user_id User ID.
  941. */
  942. do_action( 'auth_redirect', $user_id );
  943. // If the user wants ssl but the session is not ssl, redirect.
  944. if ( ! $secure && get_user_option( 'use_ssl', $user_id ) && false !== strpos( $_SERVER['REQUEST_URI'], 'wp-admin' ) ) {
  945. if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) {
  946. wp_redirect( set_url_scheme( $_SERVER['REQUEST_URI'], 'https' ) );
  947. exit();
  948. } else {
  949. wp_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
  950. exit();
  951. }
  952. }
  953. return; // The cookie is good, so we're done.
  954. }
  955. // The cookie is no good, so force login.
  956. nocache_headers();
  957. $redirect = ( strpos( $_SERVER['REQUEST_URI'], '/options.php' ) && wp_get_referer() ) ? wp_get_referer() : set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
  958. $login_url = wp_login_url( $redirect, true );
  959. wp_redirect( $login_url );
  960. exit();
  961. }
  962. endif;
  963. if ( ! function_exists( 'check_admin_referer' ) ) :
  964. /**
  965. * Ensures intent by verifying that a user was referred from another admin page with the correct security nonce.
  966. *
  967. * This function ensures the user intends to perform a given action, which helps protect against clickjacking style
  968. * attacks. It verifies intent, not authorisation, therefore it does not verify the user's capabilities. This should
  969. * be performed with `current_user_can()` or similar.
  970. *
  971. * If the nonce value is invalid, the function will exit with an "Are You Sure?" style message.
  972. *
  973. * @since 1.2.0
  974. * @since 2.5.0 The `$query_arg` parameter was added.
  975. *
  976. * @param int|string $action The nonce action.
  977. * @param string $query_arg Optional. Key to check for nonce in `$_REQUEST`. Default '_wpnonce'.
  978. * @return int|false 1 if the nonce is valid and generated between 0-12 hours ago,
  979. * 2 if the nonce is valid and generated between 12-24 hours ago.
  980. * False if the nonce is invalid.
  981. */
  982. function check_admin_referer( $action = -1, $query_arg = '_wpnonce' ) {
  983. if ( -1 === $action ) {
  984. _doing_it_wrong( __FUNCTION__, __( 'You should specify a nonce action to be verified by using the first parameter.' ), '3.2.0' );
  985. }
  986. $adminurl = strtolower( admin_url() );
  987. $referer = strtolower( wp_get_referer() );
  988. $result = isset( $_REQUEST[ $query_arg ] ) ? wp_verify_nonce( $_REQUEST[ $query_arg ], $action ) : false;
  989. /**
  990. * Fires once the admin request has been validated or not.
  991. *
  992. * @since 1.5.1
  993. *
  994. * @param string $action The nonce action.
  995. * @param false|int $result False if the nonce is invalid, 1 if the nonce is valid and generated between
  996. * 0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.
  997. */
  998. do_action( 'check_admin_referer', $action, $result );
  999. if ( ! $result && ! ( -1 === $action && strpos( $referer, $adminurl ) === 0 ) ) {
  1000. wp_nonce_ays( $action );
  1001. die();
  1002. }
  1003. return $result;
  1004. }
  1005. endif;
  1006. if ( ! function_exists( 'check_ajax_referer' ) ) :
  1007. /**
  1008. * Verifies the Ajax request to prevent processing requests external of the blog.
  1009. *
  1010. * @since 2.0.3
  1011. *
  1012. * @param int|string $action Action nonce.
  1013. * @param false|string $query_arg Optional. Key to check for the nonce in `$_REQUEST` (since 2.5). If false,
  1014. * `$_REQUEST` values will be evaluated for '_ajax_nonce', and '_wpnonce'
  1015. * (in that order). Default false.
  1016. * @param bool $die Optional. Whether to die early when the nonce cannot be verified.
  1017. * Default true.
  1018. * @return int|false 1 if the nonce is valid and generated between 0-12 hours ago,
  1019. * 2 if the nonce is valid and generated between 12-24 hours ago.
  1020. * False if the nonce is invalid.
  1021. */
  1022. function check_ajax_referer( $action = -1, $query_arg = false, $die = true ) {
  1023. if ( -1 == $action ) {
  1024. _doing_it_wrong( __FUNCTION__, __( 'You should specify a nonce action to be verified by using the first parameter.' ), '4.7' );
  1025. }
  1026. $nonce = '';
  1027. if ( $query_arg && isset( $_REQUEST[ $query_arg ] ) ) {
  1028. $nonce = $_REQUEST[ $query_arg ];
  1029. } elseif ( isset( $_REQUEST['_ajax_nonce'] ) ) {
  1030. $nonce = $_REQUEST['_ajax_nonce'];
  1031. } elseif ( isset( $_REQUEST['_wpnonce'] ) ) {
  1032. $nonce = $_REQUEST['_wpnonce'];
  1033. }
  1034. $result = wp_verify_nonce( $nonce, $action );
  1035. /**
  1036. * Fires once the Ajax request has been validated or not.
  1037. *
  1038. * @since 2.1.0
  1039. *
  1040. * @param string $action The Ajax nonce action.
  1041. * @param false|int $result False if the nonce is invalid, 1 if the nonce is valid and generated between
  1042. * 0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.
  1043. */
  1044. do_action( 'check_ajax_referer', $action, $result );
  1045. if ( $die && false === $result ) {
  1046. if ( wp_doing_ajax() ) {
  1047. wp_die( -1, 403 );
  1048. } else {
  1049. die( '-1' );
  1050. }
  1051. }
  1052. return $result;
  1053. }
  1054. endif;
  1055. if ( ! function_exists( 'wp_redirect' ) ) :
  1056. /**
  1057. * Redirects to another page.
  1058. *
  1059. * Note: wp_redirect() does not exit automatically, and should almost always be
  1060. * followed by a call to `exit;`:
  1061. *
  1062. * wp_redirect( $url );
  1063. * exit;
  1064. *
  1065. * Exiting can also be selectively manipulated by using wp_redirect() as a conditional
  1066. * in conjunction with the {@see 'wp_redirect'} and {@see 'wp_redirect_location'} filters:
  1067. *
  1068. * if ( wp_redirect( $url ) ) {
  1069. * exit;
  1070. * }
  1071. *
  1072. * @since 1.5.1
  1073. * @since 5.1.0 The `$x_redirect_by` parameter was added.
  1074. * @since 5.4.0 On invalid status codes, wp_die() is called.
  1075. *
  1076. * @global bool $is_IIS
  1077. *
  1078. * @param string $location The path or URL to redirect to.
  1079. * @param int $status Optional. HTTP response status code to use. Default '302' (Moved Temporarily).
  1080. * @param string $x_redirect_by Optional. The application doing the redirect. Default 'WordPress'.
  1081. * @return bool False if the redirect was cancelled, true otherwise.
  1082. */
  1083. function wp_redirect( $location, $status = 302, $x_redirect_by = 'WordPress' ) {
  1084. global $is_IIS;
  1085. /**
  1086. * Filters the redirect location.
  1087. *
  1088. * @since 2.1.0
  1089. *
  1090. * @param string $location The path or URL to redirect to.
  1091. * @param int $status The HTTP response status code to use.
  1092. */
  1093. $location = apply_filters( 'wp_redirect', $location, $status );
  1094. /**
  1095. * Filters the redirect HTTP response status code to use.
  1096. *
  1097. * @since 2.3.0
  1098. *
  1099. * @param int $status The HTTP response status code to use.
  1100. * @param string $location The path or URL to redirect to.
  1101. */
  1102. $status = apply_filters( 'wp_redirect_status', $status, $location );
  1103. if ( ! $location ) {
  1104. return false;
  1105. }
  1106. if ( $status < 300 || 399 < $status ) {
  1107. wp_die( __( 'HTTP redirect status code must be a redirection code, 3xx.' ) );
  1108. }
  1109. $location = wp_sanitize_redirect( $location );
  1110. if ( ! $is_IIS && PHP_SAPI != 'cgi-fcgi' ) {
  1111. status_header( $status ); // This causes problems on IIS and some FastCGI setups.
  1112. }
  1113. /**
  1114. * Filters the X-Redirect-By header.
  1115. *
  1116. * Allows applications to identify themselves when they're doing a redirect.
  1117. *
  1118. * @since 5.1.0
  1119. *
  1120. * @param string $x_redirect_by The application doing the redirect.
  1121. * @param int $status Status code to use.
  1122. * @param string $location The path to redirect to.
  1123. */
  1124. $x_redirect_by = apply_filters( 'x_redirect_by', $x_redirect_by, $status, $location );
  1125. if ( is_string( $x_redirect_by ) ) {
  1126. header( "X-Redirect-By: $x_redirect_by" );
  1127. }
  1128. header( "Location: $location", true, $status );
  1129. return true;
  1130. }
  1131. endif;
  1132. if ( ! function_exists( 'wp_sanitize_redirect' ) ) :
  1133. /**
  1134. * Sanitizes a URL for use in a redirect.
  1135. *
  1136. * @since 2.3.0
  1137. *
  1138. * @param string $location The path to redirect to.
  1139. * @return string Redirect-sanitized URL.
  1140. */
  1141. function wp_sanitize_redirect( $location ) {
  1142. // Encode spaces.
  1143. $location = str_replace( ' ', '%20', $location );
  1144. $regex = '/
  1145. (
  1146. (?: [\xC2-\xDF][\x80-\xBF] # double-byte sequences 110xxxxx 10xxxxxx
  1147. | \xE0[\xA0-\xBF][\x80-\xBF] # triple-byte sequences 1110xxxx 10xxxxxx * 2
  1148. | [\xE1-\xEC][\x80-\xBF]{2}
  1149. | \xED[\x80-\x9F][\x80-\xBF]
  1150. | [\xEE-\xEF][\x80-\xBF]{2}
  1151. | \xF0[\x90-\xBF][\x80-\xBF]{2} # four-byte sequences 11110xxx 10xxxxxx * 3
  1152. | [\xF1-\xF3][\x80-\xBF]{3}
  1153. | \xF4[\x80-\x8F][\x80-\xBF]{2}
  1154. ){1,40} # ...one or more times
  1155. )/x';
  1156. $location = preg_replace_callback( $regex, '_wp_sanitize_utf8_in_redirect', $location );
  1157. $location = preg_replace( '|[^a-z0-9-~+_.?#=&;,/:%!*\[\]()@]|i', '', $location );
  1158. $location = wp_kses_no_null( $location );
  1159. // Remove %0D and %0A from location.
  1160. $strip = array( '%0d', '%0a', '%0D', '%0A' );
  1161. return _deep_replace( $strip, $location );
  1162. }
  1163. /**
  1164. * URL encode UTF-8 characters in a URL.
  1165. *
  1166. * @ignore
  1167. * @since 4.2.0
  1168. * @access private
  1169. *
  1170. * @see wp_sanitize_redirect()
  1171. *
  1172. * @param array $matches RegEx matches against the redirect location.
  1173. * @return string URL-encoded version of the first RegEx match.
  1174. */
  1175. function _wp_sanitize_utf8_in_redirect( $matches ) {
  1176. return urlencode( $matches[0] );
  1177. }
  1178. endif;
  1179. if ( ! function_exists( 'wp_safe_redirect' ) ) :
  1180. /**
  1181. * Performs a safe (local) redirect, using wp_redirect().
  1182. *
  1183. * Checks whether the $location is using an allowed host, if it has an absolute
  1184. * path. A plugin can therefore set or remove allowed host(s) to or from the
  1185. * list.
  1186. *
  1187. * If the host is not allowed, then the redirect defaults to wp-admin on the siteurl
  1188. * instead. This prevents malicious redirects which redirect to another host,
  1189. * but only used in a few places.
  1190. *
  1191. * Note: wp_safe_redirect() does not exit automatically, and should almost always be
  1192. * followed by a call to `exit;`:
  1193. *
  1194. * wp_safe_redirect( $url );
  1195. * exit;
  1196. *
  1197. * Exiting can also be selectively manipulated by using wp_safe_redirect() as a conditional
  1198. * in conjunction with the {@see 'wp_redirect'} and {@see 'wp_redirect_location'} filters:
  1199. *
  1200. * if ( wp_safe_redirect( $url ) ) {
  1201. * exit;
  1202. * }
  1203. *
  1204. * @since 2.3.0
  1205. * @since 5.1.0 The return value from wp_redirect() is now passed on, and the `$x_redirect_by` parameter was added.
  1206. *
  1207. * @param string $location The path or URL to redirect to.
  1208. * @param int $status Optional. HTTP response status code to use. Default '302' (Moved Temporarily).
  1209. * @param string $x_redirect_by Optional. The application doing the redirect. Default 'WordPress'.
  1210. * @return bool $redirect False if the redirect was cancelled, true otherwise.
  1211. */
  1212. function wp_safe_redirect( $location, $status = 302, $x_redirect_by = 'WordPress' ) {
  1213. // Need to look at the URL the way it will end up in wp_redirect().
  1214. $location = wp_sanitize_redirect( $location );
  1215. /**
  1216. * Filters the redirect fallback URL for when the provided redirect is not safe (local).
  1217. *
  1218. * @since 4.3.0
  1219. *
  1220. * @param string $fallback_url The fallback URL to use by default.
  1221. * @param int $status The HTTP response status code to use.
  1222. */
  1223. $location = wp_validate_redirect( $location, apply_filters( 'wp_safe_redirect_fallback', admin_url(), $status ) );
  1224. return wp_redirect( $location, $status, $x_redirect_by );
  1225. }
  1226. endif;
  1227. if ( ! function_exists( 'wp_validate_redirect' ) ) :
  1228. /**
  1229. * Validates a URL for use in a redirect.
  1230. *
  1231. * Checks whether the $location is using an allowed host, if it has an absolute
  1232. * path. A plugin can therefore set or remove allowed host(s) to or from the
  1233. * list.
  1234. *
  1235. * If the host is not allowed, then the redirect is to $default supplied
  1236. *
  1237. * @since 2.8.1
  1238. *
  1239. * @param string $location The redirect to validate
  1240. * @param string $default The value to return if $location is not allowed
  1241. * @return string redirect-sanitized URL
  1242. */
  1243. function wp_validate_redirect( $location, $default = '' ) {
  1244. $location = wp_sanitize_redirect( trim( $location, " \t\n\r\0\x08\x0B" ) );
  1245. // Browsers will assume 'http' is your protocol, and will obey a redirect to a URL starting with '//'.
  1246. if ( substr( $location, 0, 2 ) == '//' ) {
  1247. $location = 'http:' . $location;
  1248. }
  1249. // In PHP 5 parse_url() may fail if the URL query part contains 'http://'.
  1250. // See https://bugs.php.net/bug.php?id=38143
  1251. $cut = strpos( $location, '?' );
  1252. $test = $cut ? substr( $location, 0, $cut ) : $location;
  1253. // @-operator is used to prevent possible warnings in PHP < 5.3.3.
  1254. $lp = @parse_url( $test );
  1255. // Give up if malformed URL.
  1256. if ( false === $lp ) {
  1257. return $default;
  1258. }
  1259. // Allow only 'http' and 'https' schemes. No 'data:', etc.
  1260. if ( isset( $lp['scheme'] ) && ! ( 'http' == $lp['scheme'] || 'https' == $lp['scheme'] ) ) {
  1261. return $default;
  1262. }
  1263. if ( ! isset( $lp['host'] ) && ! empty( $lp['path'] ) && '/' !== $lp['path'][0] ) {
  1264. $path = '';
  1265. if ( ! empty( $_SERVER['REQUEST_URI'] ) ) {
  1266. $path = dirname( parse_url( 'http://placeholder' . $_SERVER['REQUEST_URI'], PHP_URL_PATH ) . '?' );
  1267. $path = wp_normalize_path( $path );
  1268. }
  1269. $location = '/' . ltrim( $path . '/', '/' ) . $location;
  1270. }
  1271. // Reject if certain components are set but host is not.
  1272. // This catches URLs like https:host.com for which parse_url() does not set the host field.
  1273. if ( ! isset( $lp['host'] ) && ( isset( $lp['scheme'] ) || isset( $lp['user'] ) || isset( $lp['pass'] ) || isset( $lp['port'] ) ) ) {
  1274. return $default;
  1275. }
  1276. // Reject malformed components parse_url() can return on odd inputs.
  1277. foreach ( array( 'user', 'pass', 'host' ) as $component ) {
  1278. if ( isset( $lp[ $component ] ) && strpbrk( $lp[ $component ], ':/?#@' ) ) {
  1279. return $default;
  1280. }
  1281. }
  1282. $wpp = parse_url( home_url() );
  1283. /**
  1284. * Filters the whitelist of hosts to redirect to.
  1285. *
  1286. * @since 2.3.0
  1287. *
  1288. * @param string[] $hosts An array of allowed host names.
  1289. * @param string $host The host name of the redirect destination; empty string if not set.
  1290. */
  1291. $allowed_hosts = (array) apply_filters( 'allowed_redirect_hosts', array( $wpp['host'] ), isset( $lp['host'] ) ? $lp['host'] : '' );
  1292. if ( isset( $lp['host'] ) && ( ! in_array( $lp['host'], $allowed_hosts ) && strtolower( $wpp['host'] ) !== $lp['host'] ) ) {
  1293. $location = $default;
  1294. }
  1295. return $location;
  1296. }
  1297. endif;
  1298. if ( ! function_exists( 'wp_notify_postauthor' ) ) :
  1299. /**
  1300. * Notify an author (and/or others) of a comment/trackback/pingback on a post.
  1301. *
  1302. * @since 1.0.0
  1303. *
  1304. * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
  1305. * @param string $deprecated Not used
  1306. * @return bool True on completion. False if no email addresses were specified.
  1307. */
  1308. function wp_notify_postauthor( $comment_id, $deprecated = null ) {
  1309. if ( null !== $deprecated ) {
  1310. _deprecated_argument( __FUNCTION__, '3.8.0' );
  1311. }
  1312. $comment = get_comment( $comment_id );
  1313. if ( empty( $comment ) || empty( $comment->comment_post_ID ) ) {
  1314. return false;
  1315. }
  1316. $post = get_post( $comment->comment_post_ID );
  1317. $author = get_userdata( $post->post_author );
  1318. // Who to notify? By default, just the post author, but others can be added.
  1319. $emails = array();
  1320. if ( $author ) {
  1321. $emails[] = $author->user_email;
  1322. }
  1323. /**
  1324. * Filters the list of email addresses to receive a comment notification.
  1325. *
  1326. * By default, only post auth