PageRenderTime 60ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/pluggable.php

https://gitlab.com/Gashler/sg
PHP | 1571 lines | 703 code | 195 blank | 673 comment | 188 complexity | 8eb2fb627338fa7bf49afad5b88656f3 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 ( isset( $current_user ) && ( $current_user instanceof WP_User ) && ( $id == $current_user->ID ) )
  28. return $current_user;
  29. $current_user = new WP_User( $id, $name );
  30. setup_userdata( $current_user->ID );
  31. /**
  32. * Fires after the current user is set.
  33. *
  34. * @since 2.0.1
  35. */
  36. do_action( 'set_current_user' );
  37. return $current_user;
  38. }
  39. endif;
  40. if ( !function_exists('wp_get_current_user') ) :
  41. /**
  42. * Retrieve the current user object.
  43. *
  44. * @since 2.0.3
  45. *
  46. * @global WP_User $current_user
  47. *
  48. * @return WP_User Current user WP_User object
  49. */
  50. function wp_get_current_user() {
  51. global $current_user;
  52. get_currentuserinfo();
  53. return $current_user;
  54. }
  55. endif;
  56. if ( !function_exists('get_currentuserinfo') ) :
  57. /**
  58. * Populate global variables with information about the currently logged in user.
  59. *
  60. * Will set the current user, if the current user is not set. The current user
  61. * will be set to the logged-in person. If no user is logged-in, then it will
  62. * set the current user to 0, which is invalid and won't have any permissions.
  63. *
  64. * @since 0.71
  65. *
  66. * @global WP_User $current_user Checks if the current user is set
  67. *
  68. * @return false|void False on XML-RPC Request and invalid auth cookie.
  69. */
  70. function get_currentuserinfo() {
  71. global $current_user;
  72. if ( ! empty( $current_user ) ) {
  73. if ( $current_user instanceof WP_User )
  74. return;
  75. // Upgrade stdClass to WP_User
  76. if ( is_object( $current_user ) && isset( $current_user->ID ) ) {
  77. $cur_id = $current_user->ID;
  78. $current_user = null;
  79. wp_set_current_user( $cur_id );
  80. return;
  81. }
  82. // $current_user has a junk value. Force to WP_User with ID 0.
  83. $current_user = null;
  84. wp_set_current_user( 0 );
  85. return false;
  86. }
  87. if ( defined('XMLRPC_REQUEST') && XMLRPC_REQUEST ) {
  88. wp_set_current_user( 0 );
  89. return false;
  90. }
  91. /**
  92. * Filter the current user.
  93. *
  94. * The default filters use this to determine the current user from the
  95. * request's cookies, if available.
  96. *
  97. * Returning a value of false will effectively short-circuit setting
  98. * the current user.
  99. *
  100. * @since 3.9.0
  101. *
  102. * @param int|bool $user_id User ID if one has been determined, false otherwise.
  103. */
  104. $user_id = apply_filters( 'determine_current_user', false );
  105. if ( ! $user_id ) {
  106. wp_set_current_user( 0 );
  107. return false;
  108. }
  109. wp_set_current_user( $user_id );
  110. }
  111. endif;
  112. if ( !function_exists('get_userdata') ) :
  113. /**
  114. * Retrieve user info by user ID.
  115. *
  116. * @since 0.71
  117. *
  118. * @param int $user_id User ID
  119. * @return WP_User|false WP_User object on success, false on failure.
  120. */
  121. function get_userdata( $user_id ) {
  122. return get_user_by( 'id', $user_id );
  123. }
  124. endif;
  125. if ( !function_exists('get_user_by') ) :
  126. /**
  127. * Retrieve user info by a given field
  128. *
  129. * @since 2.8.0
  130. *
  131. * @param string $field The field to retrieve the user with. id | slug | email | login
  132. * @param int|string $value A value for $field. A user ID, slug, email address, or login name.
  133. * @return WP_User|false WP_User object on success, false on failure.
  134. */
  135. function get_user_by( $field, $value ) {
  136. $userdata = WP_User::get_data_by( $field, $value );
  137. if ( !$userdata )
  138. return false;
  139. $user = new WP_User;
  140. $user->init( $userdata );
  141. return $user;
  142. }
  143. endif;
  144. if ( !function_exists('cache_users') ) :
  145. /**
  146. * Retrieve info for user lists to prevent multiple queries by get_userdata()
  147. *
  148. * @since 3.0.0
  149. *
  150. * @global wpdb $wpdb
  151. *
  152. * @param array $user_ids User ID numbers list
  153. */
  154. function cache_users( $user_ids ) {
  155. global $wpdb;
  156. $clean = _get_non_cached_ids( $user_ids, 'users' );
  157. if ( empty( $clean ) )
  158. return;
  159. $list = implode( ',', $clean );
  160. $users = $wpdb->get_results( "SELECT * FROM $wpdb->users WHERE ID IN ($list)" );
  161. $ids = array();
  162. foreach ( $users as $user ) {
  163. update_user_caches( $user );
  164. $ids[] = $user->ID;
  165. }
  166. update_meta_cache( 'user', $ids );
  167. }
  168. endif;
  169. if ( !function_exists( 'wp_mail' ) ) :
  170. /**
  171. * Send mail, similar to PHP's mail
  172. *
  173. * A true return value does not automatically mean that the user received the
  174. * email successfully. It just only means that the method used was able to
  175. * process the request without any errors.
  176. *
  177. * Using the two 'wp_mail_from' and 'wp_mail_from_name' hooks allow from
  178. * creating a from address like 'Name <email@address.com>' when both are set. If
  179. * just 'wp_mail_from' is set, then just the email address will be used with no
  180. * name.
  181. *
  182. * The default content type is 'text/plain' which does not allow using HTML.
  183. * However, you can set the content type of the email by using the
  184. * 'wp_mail_content_type' filter.
  185. *
  186. * The default charset is based on the charset used on the blog. The charset can
  187. * be set using the 'wp_mail_charset' filter.
  188. *
  189. * @since 1.2.1
  190. *
  191. * @global PHPMailer $phpmailer
  192. *
  193. * @param string|array $to Array or comma-separated list of email addresses to send message.
  194. * @param string $subject Email subject
  195. * @param string $message Message contents
  196. * @param string|array $headers Optional. Additional headers.
  197. * @param string|array $attachments Optional. Files to attach.
  198. * @return bool Whether the email contents were sent successfully.
  199. */
  200. function wp_mail( $to, $subject, $message, $headers = '', $attachments = array() ) {
  201. // Compact the input, apply the filters, and extract them back out
  202. /**
  203. * Filter the wp_mail() arguments.
  204. *
  205. * @since 2.2.0
  206. *
  207. * @param array $args A compacted array of wp_mail() arguments, including the "to" email,
  208. * subject, message, headers, and attachments values.
  209. */
  210. $atts = apply_filters( 'wp_mail', compact( 'to', 'subject', 'message', 'headers', 'attachments' ) );
  211. if ( isset( $atts['to'] ) ) {
  212. $to = $atts['to'];
  213. }
  214. if ( isset( $atts['subject'] ) ) {
  215. $subject = $atts['subject'];
  216. }
  217. if ( isset( $atts['message'] ) ) {
  218. $message = $atts['message'];
  219. }
  220. if ( isset( $atts['headers'] ) ) {
  221. $headers = $atts['headers'];
  222. }
  223. if ( isset( $atts['attachments'] ) ) {
  224. $attachments = $atts['attachments'];
  225. }
  226. if ( ! is_array( $attachments ) ) {
  227. $attachments = explode( "\n", str_replace( "\r\n", "\n", $attachments ) );
  228. }
  229. global $phpmailer;
  230. // (Re)create it, if it's gone missing
  231. if ( ! ( $phpmailer instanceof PHPMailer ) ) {
  232. require_once ABSPATH . WPINC . '/class-phpmailer.php';
  233. require_once ABSPATH . WPINC . '/class-smtp.php';
  234. $phpmailer = new PHPMailer( true );
  235. }
  236. // Headers
  237. if ( empty( $headers ) ) {
  238. $headers = array();
  239. } else {
  240. if ( !is_array( $headers ) ) {
  241. // Explode the headers out, so this function can take both
  242. // string headers and an array of headers.
  243. $tempheaders = explode( "\n", str_replace( "\r\n", "\n", $headers ) );
  244. } else {
  245. $tempheaders = $headers;
  246. }
  247. $headers = array();
  248. $cc = array();
  249. $bcc = array();
  250. // If it's actually got contents
  251. if ( !empty( $tempheaders ) ) {
  252. // Iterate through the raw headers
  253. foreach ( (array) $tempheaders as $header ) {
  254. if ( strpos($header, ':') === false ) {
  255. if ( false !== stripos( $header, 'boundary=' ) ) {
  256. $parts = preg_split('/boundary=/i', trim( $header ) );
  257. $boundary = trim( str_replace( array( "'", '"' ), '', $parts[1] ) );
  258. }
  259. continue;
  260. }
  261. // Explode them out
  262. list( $name, $content ) = explode( ':', trim( $header ), 2 );
  263. // Cleanup crew
  264. $name = trim( $name );
  265. $content = trim( $content );
  266. switch ( strtolower( $name ) ) {
  267. // Mainly for legacy -- process a From: header if it's there
  268. case 'from':
  269. $bracket_pos = strpos( $content, '<' );
  270. if ( $bracket_pos !== false ) {
  271. // Text before the bracketed email is the "From" name.
  272. if ( $bracket_pos > 0 ) {
  273. $from_name = substr( $content, 0, $bracket_pos - 1 );
  274. $from_name = str_replace( '"', '', $from_name );
  275. $from_name = trim( $from_name );
  276. }
  277. $from_email = substr( $content, $bracket_pos + 1 );
  278. $from_email = str_replace( '>', '', $from_email );
  279. $from_email = trim( $from_email );
  280. // Avoid setting an empty $from_email.
  281. } elseif ( '' !== trim( $content ) ) {
  282. $from_email = trim( $content );
  283. }
  284. break;
  285. case 'content-type':
  286. if ( strpos( $content, ';' ) !== false ) {
  287. list( $type, $charset_content ) = explode( ';', $content );
  288. $content_type = trim( $type );
  289. if ( false !== stripos( $charset_content, 'charset=' ) ) {
  290. $charset = trim( str_replace( array( 'charset=', '"' ), '', $charset_content ) );
  291. } elseif ( false !== stripos( $charset_content, 'boundary=' ) ) {
  292. $boundary = trim( str_replace( array( 'BOUNDARY=', 'boundary=', '"' ), '', $charset_content ) );
  293. $charset = '';
  294. }
  295. // Avoid setting an empty $content_type.
  296. } elseif ( '' !== trim( $content ) ) {
  297. $content_type = trim( $content );
  298. }
  299. break;
  300. case 'cc':
  301. $cc = array_merge( (array) $cc, explode( ',', $content ) );
  302. break;
  303. case 'bcc':
  304. $bcc = array_merge( (array) $bcc, explode( ',', $content ) );
  305. break;
  306. default:
  307. // Add it to our grand headers array
  308. $headers[trim( $name )] = trim( $content );
  309. break;
  310. }
  311. }
  312. }
  313. }
  314. // Empty out the values that may be set
  315. $phpmailer->ClearAllRecipients();
  316. $phpmailer->ClearAttachments();
  317. $phpmailer->ClearCustomHeaders();
  318. $phpmailer->ClearReplyTos();
  319. // From email and name
  320. // If we don't have a name from the input headers
  321. if ( !isset( $from_name ) )
  322. $from_name = 'WordPress';
  323. /* If we don't have an email from the input headers default to wordpress@$sitename
  324. * Some hosts will block outgoing mail from this address if it doesn't exist but
  325. * there's no easy alternative. Defaulting to admin_email might appear to be another
  326. * option but some hosts may refuse to relay mail from an unknown domain. See
  327. * https://core.trac.wordpress.org/ticket/5007.
  328. */
  329. if ( !isset( $from_email ) ) {
  330. // Get the site domain and get rid of www.
  331. $sitename = strtolower( $_SERVER['SERVER_NAME'] );
  332. if ( substr( $sitename, 0, 4 ) == 'www.' ) {
  333. $sitename = substr( $sitename, 4 );
  334. }
  335. $from_email = 'wordpress@' . $sitename;
  336. }
  337. /**
  338. * Filter the email address to send from.
  339. *
  340. * @since 2.2.0
  341. *
  342. * @param string $from_email Email address to send from.
  343. */
  344. $phpmailer->From = apply_filters( 'wp_mail_from', $from_email );
  345. /**
  346. * Filter the name to associate with the "from" email address.
  347. *
  348. * @since 2.3.0
  349. *
  350. * @param string $from_name Name associated with the "from" email address.
  351. */
  352. $phpmailer->FromName = apply_filters( 'wp_mail_from_name', $from_name );
  353. // Set destination addresses
  354. if ( !is_array( $to ) )
  355. $to = explode( ',', $to );
  356. foreach ( (array) $to as $recipient ) {
  357. try {
  358. // Break $recipient into name and address parts if in the format "Foo <bar@baz.com>"
  359. $recipient_name = '';
  360. if ( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) {
  361. if ( count( $matches ) == 3 ) {
  362. $recipient_name = $matches[1];
  363. $recipient = $matches[2];
  364. }
  365. }
  366. $phpmailer->AddAddress( $recipient, $recipient_name);
  367. } catch ( phpmailerException $e ) {
  368. continue;
  369. }
  370. }
  371. // Set mail's subject and body
  372. $phpmailer->Subject = $subject;
  373. $phpmailer->Body = $message;
  374. // Add any CC and BCC recipients
  375. if ( !empty( $cc ) ) {
  376. foreach ( (array) $cc as $recipient ) {
  377. try {
  378. // Break $recipient into name and address parts if in the format "Foo <bar@baz.com>"
  379. $recipient_name = '';
  380. if ( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) {
  381. if ( count( $matches ) == 3 ) {
  382. $recipient_name = $matches[1];
  383. $recipient = $matches[2];
  384. }
  385. }
  386. $phpmailer->AddCc( $recipient, $recipient_name );
  387. } catch ( phpmailerException $e ) {
  388. continue;
  389. }
  390. }
  391. }
  392. if ( !empty( $bcc ) ) {
  393. foreach ( (array) $bcc as $recipient) {
  394. try {
  395. // Break $recipient into name and address parts if in the format "Foo <bar@baz.com>"
  396. $recipient_name = '';
  397. if ( preg_match( '/(.*)<(.+)>/', $recipient, $matches ) ) {
  398. if ( count( $matches ) == 3 ) {
  399. $recipient_name = $matches[1];
  400. $recipient = $matches[2];
  401. }
  402. }
  403. $phpmailer->AddBcc( $recipient, $recipient_name );
  404. } catch ( phpmailerException $e ) {
  405. continue;
  406. }
  407. }
  408. }
  409. // Set to use PHP's mail()
  410. $phpmailer->IsMail();
  411. // Set Content-Type and charset
  412. // If we don't have a content-type from the input headers
  413. if ( !isset( $content_type ) )
  414. $content_type = 'text/plain';
  415. /**
  416. * Filter the wp_mail() content type.
  417. *
  418. * @since 2.3.0
  419. *
  420. * @param string $content_type Default wp_mail() content type.
  421. */
  422. $content_type = apply_filters( 'wp_mail_content_type', $content_type );
  423. $phpmailer->ContentType = $content_type;
  424. // Set whether it's plaintext, depending on $content_type
  425. if ( 'text/html' == $content_type )
  426. $phpmailer->IsHTML( true );
  427. // If we don't have a charset from the input headers
  428. if ( !isset( $charset ) )
  429. $charset = get_bloginfo( 'charset' );
  430. // Set the content-type and charset
  431. /**
  432. * Filter the default wp_mail() charset.
  433. *
  434. * @since 2.3.0
  435. *
  436. * @param string $charset Default email charset.
  437. */
  438. $phpmailer->CharSet = apply_filters( 'wp_mail_charset', $charset );
  439. // Set custom headers
  440. if ( !empty( $headers ) ) {
  441. foreach( (array) $headers as $name => $content ) {
  442. $phpmailer->AddCustomHeader( sprintf( '%1$s: %2$s', $name, $content ) );
  443. }
  444. if ( false !== stripos( $content_type, 'multipart' ) && ! empty($boundary) )
  445. $phpmailer->AddCustomHeader( sprintf( "Content-Type: %s;\n\t boundary=\"%s\"", $content_type, $boundary ) );
  446. }
  447. if ( !empty( $attachments ) ) {
  448. foreach ( $attachments as $attachment ) {
  449. try {
  450. $phpmailer->AddAttachment($attachment);
  451. } catch ( phpmailerException $e ) {
  452. continue;
  453. }
  454. }
  455. }
  456. /**
  457. * Fires after PHPMailer is initialized.
  458. *
  459. * @since 2.2.0
  460. *
  461. * @param PHPMailer &$phpmailer The PHPMailer instance, passed by reference.
  462. */
  463. do_action_ref_array( 'phpmailer_init', array( &$phpmailer ) );
  464. // Send!
  465. try {
  466. return $phpmailer->Send();
  467. } catch ( phpmailerException $e ) {
  468. return false;
  469. }
  470. }
  471. endif;
  472. if ( !function_exists('wp_authenticate') ) :
  473. /**
  474. * Checks a user's login information and logs them in if it checks out.
  475. *
  476. * @since 2.5.0
  477. *
  478. * @param string $username User's username
  479. * @param string $password User's password
  480. * @return WP_User|WP_Error WP_User object if login successful, otherwise WP_Error object.
  481. */
  482. function wp_authenticate($username, $password) {
  483. $username = sanitize_user($username);
  484. $password = trim($password);
  485. /**
  486. * Filter the user to authenticate.
  487. *
  488. * If a non-null value is passed, the filter will effectively short-circuit
  489. * authentication, returning an error instead.
  490. *
  491. * @since 2.8.0
  492. *
  493. * @param null|WP_User $user User to authenticate.
  494. * @param string $username User login.
  495. * @param string $password User password
  496. */
  497. $user = apply_filters( 'authenticate', null, $username, $password );
  498. if ( $user == null ) {
  499. // TODO what should the error message be? (Or would these even happen?)
  500. // Only needed if all authentication handlers fail to return anything.
  501. $user = new WP_Error('authentication_failed', __('<strong>ERROR</strong>: Invalid username or incorrect password.'));
  502. }
  503. $ignore_codes = array('empty_username', 'empty_password');
  504. if (is_wp_error($user) && !in_array($user->get_error_code(), $ignore_codes) ) {
  505. /**
  506. * Fires after a user login has failed.
  507. *
  508. * @since 2.5.0
  509. *
  510. * @param string $username User login.
  511. */
  512. do_action( 'wp_login_failed', $username );
  513. }
  514. return $user;
  515. }
  516. endif;
  517. if ( !function_exists('wp_logout') ) :
  518. /**
  519. * Log the current user out.
  520. *
  521. * @since 2.5.0
  522. */
  523. function wp_logout() {
  524. wp_destroy_current_session();
  525. wp_clear_auth_cookie();
  526. /**
  527. * Fires after a user is logged-out.
  528. *
  529. * @since 1.5.0
  530. */
  531. do_action( 'wp_logout' );
  532. }
  533. endif;
  534. if ( !function_exists('wp_validate_auth_cookie') ) :
  535. /**
  536. * Validates authentication cookie.
  537. *
  538. * The checks include making sure that the authentication cookie is set and
  539. * pulling in the contents (if $cookie is not used).
  540. *
  541. * Makes sure the cookie is not expired. Verifies the hash in cookie is what is
  542. * should be and compares the two.
  543. *
  544. * @since 2.5.0
  545. *
  546. * @global int $login_grace_period
  547. *
  548. * @param string $cookie Optional. If used, will validate contents instead of cookie's
  549. * @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in
  550. * @return false|int False if invalid cookie, User ID if valid.
  551. */
  552. function wp_validate_auth_cookie($cookie = '', $scheme = '') {
  553. if ( ! $cookie_elements = wp_parse_auth_cookie($cookie, $scheme) ) {
  554. /**
  555. * Fires if an authentication cookie is malformed.
  556. *
  557. * @since 2.7.0
  558. *
  559. * @param string $cookie Malformed auth cookie.
  560. * @param string $scheme Authentication scheme. Values include 'auth', 'secure_auth',
  561. * or 'logged_in'.
  562. */
  563. do_action( 'auth_cookie_malformed', $cookie, $scheme );
  564. return false;
  565. }
  566. $scheme = $cookie_elements['scheme'];
  567. $username = $cookie_elements['username'];
  568. $hmac = $cookie_elements['hmac'];
  569. $token = $cookie_elements['token'];
  570. $expired = $expiration = $cookie_elements['expiration'];
  571. // Allow a grace period for POST and AJAX requests
  572. if ( defined('DOING_AJAX') || 'POST' == $_SERVER['REQUEST_METHOD'] ) {
  573. $expired += HOUR_IN_SECONDS;
  574. }
  575. // Quick check to see if an honest cookie has expired
  576. if ( $expired < time() ) {
  577. /**
  578. * Fires once an authentication cookie has expired.
  579. *
  580. * @since 2.7.0
  581. *
  582. * @param array $cookie_elements An array of data for the authentication cookie.
  583. */
  584. do_action( 'auth_cookie_expired', $cookie_elements );
  585. return false;
  586. }
  587. $user = get_user_by('login', $username);
  588. if ( ! $user ) {
  589. /**
  590. * Fires if a bad username is entered in the user authentication process.
  591. *
  592. * @since 2.7.0
  593. *
  594. * @param array $cookie_elements An array of data for the authentication cookie.
  595. */
  596. do_action( 'auth_cookie_bad_username', $cookie_elements );
  597. return false;
  598. }
  599. $pass_frag = substr($user->user_pass, 8, 4);
  600. $key = wp_hash( $username . '|' . $pass_frag . '|' . $expiration . '|' . $token, $scheme );
  601. // If ext/hash is not present, compat.php's hash_hmac() does not support sha256.
  602. $algo = function_exists( 'hash' ) ? 'sha256' : 'sha1';
  603. $hash = hash_hmac( $algo, $username . '|' . $expiration . '|' . $token, $key );
  604. if ( ! hash_equals( $hash, $hmac ) ) {
  605. /**
  606. * Fires if a bad authentication cookie hash is encountered.
  607. *
  608. * @since 2.7.0
  609. *
  610. * @param array $cookie_elements An array of data for the authentication cookie.
  611. */
  612. do_action( 'auth_cookie_bad_hash', $cookie_elements );
  613. return false;
  614. }
  615. $manager = WP_Session_Tokens::get_instance( $user->ID );
  616. if ( ! $manager->verify( $token ) ) {
  617. do_action( 'auth_cookie_bad_session_token', $cookie_elements );
  618. return false;
  619. }
  620. // AJAX/POST grace period set above
  621. if ( $expiration < time() ) {
  622. $GLOBALS['login_grace_period'] = 1;
  623. }
  624. /**
  625. * Fires once an authentication cookie has been validated.
  626. *
  627. * @since 2.7.0
  628. *
  629. * @param array $cookie_elements An array of data for the authentication cookie.
  630. * @param WP_User $user User object.
  631. */
  632. do_action( 'auth_cookie_valid', $cookie_elements, $user );
  633. return $user->ID;
  634. }
  635. endif;
  636. if ( !function_exists('wp_generate_auth_cookie') ) :
  637. /**
  638. * Generate authentication cookie contents.
  639. *
  640. * @since 2.5.0
  641. *
  642. * @param int $user_id User ID
  643. * @param int $expiration Cookie expiration in seconds
  644. * @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in
  645. * @param string $token User's session token to use for this cookie
  646. * @return string Authentication cookie contents. Empty string if user does not exist.
  647. */
  648. function wp_generate_auth_cookie( $user_id, $expiration, $scheme = 'auth', $token = '' ) {
  649. $user = get_userdata($user_id);
  650. if ( ! $user ) {
  651. return '';
  652. }
  653. if ( ! $token ) {
  654. $manager = WP_Session_Tokens::get_instance( $user_id );
  655. $token = $manager->create( $expiration );
  656. }
  657. $pass_frag = substr($user->user_pass, 8, 4);
  658. $key = wp_hash( $user->user_login . '|' . $pass_frag . '|' . $expiration . '|' . $token, $scheme );
  659. // If ext/hash is not present, compat.php's hash_hmac() does not support sha256.
  660. $algo = function_exists( 'hash' ) ? 'sha256' : 'sha1';
  661. $hash = hash_hmac( $algo, $user->user_login . '|' . $expiration . '|' . $token, $key );
  662. $cookie = $user->user_login . '|' . $expiration . '|' . $token . '|' . $hash;
  663. /**
  664. * Filter the authentication cookie.
  665. *
  666. * @since 2.5.0
  667. *
  668. * @param string $cookie Authentication cookie.
  669. * @param int $user_id User ID.
  670. * @param int $expiration Authentication cookie expiration in seconds.
  671. * @param string $scheme Cookie scheme used. Accepts 'auth', 'secure_auth', or 'logged_in'.
  672. * @param string $token User's session token used.
  673. */
  674. return apply_filters( 'auth_cookie', $cookie, $user_id, $expiration, $scheme, $token );
  675. }
  676. endif;
  677. if ( !function_exists('wp_parse_auth_cookie') ) :
  678. /**
  679. * Parse a cookie into its components
  680. *
  681. * @since 2.7.0
  682. *
  683. * @param string $cookie
  684. * @param string $scheme Optional. The cookie scheme to use: auth, secure_auth, or logged_in
  685. * @return array|false Authentication cookie components
  686. */
  687. function wp_parse_auth_cookie($cookie = '', $scheme = '') {
  688. if ( empty($cookie) ) {
  689. switch ($scheme){
  690. case 'auth':
  691. $cookie_name = AUTH_COOKIE;
  692. break;
  693. case 'secure_auth':
  694. $cookie_name = SECURE_AUTH_COOKIE;
  695. break;
  696. case "logged_in":
  697. $cookie_name = LOGGED_IN_COOKIE;
  698. break;
  699. default:
  700. if ( is_ssl() ) {
  701. $cookie_name = SECURE_AUTH_COOKIE;
  702. $scheme = 'secure_auth';
  703. } else {
  704. $cookie_name = AUTH_COOKIE;
  705. $scheme = 'auth';
  706. }
  707. }
  708. if ( empty($_COOKIE[$cookie_name]) )
  709. return false;
  710. $cookie = $_COOKIE[$cookie_name];
  711. }
  712. $cookie_elements = explode('|', $cookie);
  713. if ( count( $cookie_elements ) !== 4 ) {
  714. return false;
  715. }
  716. list( $username, $expiration, $token, $hmac ) = $cookie_elements;
  717. return compact( 'username', 'expiration', 'token', 'hmac', 'scheme' );
  718. }
  719. endif;
  720. if ( !function_exists('wp_set_auth_cookie') ) :
  721. /**
  722. * Sets the authentication cookies based on user ID.
  723. *
  724. * The $remember parameter increases the time that the cookie will be kept. The
  725. * default the cookie is kept without remembering is two days. When $remember is
  726. * set, the cookies will be kept for 14 days or two weeks.
  727. *
  728. * @since 2.5.0
  729. * @since 4.3.0 Added the `$token` parameter.
  730. *
  731. * @param int $user_id User ID
  732. * @param bool $remember Whether to remember the user
  733. * @param mixed $secure Whether the admin cookies should only be sent over HTTPS.
  734. * Default is_ssl().
  735. * @param string $token Optional. User's session token to use for this cookie.
  736. */
  737. function wp_set_auth_cookie( $user_id, $remember = false, $secure = '', $token = '' ) {
  738. if ( $remember ) {
  739. /**
  740. * Filter the duration of the authentication cookie expiration period.
  741. *
  742. * @since 2.8.0
  743. *
  744. * @param int $length Duration of the expiration period in seconds.
  745. * @param int $user_id User ID.
  746. * @param bool $remember Whether to remember the user login. Default false.
  747. */
  748. $expiration = time() + apply_filters( 'auth_cookie_expiration', 14 * DAY_IN_SECONDS, $user_id, $remember );
  749. /*
  750. * Ensure the browser will continue to send the cookie after the expiration time is reached.
  751. * Needed for the login grace period in wp_validate_auth_cookie().
  752. */
  753. $expire = $expiration + ( 12 * HOUR_IN_SECONDS );
  754. } else {
  755. /** This filter is documented in wp-includes/pluggable.php */
  756. $expiration = time() + apply_filters( 'auth_cookie_expiration', 2 * DAY_IN_SECONDS, $user_id, $remember );
  757. $expire = 0;
  758. }
  759. if ( '' === $secure ) {
  760. $secure = is_ssl();
  761. }
  762. // Frontend cookie is secure when the auth cookie is secure and the site's home URL is forced HTTPS.
  763. $secure_logged_in_cookie = $secure && 'https' === parse_url( get_option( 'home' ), PHP_URL_SCHEME );
  764. /**
  765. * Filter whether the connection is secure.
  766. *
  767. * @since 3.1.0
  768. *
  769. * @param bool $secure Whether the connection is secure.
  770. * @param int $user_id User ID.
  771. */
  772. $secure = apply_filters( 'secure_auth_cookie', $secure, $user_id );
  773. /**
  774. * Filter whether to use a secure cookie when logged-in.
  775. *
  776. * @since 3.1.0
  777. *
  778. * @param bool $secure_logged_in_cookie Whether to use a secure cookie when logged-in.
  779. * @param int $user_id User ID.
  780. * @param bool $secure Whether the connection is secure.
  781. */
  782. $secure_logged_in_cookie = apply_filters( 'secure_logged_in_cookie', $secure_logged_in_cookie, $user_id, $secure );
  783. if ( $secure ) {
  784. $auth_cookie_name = SECURE_AUTH_COOKIE;
  785. $scheme = 'secure_auth';
  786. } else {
  787. $auth_cookie_name = AUTH_COOKIE;
  788. $scheme = 'auth';
  789. }
  790. if ( '' === $token ) {
  791. $manager = WP_Session_Tokens::get_instance( $user_id );
  792. $token = $manager->create( $expiration );
  793. }
  794. $auth_cookie = wp_generate_auth_cookie( $user_id, $expiration, $scheme, $token );
  795. $logged_in_cookie = wp_generate_auth_cookie( $user_id, $expiration, 'logged_in', $token );
  796. /**
  797. * Fires immediately before the authentication cookie is set.
  798. *
  799. * @since 2.5.0
  800. *
  801. * @param string $auth_cookie Authentication cookie.
  802. * @param int $expire Login grace period in seconds. Default 43,200 seconds, or 12 hours.
  803. * @param int $expiration Duration in seconds the authentication cookie should be valid.
  804. * Default 1,209,600 seconds, or 14 days.
  805. * @param int $user_id User ID.
  806. * @param string $scheme Authentication scheme. Values include 'auth', 'secure_auth', or 'logged_in'.
  807. */
  808. do_action( 'set_auth_cookie', $auth_cookie, $expire, $expiration, $user_id, $scheme );
  809. /**
  810. * Fires immediately before the secure authentication cookie is set.
  811. *
  812. * @since 2.6.0
  813. *
  814. * @param string $logged_in_cookie The logged-in cookie.
  815. * @param int $expire Login grace period in seconds. Default 43,200 seconds, or 12 hours.
  816. * @param int $expiration Duration in seconds the authentication cookie should be valid.
  817. * Default 1,209,600 seconds, or 14 days.
  818. * @param int $user_id User ID.
  819. * @param string $scheme Authentication scheme. Default 'logged_in'.
  820. */
  821. do_action( 'set_logged_in_cookie', $logged_in_cookie, $expire, $expiration, $user_id, 'logged_in' );
  822. setcookie($auth_cookie_name, $auth_cookie, $expire, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN, $secure, true);
  823. setcookie($auth_cookie_name, $auth_cookie, $expire, ADMIN_COOKIE_PATH, COOKIE_DOMAIN, $secure, true);
  824. setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire, COOKIEPATH, COOKIE_DOMAIN, $secure_logged_in_cookie, true);
  825. if ( COOKIEPATH != SITECOOKIEPATH )
  826. setcookie(LOGGED_IN_COOKIE, $logged_in_cookie, $expire, SITECOOKIEPATH, COOKIE_DOMAIN, $secure_logged_in_cookie, true);
  827. }
  828. endif;
  829. if ( !function_exists('wp_clear_auth_cookie') ) :
  830. /**
  831. * Removes all of the cookies associated with authentication.
  832. *
  833. * @since 2.5.0
  834. */
  835. function wp_clear_auth_cookie() {
  836. /**
  837. * Fires just before the authentication cookies are cleared.
  838. *
  839. * @since 2.7.0
  840. */
  841. do_action( 'clear_auth_cookie' );
  842. setcookie( AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, ADMIN_COOKIE_PATH, COOKIE_DOMAIN );
  843. setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, ADMIN_COOKIE_PATH, COOKIE_DOMAIN );
  844. setcookie( AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN );
  845. setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, PLUGINS_COOKIE_PATH, COOKIE_DOMAIN );
  846. setcookie( LOGGED_IN_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
  847. setcookie( LOGGED_IN_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
  848. // Old cookies
  849. setcookie( AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
  850. setcookie( AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
  851. setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
  852. setcookie( SECURE_AUTH_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
  853. // Even older cookies
  854. setcookie( USER_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
  855. setcookie( PASS_COOKIE, ' ', time() - YEAR_IN_SECONDS, COOKIEPATH, COOKIE_DOMAIN );
  856. setcookie( USER_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
  857. setcookie( PASS_COOKIE, ' ', time() - YEAR_IN_SECONDS, SITECOOKIEPATH, COOKIE_DOMAIN );
  858. }
  859. endif;
  860. if ( !function_exists('is_user_logged_in') ) :
  861. /**
  862. * Checks if the current visitor is a logged in user.
  863. *
  864. * @since 2.0.0
  865. *
  866. * @return bool True if user is logged in, false if not logged in.
  867. */
  868. function is_user_logged_in() {
  869. $user = wp_get_current_user();
  870. return $user->exists();
  871. }
  872. endif;
  873. if ( !function_exists('auth_redirect') ) :
  874. /**
  875. * Checks if a user is logged in, if not it redirects them to the login page.
  876. *
  877. * @since 1.5.0
  878. */
  879. function auth_redirect() {
  880. // Checks if a user is logged in, if not redirects them to the login page
  881. $secure = ( is_ssl() || force_ssl_admin() );
  882. /**
  883. * Filter whether to use a secure authentication redirect.
  884. *
  885. * @since 3.1.0
  886. *
  887. * @param bool $secure Whether to use a secure authentication redirect. Default false.
  888. */
  889. $secure = apply_filters( 'secure_auth_redirect', $secure );
  890. // If https is required and request is http, redirect
  891. if ( $secure && !is_ssl() && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin') ) {
  892. if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) {
  893. wp_redirect( set_url_scheme( $_SERVER['REQUEST_URI'], 'https' ) );
  894. exit();
  895. } else {
  896. wp_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
  897. exit();
  898. }
  899. }
  900. if ( is_user_admin() ) {
  901. $scheme = 'logged_in';
  902. } else {
  903. /**
  904. * Filter the authentication redirect scheme.
  905. *
  906. * @since 2.9.0
  907. *
  908. * @param string $scheme Authentication redirect scheme. Default empty.
  909. */
  910. $scheme = apply_filters( 'auth_redirect_scheme', '' );
  911. }
  912. if ( $user_id = wp_validate_auth_cookie( '', $scheme) ) {
  913. /**
  914. * Fires before the authentication redirect.
  915. *
  916. * @since 2.8.0
  917. *
  918. * @param int $user_id User ID.
  919. */
  920. do_action( 'auth_redirect', $user_id );
  921. // If the user wants ssl but the session is not ssl, redirect.
  922. if ( !$secure && get_user_option('use_ssl', $user_id) && false !== strpos($_SERVER['REQUEST_URI'], 'wp-admin') ) {
  923. if ( 0 === strpos( $_SERVER['REQUEST_URI'], 'http' ) ) {
  924. wp_redirect( set_url_scheme( $_SERVER['REQUEST_URI'], 'https' ) );
  925. exit();
  926. } else {
  927. wp_redirect( 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
  928. exit();
  929. }
  930. }
  931. return; // The cookie is good so we're done
  932. }
  933. // The cookie is no good so force login
  934. nocache_headers();
  935. $redirect = ( strpos( $_SERVER['REQUEST_URI'], '/options.php' ) && wp_get_referer() ) ? wp_get_referer() : set_url_scheme( 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] );
  936. $login_url = wp_login_url($redirect, true);
  937. wp_redirect($login_url);
  938. exit();
  939. }
  940. endif;
  941. if ( !function_exists('check_admin_referer') ) :
  942. /**
  943. * Makes sure that a user was referred from another admin page.
  944. *
  945. * To avoid security exploits.
  946. *
  947. * @since 1.2.0
  948. *
  949. * @param int|string $action Action nonce.
  950. * @param string $query_arg Optional. Key to check for nonce in `$_REQUEST` (since 2.5).
  951. * Default '_wpnonce'.
  952. * @return false|int False if the nonce is invalid, 1 if the nonce is valid and generated between
  953. * 0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.
  954. */
  955. function check_admin_referer( $action = -1, $query_arg = '_wpnonce' ) {
  956. if ( -1 == $action )
  957. _doing_it_wrong( __FUNCTION__, __( 'You should specify a nonce action to be verified by using the first parameter.' ), '3.2' );
  958. $adminurl = strtolower(admin_url());
  959. $referer = strtolower(wp_get_referer());
  960. $result = isset($_REQUEST[$query_arg]) ? wp_verify_nonce($_REQUEST[$query_arg], $action) : false;
  961. /**
  962. * Fires once the admin request has been validated or not.
  963. *
  964. * @since 1.5.1
  965. *
  966. * @param string $action The nonce action.
  967. * @param false|int $result False if the nonce is invalid, 1 if the nonce is valid and generated between
  968. * 0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.
  969. */
  970. do_action( 'check_admin_referer', $action, $result );
  971. if ( ! $result && ! ( -1 == $action && strpos( $referer, $adminurl ) === 0 ) ) {
  972. wp_nonce_ays( $action );
  973. die();
  974. }
  975. return $result;
  976. }
  977. endif;
  978. if ( !function_exists('check_ajax_referer') ) :
  979. /**
  980. * Verifies the AJAX request to prevent processing requests external of the blog.
  981. *
  982. * @since 2.0.3
  983. *
  984. * @param int|string $action Action nonce.
  985. * @param false|string $query_arg Optional. Key to check for the nonce in `$_REQUEST` (since 2.5). If false,
  986. * `$_REQUEST` values will be evaluated for '_ajax_nonce', and '_wpnonce'
  987. * (in that order). Default false.
  988. * @param bool $die Optional. Whether to die early when the nonce cannot be verified.
  989. * Default true.
  990. * @return false|int False if the nonce is invalid, 1 if the nonce is valid and generated between
  991. * 0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.
  992. */
  993. function check_ajax_referer( $action = -1, $query_arg = false, $die = true ) {
  994. $nonce = '';
  995. if ( $query_arg && isset( $_REQUEST[ $query_arg ] ) )
  996. $nonce = $_REQUEST[ $query_arg ];
  997. elseif ( isset( $_REQUEST['_ajax_nonce'] ) )
  998. $nonce = $_REQUEST['_ajax_nonce'];
  999. elseif ( isset( $_REQUEST['_wpnonce'] ) )
  1000. $nonce = $_REQUEST['_wpnonce'];
  1001. $result = wp_verify_nonce( $nonce, $action );
  1002. if ( $die && false === $result ) {
  1003. if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
  1004. wp_die( -1 );
  1005. else
  1006. die( '-1' );
  1007. }
  1008. /**
  1009. * Fires once the AJAX request has been validated or not.
  1010. *
  1011. * @since 2.1.0
  1012. *
  1013. * @param string $action The AJAX nonce action.
  1014. * @param false|int $result False if the nonce is invalid, 1 if the nonce is valid and generated between
  1015. * 0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.
  1016. */
  1017. do_action( 'check_ajax_referer', $action, $result );
  1018. return $result;
  1019. }
  1020. endif;
  1021. if ( !function_exists('wp_redirect') ) :
  1022. /**
  1023. * Redirects to another page.
  1024. *
  1025. * @since 1.5.1
  1026. *
  1027. * @global bool $is_IIS
  1028. *
  1029. * @param string $location The path to redirect to.
  1030. * @param int $status Status code to use.
  1031. * @return bool False if $location is not provided, true otherwise.
  1032. */
  1033. function wp_redirect($location, $status = 302) {
  1034. global $is_IIS;
  1035. /**
  1036. * Filter the redirect location.
  1037. *
  1038. * @since 2.1.0
  1039. *
  1040. * @param string $location The path to redirect to.
  1041. * @param int $status Status code to use.
  1042. */
  1043. $location = apply_filters( 'wp_redirect', $location, $status );
  1044. /**
  1045. * Filter the redirect status code.
  1046. *
  1047. * @since 2.3.0
  1048. *
  1049. * @param int $status Status code to use.
  1050. * @param string $location The path to redirect to.
  1051. */
  1052. $status = apply_filters( 'wp_redirect_status', $status, $location );
  1053. if ( ! $location )
  1054. return false;
  1055. $location = wp_sanitize_redirect($location);
  1056. if ( !$is_IIS && PHP_SAPI != 'cgi-fcgi' )
  1057. status_header($status); // This causes problems on IIS and some FastCGI setups
  1058. header("Location: $location", true, $status);
  1059. return true;
  1060. }
  1061. endif;
  1062. if ( !function_exists('wp_sanitize_redirect') ) :
  1063. /**
  1064. * Sanitizes a URL for use in a redirect.
  1065. *
  1066. * @since 2.3.0
  1067. *
  1068. * @return string redirect-sanitized URL
  1069. **/
  1070. function wp_sanitize_redirect($location) {
  1071. $regex = '/
  1072. (
  1073. (?: [\xC2-\xDF][\x80-\xBF] # double-byte sequences 110xxxxx 10xxxxxx
  1074. | \xE0[\xA0-\xBF][\x80-\xBF] # triple-byte sequences 1110xxxx 10xxxxxx * 2
  1075. | [\xE1-\xEC][\x80-\xBF]{2}
  1076. | \xED[\x80-\x9F][\x80-\xBF]
  1077. | [\xEE-\xEF][\x80-\xBF]{2}
  1078. | \xF0[\x90-\xBF][\x80-\xBF]{2} # four-byte sequences 11110xxx 10xxxxxx * 3
  1079. | [\xF1-\xF3][\x80-\xBF]{3}
  1080. | \xF4[\x80-\x8F][\x80-\xBF]{2}
  1081. ){1,40} # ...one or more times
  1082. )/x';
  1083. $location = preg_replace_callback( $regex, '_wp_sanitize_utf8_in_redirect', $location );
  1084. $location = preg_replace('|[^a-z0-9-~+_.?#=&;,/:%!*\[\]()]|i', '', $location);
  1085. $location = wp_kses_no_null($location);
  1086. // remove %0d and %0a from location
  1087. $strip = array('%0d', '%0a', '%0D', '%0A');
  1088. return _deep_replace( $strip, $location );
  1089. }
  1090. /**
  1091. * URL encode UTF-8 characters in a URL.
  1092. *
  1093. * @ignore
  1094. * @since 4.2.0
  1095. * @access private
  1096. *
  1097. * @see wp_sanitize_redirect()
  1098. */
  1099. function _wp_sanitize_utf8_in_redirect( $matches ) {
  1100. return urlencode( $matches[0] );
  1101. }
  1102. endif;
  1103. if ( !function_exists('wp_safe_redirect') ) :
  1104. /**
  1105. * Performs a safe (local) redirect, using wp_redirect().
  1106. *
  1107. * Checks whether the $location is using an allowed host, if it has an absolute
  1108. * path. A plugin can therefore set or remove allowed host(s) to or from the
  1109. * list.
  1110. *
  1111. * If the host is not allowed, then the redirect defaults to wp-admin on the siteurl
  1112. * instead. This prevents malicious redirects which redirect to another host,
  1113. * but only used in a few places.
  1114. *
  1115. * @since 2.3.0
  1116. */
  1117. function wp_safe_redirect($location, $status = 302) {
  1118. // Need to look at the URL the way it will end up in wp_redirect()
  1119. $location = wp_sanitize_redirect($location);
  1120. /**
  1121. * Filter the redirect fallback URL for when the provided redirect is not safe (local).
  1122. *
  1123. * @since 4.3.0
  1124. *
  1125. * @param string $fallback_url The fallback URL to use by default.
  1126. * @param int $status The redirect status.
  1127. */
  1128. $location = wp_validate_redirect( $location, apply_filters( 'wp_safe_redirect_fallback', admin_url(), $status ) );
  1129. wp_redirect($location, $status);
  1130. }
  1131. endif;
  1132. if ( !function_exists('wp_validate_redirect') ) :
  1133. /**
  1134. * Validates a URL for use in a redirect.
  1135. *
  1136. * Checks whether the $location is using an allowed host, if it has an absolute
  1137. * path. A plugin can therefore set or remove allowed host(s) to or from the
  1138. * list.
  1139. *
  1140. * If the host is not allowed, then the redirect is to $default supplied
  1141. *
  1142. * @since 2.8.1
  1143. *
  1144. * @param string $location The redirect to validate
  1145. * @param string $default The value to return if $location is not allowed
  1146. * @return string redirect-sanitized URL
  1147. **/
  1148. function wp_validate_redirect($location, $default = '') {
  1149. $location = trim( $location );
  1150. // browsers will assume 'http' is your protocol, and will obey a redirect to a URL starting with '//'
  1151. if ( substr($location, 0, 2) == '//' )
  1152. $location = 'http:' . $location;
  1153. // In php 5 parse_url may fail if the URL query part contains http://, bug #38143
  1154. $test = ( $cut = strpos($location, '?') ) ? substr( $location, 0, $cut ) : $location;
  1155. $lp = parse_url($test);
  1156. // Give up if malformed URL
  1157. if ( false === $lp )
  1158. return $default;
  1159. // Allow only http and https schemes. No data:, etc.
  1160. if ( isset($lp['scheme']) && !('http' == $lp['scheme'] || 'https' == $lp['scheme']) )
  1161. return $default;
  1162. // Reject if scheme is set but host is not. This catches urls like https:host.com for which parse_url does not set the host field.
  1163. if ( isset($lp['scheme']) && !isset($lp['host']) )
  1164. return $default;
  1165. $wpp = parse_url(home_url());
  1166. /**
  1167. * Filter the whitelist of hosts to redirect to.
  1168. *
  1169. * @since 2.3.0
  1170. *
  1171. * @param array $hosts An array of allowed hosts.
  1172. * @param bool|string $host The parsed host; empty if not isset.
  1173. */
  1174. $allowed_hosts = (array) apply_filters( 'allowed_redirect_hosts', array($wpp['host']), isset($lp['host']) ? $lp['host'] : '' );
  1175. if ( isset($lp['host']) && ( !in_array($lp['host'], $allowed_hosts) && $lp['host'] != strtolower($wpp['host'])) )
  1176. $location = $default;
  1177. return $location;
  1178. }
  1179. endif;
  1180. if ( ! function_exists('wp_notify_postauthor') ) :
  1181. /**
  1182. * Notify an author (and/or others) of a comment/trackback/pingback on a post.
  1183. *
  1184. * @since 1.0.0
  1185. *
  1186. * @param int $comment_id Comment ID
  1187. * @param string $deprecated Not used
  1188. * @return bool True on completion. False if no email addresses were specified.
  1189. */
  1190. function wp_notify_postauthor( $comment_id, $deprecated = null ) {
  1191. if ( null !== $deprecated ) {
  1192. _deprecated_argument( __FUNCTION__, '3.8' );
  1193. }
  1194. $comment = get_comment( $comment_id );
  1195. if ( empty( $comment ) )
  1196. return false;
  1197. $post = get_post( $comment->comment_post_ID );
  1198. $author = get_userdata( $post->post_author );
  1199. // Who to notify? By default, just the post author, but others can be added.
  1200. $emails = array();
  1201. if ( $author ) {
  1202. $emails[] = $author->user_email;
  1203. }
  1204. /**
  1205. * Filter the list of email addresses to receive a comment notification.
  1206. *
  1207. * By default, only post authors are notified of comments. This filter allows
  1208. * others to be added.
  1209. *
  1210. * @since 3.7.0
  1211. *
  1212. * @param array $emails An array of email addresses to receive a comment notification.
  1213. * @param int $comment_id The comment ID.
  1214. */
  1215. $emails = apply_filters( 'comment_notification_recipients', $emails, $comment_id );
  1216. $emails = array_filter( $emails );
  1217. // If there are no addresses to send the comment to, bail.
  1218. if ( ! count( $emails ) ) {
  1219. return false;
  1220. }
  1221. // Facilitate unsetting below without knowing the keys.
  1222. $emails = array_flip( $emails );
  1223. /**
  1224. * Filter whether to notify comment authors of their comments on their own posts.
  1225. *
  1226. * By default, comment authors aren't notified of their comments on their own
  1227. * posts. This filter allows you to override that.
  1228. *
  1229. * @since 3.8.0
  1230. *
  1231. * @param bool $notify Whether to notify the post author of their own comment.
  1232. * Default false.
  1233. * @param int $comment_id The comment ID.
  1234. */
  1235. $notify_author = apply_filters( 'comment_notification_notify_author', false, $comment_id );
  1236. // The comment was left by the author
  1237. if ( $author && ! $notify_author && $comment->user_id == $post->post_author ) {
  1238. unset( $emails[ $author->user_email ] );
  1239. }
  1240. // The author moderated a comment on their own post
  1241. if ( $author && ! $notify_author && $post->post_author == get_current_user_id() ) {
  1242. unset( $emails[ $author->user_email ] );
  1243. }
  1244. // The post author is no longer a member of the blog
  1245. if ( $author && ! $notify_author && ! user_can( $post->post_author, 'read_post', $post->ID ) ) {
  1246. unset( $emails[ $author->user_email ] );
  1247. }
  1248. // If there's no email to send the comment to, bail, otherwise flip array back around for use below
  1249. if ( ! count( $emails ) ) {
  1250. return false;
  1251. } else {
  1252. $emails = array_flip( $emails );
  1253. }
  1254. $comment_author_domain = @gethostbyaddr($comment->comment_author_IP);
  1255. // The blogname option is escaped with esc_html on the way into the database in sanitize_option
  1256. // we want to reverse this for the plain text arena of emails.
  1257. $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
  1258. switch ( $comment->comment_type ) {
  1259. case 'trackback':
  1260. $notify_message = sprintf( __( 'New trackback on your post "%s"' ), $post->post_title ) . "\r\n";
  1261. /* translators: 1: website name, 2: website IP, 3: website hostname */
  1262. $notify_message .= sprintf( __('Website: %1$s (IP: %2$s, %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
  1263. $notify_message .= sprintf( __( 'URL: %s' ), $comment->comment_author_url ) . "\r\n";
  1264. $notify_message .= sprintf( __( 'Comment: %s' ), "\r\n" . $comment->comment_content ) . "\r\n\r\n";
  1265. $notify_message .= __( 'You can see all trackbacks on this post here:' ) . "\r\n";
  1266. /* translators: 1: blog name, 2: post title */
  1267. $subject = sprintf( __('[%1$s] Trackback: "%2$s"'), $blogname, $post->post_title );
  1268. break;
  1269. case 'pingback':
  1270. $notify_message = sprintf( __( 'New pingback on your post "%s"' ), $post->post_title ) . "\r\n";
  1271. /* translators: 1: website name, 2: website IP, 3: website hostname */
  1272. $notify_message .= sprintf( __('Website: %1$s (IP: %2$s, %3$s)'), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
  1273. $notify_message .= sprintf( __( 'URL: %s' ), $comment->comment_author_url ) . "\r\n";
  1274. $notify_message .= sprintf( __( 'Comment: %s' ), "\r\n" . $comment->comment_content ) . "\r\n\r\n";
  1275. $notify_message .= __( 'You can see all pingbacks on this post here:' ) . "\r\n";
  1276. /* translators: 1: blog name, 2: post title */
  1277. $subject = sprintf( __('[%1$s] Pingback: "%2$s"'), $blogname, $post->post_title );
  1278. break;
  1279. default: // Comments
  1280. $notify_message = sprintf( __( 'New comment on your post "%s"' ), $post->post_title ) . "\r\n";
  1281. /* translators: 1: comment author, 2: author IP, 3: author domain */
  1282. $notify_message .= sprintf( __( 'Author: %1$s (IP: %2$s, %3$s)' ), $comment->comment_author, $comment->comment_author_IP, $comment_author_domain ) . "\r\n";
  1283. $notify_message .= sprintf( __( 'E-mail: %s' ), $comment->comment_author_email ) . "\r\n";
  1284. $notify_message .= sprintf( __( 'URL: %s' ), $comment->comment_author_url ) . "\r\n";
  1285. $notify_message .= sprintf( __('Comment: %s' ), "\r\n" . $comment->comment_content ) . "\r\n\r\n";
  1286. $notify_message .= __( 'You can see all comments on this post here:' ) . "\r\n";
  1287. /* translators: 1: blog name, 2: post title */
  1288. $subject = sprintf( __('[%1$s] Comment: "%2$s"'), $blogname, $post->post_title );
  1289. break;
  1290. }
  1291. $notify_message .= get_permalink($comment->comment_post_ID) . "#comments\r\n\r\n";
  1292. $notify_message .= sprintf( __('Permalink: %s'), get_comment_link( $comment_id ) ) . "\r\n";
  1293. if ( user_can( $post->post_author, 'edit_comment', $comment_id ) ) {
  1294. if ( EMPTY_TRASH_DAYS )
  1295. $notify_message .= sprintf( __('Trash it: %s'), admin_url("comment.php?action=trash&c=$comment_id") ) . "\r\n";
  1296. else
  1297. $notify_message .= sprintf( __('Delete it: %s'), admin_url("comment.php?action=delete&c=$comment_id") ) . "\r\n";
  1298. $notify_message .= sprintf( __('Spam it: %s'), admin_url("comment.php?action=spam&c=$comment_id") ) . "\r\n";
  1299. }
  1300. $wp_email = 'wordpress@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME']));
  1301. if ( '' == $comment->comment_author ) {
  1302. $from = "From: \"$blogname\" <$wp_email>";
  1303. if ( '' != $comment->comment_author_email )
  1304. $reply_to = "Reply-To: $comment->comment_author_email";
  1305. } else {
  1306. $from = "From: \"$comment->comment_author\" <$wp_email>";
  1307. if ( '' != $comment->comment_author_email )
  1308. $reply_to = "Reply-To: \"$comment->comment_author_email\" <$comment->comment_author_email>";
  1309. }
  1310. $message_headers = "$from\n"
  1311. . "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
  1312. if ( isset($reply_to) )
  1313. $message_headers .= $reply_to . "\n";
  1314. /**
  1315. * Filter the comment notification email text.
  1316. *
  1317. * @since 1.5.2
  1318. *
  1319. * @param string $notify_message The comment notification email text.
  1320. * @param int $comment_id Comment ID.
  1321. */
  1322. $notify_message = apply_filters( 'comment_notification_text', $notify_message, $comment_id );
  1323. /**
  1324. * Filter the comment notification email subject.
  1325. *
  1326. * @since 1.5.2
  1327. *
  1328. * @param string $subject The comment notification email subject.
  1329. * @param int $comment_id Comment ID.
  1330. */
  1331. $subject = apply_filters( 'comment_notification_subject', $subject, $comment_id );
  1332. /**
  1333. * Filter the comment notification email headers.
  1334. *
  1335. * @since 1.5.2
  1336. *
  1337. * @param string $message_headers Headers for the comment notification email.
  1338. * @param int $comment_id Comment ID.
  1339. */
  1340. $message_headers = apply_filters( 'comment_notification_headers', $message_headers, $comment_id );
  1341. foreach ( $emails as $email ) {
  1342. @wp_mail( $email, wp_specialchars_decode( $subject ), $notify_message, $message_headers );
  1343. }
  1344. return true;
  1345. }
  1346. endif;
  1347. if ( !function_exists('wp_notify_moderator') ) :
  1348. /**
  1349. * Notifies the moderator of the blog about a new comment that is awaiting approval.
  1350. *
  1351. * @since 1.0.0
  1352. *
  1353. * @global wpdb $wpdb WordPress database abstraction object.
  1354. *
  1355. * @param int $comment_id Comment ID
  1356. * @return true Always returns true
  1357. */
  1358. function wp_notify_moderator($comment_id) {
  1359. global $wpdb;
  1360. if ( 0 == get_option( 'moderation_notify' ) )
  1361. return true;
  1362. $comment = get_comment($comment_id);
  1363. $post = get_post($comment->comment_post_ID);
  1364. $user = get_userdata( $post->post_author );
  1365. // Send to the administration and to the post author if the author can modify the comment.
  1366. $emails = array( get_option( 'admin_email' ) );
  1367. if ( $user && user_can( $user->ID, 'edit_comment', $comment_id ) && ! empty( $user->user_email ) ) {
  1368. if ( 0 !== strcasecmp( $user->user_email, get_option( 'admin_email' ) ) )
  1369. $emails[] = $user->user_email;
  1370. }
  1371. $comment_author_domain = @gethostbyaddr($comment->comment_author_IP);
  1372. $comments_waiting = $wpdb->get_var("SELECT count(comment_ID) FROM $wpdb->comments WHERE comment_approved = '0'");
  1373. // The blogname option is escaped with esc_html on the way into the database in sanitize_option
  1374. // we want to reverse