Advertisement
Guest User

Untitled

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