You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

2498 regels
84 KiB

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