PageRenderTime 57ms CodeModel.GetById 10ms 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

Large files files are truncated, but you can click here to view the full 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' ), 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 …

Large files files are truncated, but you can click here to view the full file