PageRenderTime 56ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/comment.php

http://github.com/wordpress/wordpress
PHP | 3726 lines | 1689 code | 442 blank | 1595 comment | 349 complexity | 89a7e224fb8b33b30509a244f32f3d64 MD5 | raw file
Possible License(s): 0BSD
  1. <?php
  2. /**
  3. * Core Comment API
  4. *
  5. * @package WordPress
  6. * @subpackage Comment
  7. */
  8. /**
  9. * Check whether a comment passes internal checks to be allowed to add.
  10. *
  11. * If manual comment moderation is set in the administration, then all checks,
  12. * regardless of their type and whitelist, will fail and the function will
  13. * return false.
  14. *
  15. * If the number of links exceeds the amount in the administration, then the
  16. * check fails. If any of the parameter contents match the blacklist of words,
  17. * then the check fails.
  18. *
  19. * If the comment author was approved before, then the comment is automatically
  20. * whitelisted.
  21. *
  22. * If all checks pass, the function will return true.
  23. *
  24. * @since 1.2.0
  25. *
  26. * @global wpdb $wpdb WordPress database abstraction object.
  27. *
  28. * @param string $author Comment author name.
  29. * @param string $email Comment author email.
  30. * @param string $url Comment author URL.
  31. * @param string $comment Content of the comment.
  32. * @param string $user_ip Comment author IP address.
  33. * @param string $user_agent Comment author User-Agent.
  34. * @param string $comment_type Comment type, either user-submitted comment,
  35. * trackback, or pingback.
  36. * @return bool If all checks pass, true, otherwise false.
  37. */
  38. function check_comment( $author, $email, $url, $comment, $user_ip, $user_agent, $comment_type ) {
  39. global $wpdb;
  40. // If manual moderation is enabled, skip all checks and return false.
  41. if ( 1 == get_option( 'comment_moderation' ) ) {
  42. return false;
  43. }
  44. /** This filter is documented in wp-includes/comment-template.php */
  45. $comment = apply_filters( 'comment_text', $comment, null, array() );
  46. // Check for the number of external links if a max allowed number is set.
  47. $max_links = get_option( 'comment_max_links' );
  48. if ( $max_links ) {
  49. $num_links = preg_match_all( '/<a [^>]*href/i', $comment, $out );
  50. /**
  51. * Filters the number of links found in a comment.
  52. *
  53. * @since 3.0.0
  54. * @since 4.7.0 Added the `$comment` parameter.
  55. *
  56. * @param int $num_links The number of links found.
  57. * @param string $url Comment author's URL. Included in allowed links total.
  58. * @param string $comment Content of the comment.
  59. */
  60. $num_links = apply_filters( 'comment_max_links_url', $num_links, $url, $comment );
  61. /*
  62. * If the number of links in the comment exceeds the allowed amount,
  63. * fail the check by returning false.
  64. */
  65. if ( $num_links >= $max_links ) {
  66. return false;
  67. }
  68. }
  69. $mod_keys = trim( get_option( 'moderation_keys' ) );
  70. // If moderation 'keys' (keywords) are set, process them.
  71. if ( ! empty( $mod_keys ) ) {
  72. $words = explode( "\n", $mod_keys );
  73. foreach ( (array) $words as $word ) {
  74. $word = trim( $word );
  75. // Skip empty lines.
  76. if ( empty( $word ) ) {
  77. continue;
  78. }
  79. /*
  80. * Do some escaping magic so that '#' (number of) characters in the spam
  81. * words don't break things:
  82. */
  83. $word = preg_quote( $word, '#' );
  84. /*
  85. * Check the comment fields for moderation keywords. If any are found,
  86. * fail the check for the given field by returning false.
  87. */
  88. $pattern = "#$word#i";
  89. if ( preg_match( $pattern, $author ) ) {
  90. return false;
  91. }
  92. if ( preg_match( $pattern, $email ) ) {
  93. return false;
  94. }
  95. if ( preg_match( $pattern, $url ) ) {
  96. return false;
  97. }
  98. if ( preg_match( $pattern, $comment ) ) {
  99. return false;
  100. }
  101. if ( preg_match( $pattern, $user_ip ) ) {
  102. return false;
  103. }
  104. if ( preg_match( $pattern, $user_agent ) ) {
  105. return false;
  106. }
  107. }
  108. }
  109. /*
  110. * Check if the option to approve comments by previously-approved authors is enabled.
  111. *
  112. * If it is enabled, check whether the comment author has a previously-approved comment,
  113. * as well as whether there are any moderation keywords (if set) present in the author
  114. * email address. If both checks pass, return true. Otherwise, return false.
  115. */
  116. if ( 1 == get_option( 'comment_whitelist' ) ) {
  117. if ( 'trackback' !== $comment_type && 'pingback' !== $comment_type && '' != $author && '' != $email ) {
  118. $comment_user = get_user_by( 'email', wp_unslash( $email ) );
  119. if ( ! empty( $comment_user->ID ) ) {
  120. $ok_to_comment = $wpdb->get_var( $wpdb->prepare( "SELECT comment_approved FROM $wpdb->comments WHERE user_id = %d AND comment_approved = '1' LIMIT 1", $comment_user->ID ) );
  121. } else {
  122. // expected_slashed ($author, $email)
  123. $ok_to_comment = $wpdb->get_var( $wpdb->prepare( "SELECT comment_approved FROM $wpdb->comments WHERE comment_author = %s AND comment_author_email = %s and comment_approved = '1' LIMIT 1", $author, $email ) );
  124. }
  125. if ( ( 1 == $ok_to_comment ) &&
  126. ( empty( $mod_keys ) || false === strpos( $email, $mod_keys ) ) ) {
  127. return true;
  128. } else {
  129. return false;
  130. }
  131. } else {
  132. return false;
  133. }
  134. }
  135. return true;
  136. }
  137. /**
  138. * Retrieve the approved comments for post $post_id.
  139. *
  140. * @since 2.0.0
  141. * @since 4.1.0 Refactored to leverage WP_Comment_Query over a direct query.
  142. *
  143. * @param int $post_id The ID of the post.
  144. * @param array $args Optional. See WP_Comment_Query::__construct() for information on accepted arguments.
  145. * @return int|array $comments The approved comments, or number of comments if `$count`
  146. * argument is true.
  147. */
  148. function get_approved_comments( $post_id, $args = array() ) {
  149. if ( ! $post_id ) {
  150. return array();
  151. }
  152. $defaults = array(
  153. 'status' => 1,
  154. 'post_id' => $post_id,
  155. 'order' => 'ASC',
  156. );
  157. $parsed_args = wp_parse_args( $args, $defaults );
  158. $query = new WP_Comment_Query;
  159. return $query->query( $parsed_args );
  160. }
  161. /**
  162. * Retrieves comment data given a comment ID or comment object.
  163. *
  164. * If an object is passed then the comment data will be cached and then returned
  165. * after being passed through a filter. If the comment is empty, then the global
  166. * comment variable will be used, if it is set.
  167. *
  168. * @since 2.0.0
  169. *
  170. * @global WP_Comment $comment Global comment object.
  171. *
  172. * @param WP_Comment|string|int $comment Comment to retrieve.
  173. * @param string $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which correspond to
  174. * a WP_Comment object, an associative array, or a numeric array, respectively. Default OBJECT.
  175. * @return WP_Comment|array|null Depends on $output value.
  176. */
  177. function get_comment( &$comment = null, $output = OBJECT ) {
  178. if ( empty( $comment ) && isset( $GLOBALS['comment'] ) ) {
  179. $comment = $GLOBALS['comment'];
  180. }
  181. if ( $comment instanceof WP_Comment ) {
  182. $_comment = $comment;
  183. } elseif ( is_object( $comment ) ) {
  184. $_comment = new WP_Comment( $comment );
  185. } else {
  186. $_comment = WP_Comment::get_instance( $comment );
  187. }
  188. if ( ! $_comment ) {
  189. return null;
  190. }
  191. /**
  192. * Fires after a comment is retrieved.
  193. *
  194. * @since 2.3.0
  195. *
  196. * @param WP_Comment $_comment Comment data.
  197. */
  198. $_comment = apply_filters( 'get_comment', $_comment );
  199. if ( OBJECT == $output ) {
  200. return $_comment;
  201. } elseif ( ARRAY_A == $output ) {
  202. return $_comment->to_array();
  203. } elseif ( ARRAY_N == $output ) {
  204. return array_values( $_comment->to_array() );
  205. }
  206. return $_comment;
  207. }
  208. /**
  209. * Retrieve a list of comments.
  210. *
  211. * The comment list can be for the blog as a whole or for an individual post.
  212. *
  213. * @since 2.7.0
  214. *
  215. * @param string|array $args Optional. Array or string of arguments. See WP_Comment_Query::__construct()
  216. * for information on accepted arguments. Default empty.
  217. * @return int|array List of comments or number of found comments if `$count` argument is true.
  218. */
  219. function get_comments( $args = '' ) {
  220. $query = new WP_Comment_Query;
  221. return $query->query( $args );
  222. }
  223. /**
  224. * Retrieve all of the WordPress supported comment statuses.
  225. *
  226. * Comments have a limited set of valid status values, this provides the comment
  227. * status values and descriptions.
  228. *
  229. * @since 2.7.0
  230. *
  231. * @return string[] List of comment status labels keyed by status.
  232. */
  233. function get_comment_statuses() {
  234. $status = array(
  235. 'hold' => __( 'Unapproved' ),
  236. 'approve' => _x( 'Approved', 'comment status' ),
  237. 'spam' => _x( 'Spam', 'comment status' ),
  238. 'trash' => _x( 'Trash', 'comment status' ),
  239. );
  240. return $status;
  241. }
  242. /**
  243. * Gets the default comment status for a post type.
  244. *
  245. * @since 4.3.0
  246. *
  247. * @param string $post_type Optional. Post type. Default 'post'.
  248. * @param string $comment_type Optional. Comment type. Default 'comment'.
  249. * @return string Expected return value is 'open' or 'closed'.
  250. */
  251. function get_default_comment_status( $post_type = 'post', $comment_type = 'comment' ) {
  252. switch ( $comment_type ) {
  253. case 'pingback':
  254. case 'trackback':
  255. $supports = 'trackbacks';
  256. $option = 'ping';
  257. break;
  258. default:
  259. $supports = 'comments';
  260. $option = 'comment';
  261. break;
  262. }
  263. // Set the status.
  264. if ( 'page' === $post_type ) {
  265. $status = 'closed';
  266. } elseif ( post_type_supports( $post_type, $supports ) ) {
  267. $status = get_option( "default_{$option}_status" );
  268. } else {
  269. $status = 'closed';
  270. }
  271. /**
  272. * Filters the default comment status for the given post type.
  273. *
  274. * @since 4.3.0
  275. *
  276. * @param string $status Default status for the given post type,
  277. * either 'open' or 'closed'.
  278. * @param string $post_type Post type. Default is `post`.
  279. * @param string $comment_type Type of comment. Default is `comment`.
  280. */
  281. return apply_filters( 'get_default_comment_status', $status, $post_type, $comment_type );
  282. }
  283. /**
  284. * The date the last comment was modified.
  285. *
  286. * @since 1.5.0
  287. * @since 4.7.0 Replaced caching the modified date in a local static variable
  288. * with the Object Cache API.
  289. *
  290. * @global wpdb $wpdb WordPress database abstraction object.
  291. *
  292. * @param string $timezone Which timezone to use in reference to 'gmt', 'blog', or 'server' locations.
  293. * @return string|false Last comment modified date on success, false on failure.
  294. */
  295. function get_lastcommentmodified( $timezone = 'server' ) {
  296. global $wpdb;
  297. $timezone = strtolower( $timezone );
  298. $key = "lastcommentmodified:$timezone";
  299. $comment_modified_date = wp_cache_get( $key, 'timeinfo' );
  300. if ( false !== $comment_modified_date ) {
  301. return $comment_modified_date;
  302. }
  303. switch ( $timezone ) {
  304. case 'gmt':
  305. $comment_modified_date = $wpdb->get_var( "SELECT comment_date_gmt FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1" );
  306. break;
  307. case 'blog':
  308. $comment_modified_date = $wpdb->get_var( "SELECT comment_date FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1" );
  309. break;
  310. case 'server':
  311. $add_seconds_server = gmdate( 'Z' );
  312. $comment_modified_date = $wpdb->get_var( $wpdb->prepare( "SELECT DATE_ADD(comment_date_gmt, INTERVAL %s SECOND) FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1", $add_seconds_server ) );
  313. break;
  314. }
  315. if ( $comment_modified_date ) {
  316. wp_cache_set( $key, $comment_modified_date, 'timeinfo' );
  317. return $comment_modified_date;
  318. }
  319. return false;
  320. }
  321. /**
  322. * Retrieves the total comment counts for the whole site or a single post.
  323. *
  324. * Unlike wp_count_comments(), this function always returns the live comment counts without caching.
  325. *
  326. * @since 2.0.0
  327. *
  328. * @global wpdb $wpdb WordPress database abstraction object.
  329. *
  330. * @param int $post_id Optional. Restrict the comment counts to the given post. Default 0, which indicates that
  331. * comment counts for the whole site will be retrieved.
  332. * @return array() {
  333. * The number of comments keyed by their status.
  334. *
  335. * @type int $approved The number of approved comments.
  336. * @type int $awaiting_moderation The number of comments awaiting moderation (a.k.a. pending).
  337. * @type int $spam The number of spam comments.
  338. * @type int $trash The number of trashed comments.
  339. * @type int $post-trashed The number of comments for posts that are in the trash.
  340. * @type int $total_comments The total number of non-trashed comments, including spam.
  341. * @type int $all The total number of pending or approved comments.
  342. * }
  343. */
  344. function get_comment_count( $post_id = 0 ) {
  345. global $wpdb;
  346. $post_id = (int) $post_id;
  347. $where = '';
  348. if ( $post_id > 0 ) {
  349. $where = $wpdb->prepare( 'WHERE comment_post_ID = %d', $post_id );
  350. }
  351. $totals = (array) $wpdb->get_results(
  352. "
  353. SELECT comment_approved, COUNT( * ) AS total
  354. FROM {$wpdb->comments}
  355. {$where}
  356. GROUP BY comment_approved
  357. ",
  358. ARRAY_A
  359. );
  360. $comment_count = array(
  361. 'approved' => 0,
  362. 'awaiting_moderation' => 0,
  363. 'spam' => 0,
  364. 'trash' => 0,
  365. 'post-trashed' => 0,
  366. 'total_comments' => 0,
  367. 'all' => 0,
  368. );
  369. foreach ( $totals as $row ) {
  370. switch ( $row['comment_approved'] ) {
  371. case 'trash':
  372. $comment_count['trash'] = $row['total'];
  373. break;
  374. case 'post-trashed':
  375. $comment_count['post-trashed'] = $row['total'];
  376. break;
  377. case 'spam':
  378. $comment_count['spam'] = $row['total'];
  379. $comment_count['total_comments'] += $row['total'];
  380. break;
  381. case '1':
  382. $comment_count['approved'] = $row['total'];
  383. $comment_count['total_comments'] += $row['total'];
  384. $comment_count['all'] += $row['total'];
  385. break;
  386. case '0':
  387. $comment_count['awaiting_moderation'] = $row['total'];
  388. $comment_count['total_comments'] += $row['total'];
  389. $comment_count['all'] += $row['total'];
  390. break;
  391. default:
  392. break;
  393. }
  394. }
  395. return array_map( 'intval', $comment_count );
  396. }
  397. //
  398. // Comment meta functions.
  399. //
  400. /**
  401. * Add meta data field to a comment.
  402. *
  403. * @since 2.9.0
  404. * @link https://developer.wordpress.org/reference/functions/add_comment_meta/
  405. *
  406. * @param int $comment_id Comment ID.
  407. * @param string $meta_key Metadata name.
  408. * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
  409. * @param bool $unique Optional. Whether the same key should not be added.
  410. * Default false.
  411. * @return int|bool Meta ID on success, false on failure.
  412. */
  413. function add_comment_meta( $comment_id, $meta_key, $meta_value, $unique = false ) {
  414. return add_metadata( 'comment', $comment_id, $meta_key, $meta_value, $unique );
  415. }
  416. /**
  417. * Remove metadata matching criteria from a comment.
  418. *
  419. * You can match based on the key, or key and value. Removing based on key and
  420. * value, will keep from removing duplicate metadata with the same key. It also
  421. * allows removing all metadata matching key, if needed.
  422. *
  423. * @since 2.9.0
  424. * @link https://developer.wordpress.org/reference/functions/delete_comment_meta/
  425. *
  426. * @param int $comment_id Comment ID.
  427. * @param string $meta_key Metadata name.
  428. * @param mixed $meta_value Optional. Metadata value. If provided,
  429. * rows will only be removed that match the value.
  430. * Must be serializable if non-scalar. Default empty.
  431. * @return bool True on success, false on failure.
  432. */
  433. function delete_comment_meta( $comment_id, $meta_key, $meta_value = '' ) {
  434. return delete_metadata( 'comment', $comment_id, $meta_key, $meta_value );
  435. }
  436. /**
  437. * Retrieve comment meta field for a comment.
  438. *
  439. * @since 2.9.0
  440. * @link https://developer.wordpress.org/reference/functions/get_comment_meta/
  441. *
  442. * @param int $comment_id Comment ID.
  443. * @param string $key Optional. The meta key to retrieve. By default,
  444. * returns data for all keys.
  445. * @param bool $single Optional. Whether to return a single value.
  446. * This parameter has no effect if $key is not specified.
  447. * Default false.
  448. * @return mixed An array if $single is false. The value of meta data field
  449. * if $single is true.
  450. */
  451. function get_comment_meta( $comment_id, $key = '', $single = false ) {
  452. return get_metadata( 'comment', $comment_id, $key, $single );
  453. }
  454. /**
  455. * Update comment meta field based on comment ID.
  456. *
  457. * Use the $prev_value parameter to differentiate between meta fields with the
  458. * same key and comment ID.
  459. *
  460. * If the meta field for the comment does not exist, it will be added.
  461. *
  462. * @since 2.9.0
  463. * @link https://developer.wordpress.org/reference/functions/update_comment_meta/
  464. *
  465. * @param int $comment_id Comment ID.
  466. * @param string $meta_key Metadata key.
  467. * @param mixed $meta_value Metadata value. Must be serializable if non-scalar.
  468. * @param mixed $prev_value Optional. Previous value to check before updating.
  469. * Default empty.
  470. * @return int|bool Meta ID if the key didn't exist, true on successful update,
  471. * false on failure.
  472. */
  473. function update_comment_meta( $comment_id, $meta_key, $meta_value, $prev_value = '' ) {
  474. return update_metadata( 'comment', $comment_id, $meta_key, $meta_value, $prev_value );
  475. }
  476. /**
  477. * Queues comments for metadata lazy-loading.
  478. *
  479. * @since 4.5.0
  480. *
  481. * @param WP_Comment[] $comments Array of comment objects.
  482. */
  483. function wp_queue_comments_for_comment_meta_lazyload( $comments ) {
  484. // Don't use `wp_list_pluck()` to avoid by-reference manipulation.
  485. $comment_ids = array();
  486. if ( is_array( $comments ) ) {
  487. foreach ( $comments as $comment ) {
  488. if ( $comment instanceof WP_Comment ) {
  489. $comment_ids[] = $comment->comment_ID;
  490. }
  491. }
  492. }
  493. if ( $comment_ids ) {
  494. $lazyloader = wp_metadata_lazyloader();
  495. $lazyloader->queue_objects( 'comment', $comment_ids );
  496. }
  497. }
  498. /**
  499. * Sets the cookies used to store an unauthenticated commentator's identity. Typically used
  500. * to recall previous comments by this commentator that are still held in moderation.
  501. *
  502. * @since 3.4.0
  503. * @since 4.9.6 The `$cookies_consent` parameter was added.
  504. *
  505. * @param WP_Comment $comment Comment object.
  506. * @param WP_User $user Comment author's user object. The user may not exist.
  507. * @param boolean $cookies_consent Optional. Comment author's consent to store cookies. Default true.
  508. */
  509. function wp_set_comment_cookies( $comment, $user, $cookies_consent = true ) {
  510. // If the user already exists, or the user opted out of cookies, don't set cookies.
  511. if ( $user->exists() ) {
  512. return;
  513. }
  514. if ( false === $cookies_consent ) {
  515. // Remove any existing cookies.
  516. $past = time() - YEAR_IN_SECONDS;
  517. setcookie( 'comment_author_' . COOKIEHASH, ' ', $past, COOKIEPATH, COOKIE_DOMAIN );
  518. setcookie( 'comment_author_email_' . COOKIEHASH, ' ', $past, COOKIEPATH, COOKIE_DOMAIN );
  519. setcookie( 'comment_author_url_' . COOKIEHASH, ' ', $past, COOKIEPATH, COOKIE_DOMAIN );
  520. return;
  521. }
  522. /**
  523. * Filters the lifetime of the comment cookie in seconds.
  524. *
  525. * @since 2.8.0
  526. *
  527. * @param int $seconds Comment cookie lifetime. Default 30000000.
  528. */
  529. $comment_cookie_lifetime = time() + apply_filters( 'comment_cookie_lifetime', 30000000 );
  530. $secure = ( 'https' === parse_url( home_url(), PHP_URL_SCHEME ) );
  531. setcookie( 'comment_author_' . COOKIEHASH, $comment->comment_author, $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure );
  532. setcookie( 'comment_author_email_' . COOKIEHASH, $comment->comment_author_email, $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure );
  533. setcookie( 'comment_author_url_' . COOKIEHASH, esc_url( $comment->comment_author_url ), $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure );
  534. }
  535. /**
  536. * Sanitizes the cookies sent to the user already.
  537. *
  538. * Will only do anything if the cookies have already been created for the user.
  539. * Mostly used after cookies had been sent to use elsewhere.
  540. *
  541. * @since 2.0.4
  542. */
  543. function sanitize_comment_cookies() {
  544. if ( isset( $_COOKIE[ 'comment_author_' . COOKIEHASH ] ) ) {
  545. /**
  546. * Filters the comment author's name cookie before it is set.
  547. *
  548. * When this filter hook is evaluated in wp_filter_comment(),
  549. * the comment author's name string is passed.
  550. *
  551. * @since 1.5.0
  552. *
  553. * @param string $author_cookie The comment author name cookie.
  554. */
  555. $comment_author = apply_filters( 'pre_comment_author_name', $_COOKIE[ 'comment_author_' . COOKIEHASH ] );
  556. $comment_author = wp_unslash( $comment_author );
  557. $comment_author = esc_attr( $comment_author );
  558. $_COOKIE[ 'comment_author_' . COOKIEHASH ] = $comment_author;
  559. }
  560. if ( isset( $_COOKIE[ 'comment_author_email_' . COOKIEHASH ] ) ) {
  561. /**
  562. * Filters the comment author's email cookie before it is set.
  563. *
  564. * When this filter hook is evaluated in wp_filter_comment(),
  565. * the comment author's email string is passed.
  566. *
  567. * @since 1.5.0
  568. *
  569. * @param string $author_email_cookie The comment author email cookie.
  570. */
  571. $comment_author_email = apply_filters( 'pre_comment_author_email', $_COOKIE[ 'comment_author_email_' . COOKIEHASH ] );
  572. $comment_author_email = wp_unslash( $comment_author_email );
  573. $comment_author_email = esc_attr( $comment_author_email );
  574. $_COOKIE[ 'comment_author_email_' . COOKIEHASH ] = $comment_author_email;
  575. }
  576. if ( isset( $_COOKIE[ 'comment_author_url_' . COOKIEHASH ] ) ) {
  577. /**
  578. * Filters the comment author's URL cookie before it is set.
  579. *
  580. * When this filter hook is evaluated in wp_filter_comment(),
  581. * the comment author's URL string is passed.
  582. *
  583. * @since 1.5.0
  584. *
  585. * @param string $author_url_cookie The comment author URL cookie.
  586. */
  587. $comment_author_url = apply_filters( 'pre_comment_author_url', $_COOKIE[ 'comment_author_url_' . COOKIEHASH ] );
  588. $comment_author_url = wp_unslash( $comment_author_url );
  589. $_COOKIE[ 'comment_author_url_' . COOKIEHASH ] = $comment_author_url;
  590. }
  591. }
  592. /**
  593. * Validates whether this comment is allowed to be made.
  594. *
  595. * @since 2.0.0
  596. * @since 4.7.0 The `$avoid_die` parameter was added, allowing the function to
  597. * return a WP_Error object instead of dying.
  598. *
  599. * @global wpdb $wpdb WordPress database abstraction object.
  600. *
  601. * @param array $commentdata Contains information on the comment.
  602. * @param bool $avoid_die When true, a disallowed comment will result in the function
  603. * returning a WP_Error object, rather than executing wp_die().
  604. * Default false.
  605. * @return int|string|WP_Error Allowed comments return the approval status (0|1|'spam'|'trash').
  606. * If `$avoid_die` is true, disallowed comments return a WP_Error.
  607. */
  608. function wp_allow_comment( $commentdata, $avoid_die = false ) {
  609. global $wpdb;
  610. // Simple duplicate check.
  611. // expected_slashed ($comment_post_ID, $comment_author, $comment_author_email, $comment_content)
  612. $dupe = $wpdb->prepare(
  613. "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_parent = %s AND comment_approved != 'trash' AND ( comment_author = %s ",
  614. wp_unslash( $commentdata['comment_post_ID'] ),
  615. wp_unslash( $commentdata['comment_parent'] ),
  616. wp_unslash( $commentdata['comment_author'] )
  617. );
  618. if ( $commentdata['comment_author_email'] ) {
  619. $dupe .= $wpdb->prepare(
  620. 'AND comment_author_email = %s ',
  621. wp_unslash( $commentdata['comment_author_email'] )
  622. );
  623. }
  624. $dupe .= $wpdb->prepare(
  625. ') AND comment_content = %s LIMIT 1',
  626. wp_unslash( $commentdata['comment_content'] )
  627. );
  628. $dupe_id = $wpdb->get_var( $dupe );
  629. /**
  630. * Filters the ID, if any, of the duplicate comment found when creating a new comment.
  631. *
  632. * Return an empty value from this filter to allow what WP considers a duplicate comment.
  633. *
  634. * @since 4.4.0
  635. *
  636. * @param int $dupe_id ID of the comment identified as a duplicate.
  637. * @param array $commentdata Data for the comment being created.
  638. */
  639. $dupe_id = apply_filters( 'duplicate_comment_id', $dupe_id, $commentdata );
  640. if ( $dupe_id ) {
  641. /**
  642. * Fires immediately after a duplicate comment is detected.
  643. *
  644. * @since 3.0.0
  645. *
  646. * @param array $commentdata Comment data.
  647. */
  648. do_action( 'comment_duplicate_trigger', $commentdata );
  649. /**
  650. * Filters duplicate comment error message.
  651. *
  652. * @since 5.2.0
  653. *
  654. * @param string $comment_duplicate_message Duplicate comment error message.
  655. */
  656. $comment_duplicate_message = apply_filters( 'comment_duplicate_message', __( 'Duplicate comment detected; it looks as though you&#8217;ve already said that!' ) );
  657. if ( true === $avoid_die ) {
  658. return new WP_Error( 'comment_duplicate', $comment_duplicate_message, 409 );
  659. } else {
  660. if ( wp_doing_ajax() ) {
  661. die( $comment_duplicate_message );
  662. }
  663. wp_die( $comment_duplicate_message, 409 );
  664. }
  665. }
  666. /**
  667. * Fires immediately before a comment is marked approved.
  668. *
  669. * Allows checking for comment flooding.
  670. *
  671. * @since 2.3.0
  672. * @since 4.7.0 The `$avoid_die` parameter was added.
  673. *
  674. * @param string $comment_author_IP Comment author's IP address.
  675. * @param string $comment_author_email Comment author's email.
  676. * @param string $comment_date_gmt GMT date the comment was posted.
  677. * @param bool $avoid_die Whether to prevent executing wp_die()
  678. * or die() if a comment flood is occurring.
  679. */
  680. do_action(
  681. 'check_comment_flood',
  682. $commentdata['comment_author_IP'],
  683. $commentdata['comment_author_email'],
  684. $commentdata['comment_date_gmt'],
  685. $avoid_die
  686. );
  687. /**
  688. * Filters whether a comment is part of a comment flood.
  689. *
  690. * The default check is wp_check_comment_flood(). See check_comment_flood_db().
  691. *
  692. * @since 4.7.0
  693. *
  694. * @param bool $is_flood Is a comment flooding occurring? Default false.
  695. * @param string $comment_author_IP Comment author's IP address.
  696. * @param string $comment_author_email Comment author's email.
  697. * @param string $comment_date_gmt GMT date the comment was posted.
  698. * @param bool $avoid_die Whether to prevent executing wp_die()
  699. * or die() if a comment flood is occurring.
  700. */
  701. $is_flood = apply_filters(
  702. 'wp_is_comment_flood',
  703. false,
  704. $commentdata['comment_author_IP'],
  705. $commentdata['comment_author_email'],
  706. $commentdata['comment_date_gmt'],
  707. $avoid_die
  708. );
  709. if ( $is_flood ) {
  710. /** This filter is documented in wp-includes/comment-template.php */
  711. $comment_flood_message = apply_filters( 'comment_flood_message', __( 'You are posting comments too quickly. Slow down.' ) );
  712. return new WP_Error( 'comment_flood', $comment_flood_message, 429 );
  713. }
  714. if ( ! empty( $commentdata['user_id'] ) ) {
  715. $user = get_userdata( $commentdata['user_id'] );
  716. $post_author = $wpdb->get_var(
  717. $wpdb->prepare(
  718. "SELECT post_author FROM $wpdb->posts WHERE ID = %d LIMIT 1",
  719. $commentdata['comment_post_ID']
  720. )
  721. );
  722. }
  723. if ( isset( $user ) && ( $commentdata['user_id'] == $post_author || $user->has_cap( 'moderate_comments' ) ) ) {
  724. // The author and the admins get respect.
  725. $approved = 1;
  726. } else {
  727. // Everyone else's comments will be checked.
  728. if ( check_comment(
  729. $commentdata['comment_author'],
  730. $commentdata['comment_author_email'],
  731. $commentdata['comment_author_url'],
  732. $commentdata['comment_content'],
  733. $commentdata['comment_author_IP'],
  734. $commentdata['comment_agent'],
  735. $commentdata['comment_type']
  736. ) ) {
  737. $approved = 1;
  738. } else {
  739. $approved = 0;
  740. }
  741. if ( wp_blacklist_check(
  742. $commentdata['comment_author'],
  743. $commentdata['comment_author_email'],
  744. $commentdata['comment_author_url'],
  745. $commentdata['comment_content'],
  746. $commentdata['comment_author_IP'],
  747. $commentdata['comment_agent']
  748. ) ) {
  749. $approved = EMPTY_TRASH_DAYS ? 'trash' : 'spam';
  750. }
  751. }
  752. /**
  753. * Filters a comment's approval status before it is set.
  754. *
  755. * @since 2.1.0
  756. * @since 4.9.0 Returning a WP_Error value from the filter will shortcircuit comment insertion
  757. * and allow skipping further processing.
  758. *
  759. * @param int|string|WP_Error $approved The approval status. Accepts 1, 0, 'spam', 'trash',
  760. * or WP_Error.
  761. * @param array $commentdata Comment data.
  762. */
  763. return apply_filters( 'pre_comment_approved', $approved, $commentdata );
  764. }
  765. /**
  766. * Hooks WP's native database-based comment-flood check.
  767. *
  768. * This wrapper maintains backward compatibility with plugins that expect to
  769. * be able to unhook the legacy check_comment_flood_db() function from
  770. * 'check_comment_flood' using remove_action().
  771. *
  772. * @since 2.3.0
  773. * @since 4.7.0 Converted to be an add_filter() wrapper.
  774. */
  775. function check_comment_flood_db() {
  776. add_filter( 'wp_is_comment_flood', 'wp_check_comment_flood', 10, 5 );
  777. }
  778. /**
  779. * Checks whether comment flooding is occurring.
  780. *
  781. * Won't run, if current user can manage options, so to not block
  782. * administrators.
  783. *
  784. * @since 4.7.0
  785. *
  786. * @global wpdb $wpdb WordPress database abstraction object.
  787. *
  788. * @param bool $is_flood Is a comment flooding occurring?
  789. * @param string $ip Comment author's IP address.
  790. * @param string $email Comment author's email address.
  791. * @param string $date MySQL time string.
  792. * @param bool $avoid_die When true, a disallowed comment will result in the function
  793. * returning a WP_Error object, rather than executing wp_die().
  794. * Default false.
  795. * @return bool Whether comment flooding is occurring.
  796. */
  797. function wp_check_comment_flood( $is_flood, $ip, $email, $date, $avoid_die = false ) {
  798. global $wpdb;
  799. // Another callback has declared a flood. Trust it.
  800. if ( true === $is_flood ) {
  801. return $is_flood;
  802. }
  803. // Don't throttle admins or moderators.
  804. if ( current_user_can( 'manage_options' ) || current_user_can( 'moderate_comments' ) ) {
  805. return false;
  806. }
  807. $hour_ago = gmdate( 'Y-m-d H:i:s', time() - HOUR_IN_SECONDS );
  808. if ( is_user_logged_in() ) {
  809. $user = get_current_user_id();
  810. $check_column = '`user_id`';
  811. } else {
  812. $user = $ip;
  813. $check_column = '`comment_author_IP`';
  814. }
  815. $sql = $wpdb->prepare(
  816. "SELECT `comment_date_gmt` FROM `$wpdb->comments` WHERE `comment_date_gmt` >= %s AND ( $check_column = %s OR `comment_author_email` = %s ) ORDER BY `comment_date_gmt` DESC LIMIT 1",
  817. $hour_ago,
  818. $user,
  819. $email
  820. );
  821. $lasttime = $wpdb->get_var( $sql );
  822. if ( $lasttime ) {
  823. $time_lastcomment = mysql2date( 'U', $lasttime, false );
  824. $time_newcomment = mysql2date( 'U', $date, false );
  825. /**
  826. * Filters the comment flood status.
  827. *
  828. * @since 2.1.0
  829. *
  830. * @param bool $bool Whether a comment flood is occurring. Default false.
  831. * @param int $time_lastcomment Timestamp of when the last comment was posted.
  832. * @param int $time_newcomment Timestamp of when the new comment was posted.
  833. */
  834. $flood_die = apply_filters( 'comment_flood_filter', false, $time_lastcomment, $time_newcomment );
  835. if ( $flood_die ) {
  836. /**
  837. * Fires before the comment flood message is triggered.
  838. *
  839. * @since 1.5.0
  840. *
  841. * @param int $time_lastcomment Timestamp of when the last comment was posted.
  842. * @param int $time_newcomment Timestamp of when the new comment was posted.
  843. */
  844. do_action( 'comment_flood_trigger', $time_lastcomment, $time_newcomment );
  845. if ( true === $avoid_die ) {
  846. return true;
  847. } else {
  848. /**
  849. * Filters the comment flood error message.
  850. *
  851. * @since 5.2.0
  852. *
  853. * @param string $comment_flood_message Comment flood error message.
  854. */
  855. $comment_flood_message = apply_filters( 'comment_flood_message', __( 'You are posting comments too quickly. Slow down.' ) );
  856. if ( wp_doing_ajax() ) {
  857. die( $comment_flood_message );
  858. }
  859. wp_die( $comment_flood_message, 429 );
  860. }
  861. }
  862. }
  863. return false;
  864. }
  865. /**
  866. * Separates an array of comments into an array keyed by comment_type.
  867. *
  868. * @since 2.7.0
  869. *
  870. * @param WP_Comment[] $comments Array of comments
  871. * @return WP_Comment[] Array of comments keyed by comment_type.
  872. */
  873. function separate_comments( &$comments ) {
  874. $comments_by_type = array(
  875. 'comment' => array(),
  876. 'trackback' => array(),
  877. 'pingback' => array(),
  878. 'pings' => array(),
  879. );
  880. $count = count( $comments );
  881. for ( $i = 0; $i < $count; $i++ ) {
  882. $type = $comments[ $i ]->comment_type;
  883. if ( empty( $type ) ) {
  884. $type = 'comment';
  885. }
  886. $comments_by_type[ $type ][] = &$comments[ $i ];
  887. if ( 'trackback' == $type || 'pingback' == $type ) {
  888. $comments_by_type['pings'][] = &$comments[ $i ];
  889. }
  890. }
  891. return $comments_by_type;
  892. }
  893. /**
  894. * Calculate the total number of comment pages.
  895. *
  896. * @since 2.7.0
  897. *
  898. * @uses Walker_Comment
  899. *
  900. * @global WP_Query $wp_query WordPress Query object.
  901. *
  902. * @param WP_Comment[] $comments Optional. Array of WP_Comment objects. Defaults to $wp_query->comments.
  903. * @param int $per_page Optional. Comments per page.
  904. * @param bool $threaded Optional. Control over flat or threaded comments.
  905. * @return int Number of comment pages.
  906. */
  907. function get_comment_pages_count( $comments = null, $per_page = null, $threaded = null ) {
  908. global $wp_query;
  909. if ( null === $comments && null === $per_page && null === $threaded && ! empty( $wp_query->max_num_comment_pages ) ) {
  910. return $wp_query->max_num_comment_pages;
  911. }
  912. if ( ( ! $comments || ! is_array( $comments ) ) && ! empty( $wp_query->comments ) ) {
  913. $comments = $wp_query->comments;
  914. }
  915. if ( empty( $comments ) ) {
  916. return 0;
  917. }
  918. if ( ! get_option( 'page_comments' ) ) {
  919. return 1;
  920. }
  921. if ( ! isset( $per_page ) ) {
  922. $per_page = (int) get_query_var( 'comments_per_page' );
  923. }
  924. if ( 0 === $per_page ) {
  925. $per_page = (int) get_option( 'comments_per_page' );
  926. }
  927. if ( 0 === $per_page ) {
  928. return 1;
  929. }
  930. if ( ! isset( $threaded ) ) {
  931. $threaded = get_option( 'thread_comments' );
  932. }
  933. if ( $threaded ) {
  934. $walker = new Walker_Comment;
  935. $count = ceil( $walker->get_number_of_root_elements( $comments ) / $per_page );
  936. } else {
  937. $count = ceil( count( $comments ) / $per_page );
  938. }
  939. return $count;
  940. }
  941. /**
  942. * Calculate what page number a comment will appear on for comment paging.
  943. *
  944. * @since 2.7.0
  945. *
  946. * @global wpdb $wpdb WordPress database abstraction object.
  947. *
  948. * @param int $comment_ID Comment ID.
  949. * @param array $args {
  950. * Array of optional arguments.
  951. * @type string $type Limit paginated comments to those matching a given type. Accepts 'comment',
  952. * 'trackback', 'pingback', 'pings' (trackbacks and pingbacks), or 'all'.
  953. * Default is 'all'.
  954. * @type int $per_page Per-page count to use when calculating pagination. Defaults to the value of the
  955. * 'comments_per_page' option.
  956. * @type int|string $max_depth If greater than 1, comment page will be determined for the top-level parent of
  957. * `$comment_ID`. Defaults to the value of the 'thread_comments_depth' option.
  958. * } *
  959. * @return int|null Comment page number or null on error.
  960. */
  961. function get_page_of_comment( $comment_ID, $args = array() ) {
  962. global $wpdb;
  963. $page = null;
  964. $comment = get_comment( $comment_ID );
  965. if ( ! $comment ) {
  966. return;
  967. }
  968. $defaults = array(
  969. 'type' => 'all',
  970. 'page' => '',
  971. 'per_page' => '',
  972. 'max_depth' => '',
  973. );
  974. $args = wp_parse_args( $args, $defaults );
  975. $original_args = $args;
  976. // Order of precedence: 1. `$args['per_page']`, 2. 'comments_per_page' query_var, 3. 'comments_per_page' option.
  977. if ( get_option( 'page_comments' ) ) {
  978. if ( '' === $args['per_page'] ) {
  979. $args['per_page'] = get_query_var( 'comments_per_page' );
  980. }
  981. if ( '' === $args['per_page'] ) {
  982. $args['per_page'] = get_option( 'comments_per_page' );
  983. }
  984. }
  985. if ( empty( $args['per_page'] ) ) {
  986. $args['per_page'] = 0;
  987. $args['page'] = 0;
  988. }
  989. if ( $args['per_page'] < 1 ) {
  990. $page = 1;
  991. }
  992. if ( null === $page ) {
  993. if ( '' === $args['max_depth'] ) {
  994. if ( get_option( 'thread_comments' ) ) {
  995. $args['max_depth'] = get_option( 'thread_comments_depth' );
  996. } else {
  997. $args['max_depth'] = -1;
  998. }
  999. }
  1000. // Find this comment's top-level parent if threading is enabled.
  1001. if ( $args['max_depth'] > 1 && 0 != $comment->comment_parent ) {
  1002. return get_page_of_comment( $comment->comment_parent, $args );
  1003. }
  1004. $comment_args = array(
  1005. 'type' => $args['type'],
  1006. 'post_id' => $comment->comment_post_ID,
  1007. 'fields' => 'ids',
  1008. 'count' => true,
  1009. 'status' => 'approve',
  1010. 'parent' => 0,
  1011. 'date_query' => array(
  1012. array(
  1013. 'column' => "$wpdb->comments.comment_date_gmt",
  1014. 'before' => $comment->comment_date_gmt,
  1015. ),
  1016. ),
  1017. );
  1018. $comment_query = new WP_Comment_Query();
  1019. $older_comment_count = $comment_query->query( $comment_args );
  1020. // No older comments? Then it's page #1.
  1021. if ( 0 == $older_comment_count ) {
  1022. $page = 1;
  1023. // Divide comments older than this one by comments per page to get this comment's page number.
  1024. } else {
  1025. $page = ceil( ( $older_comment_count + 1 ) / $args['per_page'] );
  1026. }
  1027. }
  1028. /**
  1029. * Filters the calculated page on which a comment appears.
  1030. *
  1031. * @since 4.4.0
  1032. * @since 4.7.0 Introduced the `$comment_ID` parameter.
  1033. *
  1034. * @param int $page Comment page.
  1035. * @param array $args {
  1036. * Arguments used to calculate pagination. These include arguments auto-detected by the function,
  1037. * based on query vars, system settings, etc. For pristine arguments passed to the function,
  1038. * see `$original_args`.
  1039. *
  1040. * @type string $type Type of comments to count.
  1041. * @type int $page Calculated current page.
  1042. * @type int $per_page Calculated number of comments per page.
  1043. * @type int $max_depth Maximum comment threading depth allowed.
  1044. * }
  1045. * @param array $original_args {
  1046. * Array of arguments passed to the function. Some or all of these may not be set.
  1047. *
  1048. * @type string $type Type of comments to count.
  1049. * @type int $page Current comment page.
  1050. * @type int $per_page Number of comments per page.
  1051. * @type int $max_depth Maximum comment threading depth allowed.
  1052. * }
  1053. * @param int $comment_ID ID of the comment.
  1054. */
  1055. return apply_filters( 'get_page_of_comment', (int) $page, $args, $original_args, $comment_ID );
  1056. }
  1057. /**
  1058. * Retrieves the maximum character lengths for the comment form fields.
  1059. *
  1060. * @since 4.5.0
  1061. *
  1062. * @global wpdb $wpdb WordPress database abstraction object.
  1063. *
  1064. * @return int[] Array of maximum lengths keyed by field name.
  1065. */
  1066. function wp_get_comment_fields_max_lengths() {
  1067. global $wpdb;
  1068. $lengths = array(
  1069. 'comment_author' => 245,
  1070. 'comment_author_email' => 100,
  1071. 'comment_author_url' => 200,
  1072. 'comment_content' => 65525,
  1073. );
  1074. if ( $wpdb->is_mysql ) {
  1075. foreach ( $lengths as $column => $length ) {
  1076. $col_length = $wpdb->get_col_length( $wpdb->comments, $column );
  1077. $max_length = 0;
  1078. // No point if we can't get the DB column lengths.
  1079. if ( is_wp_error( $col_length ) ) {
  1080. break;
  1081. }
  1082. if ( ! is_array( $col_length ) && (int) $col_length > 0 ) {
  1083. $max_length = (int) $col_length;
  1084. } elseif ( is_array( $col_length ) && isset( $col_length['length'] ) && intval( $col_length['length'] ) > 0 ) {
  1085. $max_length = (int) $col_length['length'];
  1086. if ( ! empty( $col_length['type'] ) && 'byte' === $col_length['type'] ) {
  1087. $max_length = $max_length - 10;
  1088. }
  1089. }
  1090. if ( $max_length > 0 ) {
  1091. $lengths[ $column ] = $max_length;
  1092. }
  1093. }
  1094. }
  1095. /**
  1096. * Filters the lengths for the comment form fields.
  1097. *
  1098. * @since 4.5.0
  1099. *
  1100. * @param int[] $lengths Array of maximum lengths keyed by field name.
  1101. */
  1102. return apply_filters( 'wp_get_comment_fields_max_lengths', $lengths );
  1103. }
  1104. /**
  1105. * Compares the lengths of comment data against the maximum character limits.
  1106. *
  1107. * @since 4.7.0
  1108. *
  1109. * @param array $comment_data Array of arguments for inserting a comment.
  1110. * @return WP_Error|true WP_Error when a comment field exceeds the limit,
  1111. * otherwise true.
  1112. */
  1113. function wp_check_comment_data_max_lengths( $comment_data ) {
  1114. $max_lengths = wp_get_comment_fields_max_lengths();
  1115. if ( isset( $comment_data['comment_author'] ) && mb_strlen( $comment_data['comment_author'], '8bit' ) > $max_lengths['comment_author'] ) {
  1116. return new WP_Error( 'comment_author_column_length', __( '<strong>Error</strong>: Your name is too long.' ), 200 );
  1117. }
  1118. if ( isset( $comment_data['comment_author_email'] ) && strlen( $comment_data['comment_author_email'] ) > $max_lengths['comment_author_email'] ) {
  1119. return new WP_Error( 'comment_author_email_column_length', __( '<strong>Error</strong>: Your email address is too long.' ), 200 );
  1120. }
  1121. if ( isset( $comment_data['comment_author_url'] ) && strlen( $comment_data['comment_author_url'] ) > $max_lengths['comment_author_url'] ) {
  1122. return new WP_Error( 'comment_author_url_column_length', __( '<strong>Error</strong>: Your URL is too long.' ), 200 );
  1123. }
  1124. if ( isset( $comment_data['comment_content'] ) && mb_strlen( $comment_data['comment_content'], '8bit' ) > $max_lengths['comment_content'] ) {
  1125. return new WP_Error( 'comment_content_column_length', __( '<strong>Error</strong>: Your comment is too long.' ), 200 );
  1126. }
  1127. return true;
  1128. }
  1129. /**
  1130. * Does comment contain blacklisted characters or words.
  1131. *
  1132. * @since 1.5.0
  1133. *
  1134. * @param string $author The author of the comment
  1135. * @param string $email The email of the comment
  1136. * @param string $url The url used in the comment
  1137. * @param string $comment The comment content
  1138. * @param string $user_ip The comment author's IP address
  1139. * @param string $user_agent The author's browser user agent
  1140. * @return bool True if comment contains blacklisted content, false if comment does not
  1141. */
  1142. function wp_blacklist_check( $author, $email, $url, $comment, $user_ip, $user_agent ) {
  1143. /**
  1144. * Fires before the comment is tested for blacklisted characters or words.
  1145. *
  1146. * @since 1.5.0
  1147. *
  1148. * @param string $author Comment author.
  1149. * @param string $email Comment author's email.
  1150. * @param string $url Comment author's URL.
  1151. * @param string $comment Comment content.
  1152. * @param string $user_ip Comment author's IP address.
  1153. * @param string $user_agent Comment author's browser user agent.
  1154. */
  1155. do_action( 'wp_blacklist_check', $author, $email, $url, $comment, $user_ip, $user_agent );
  1156. $mod_keys = trim( get_option( 'blacklist_keys' ) );
  1157. if ( '' == $mod_keys ) {
  1158. return false; // If moderation keys are empty.
  1159. }
  1160. // Ensure HTML tags are not being used to bypass the blacklist.
  1161. $comment_without_html = wp_strip_all_tags( $comment );
  1162. $words = explode( "\n", $mod_keys );
  1163. foreach ( (array) $words as $word ) {
  1164. $word = trim( $word );
  1165. // Skip empty lines.
  1166. if ( empty( $word ) ) {
  1167. continue; }
  1168. // Do some escaping magic so that '#' chars
  1169. // in the spam words don't break things:
  1170. $word = preg_quote( $word, '#' );
  1171. $pattern = "#$word#i";
  1172. if ( preg_match( $pattern, $author )
  1173. || preg_match( $pattern, $email )
  1174. || preg_match( $pattern, $url )
  1175. || preg_match( $pattern, $comment )
  1176. || preg_match( $pattern, $comment_without_html )
  1177. || preg_match( $pattern, $user_ip )
  1178. || preg_match( $pattern, $user_agent )
  1179. ) {
  1180. return true;
  1181. }
  1182. }
  1183. return false;
  1184. }
  1185. /**
  1186. * Retrieves the total comment counts for the whole site or a single post.
  1187. *
  1188. * The comment stats are cached and then retrieved, if they already exist in the
  1189. * cache.
  1190. *
  1191. * @see get_comment_count() Which handles fetching the live comment counts.
  1192. *
  1193. * @since 2.5.0
  1194. *
  1195. * @param int $post_id Optional. Restrict the comment counts to the given post. Default 0, which indicates that
  1196. * comment counts for the whole site will be retrieved.
  1197. * @return stdClass {
  1198. * The number of comments keyed by their status.
  1199. *
  1200. * @type int $approved The number of approved comments.
  1201. * @type int $moderated The number of comments awaiting moderation (a.k.a. pending).
  1202. * @type int $spam The number of spam comments.
  1203. * @type int $trash The number of trashed comments.
  1204. * @type int $post-trashed The number of comments for posts that are in the trash.
  1205. * @type int $total_comments The total number of non-trashed comments, including spam.
  1206. * @type int $all The total number of pending or approved comments.
  1207. * }
  1208. */
  1209. function wp_count_comments( $post_id = 0 ) {
  1210. $post_id = (int) $post_id;
  1211. /**
  1212. * Filters the comments count for a given post or the whole site.
  1213. *
  1214. * @since 2.7.0
  1215. *
  1216. * @param array|stdClass $count An empty array or an object containing comment counts.
  1217. * @param int $post_id The post ID. Can be 0 to represent the whole site.
  1218. */
  1219. $filtered = apply_filters( 'wp_count_comments', array(), $post_id );
  1220. if ( ! empty( $filtered ) ) {
  1221. return $filtered;
  1222. }
  1223. $count = wp_cache_get( "comments-{$post_id}", 'counts' );
  1224. if ( false !== $count ) {
  1225. return $count;
  1226. }
  1227. $stats = get_comment_count( $post_id );
  1228. $stats['moderated'] = $stats['awaiting_moderation'];
  1229. unset( $stats['awaiting_moderation'] );
  1230. $stats_object = (object) $stats;
  1231. wp_cache_set( "comments-{$post_id}", $stats_object, 'counts' );
  1232. return $stats_object;
  1233. }
  1234. /**
  1235. * Trashes or deletes a comment.
  1236. *
  1237. * The comment is moved to Trash instead of permanently deleted unless Trash is
  1238. * disabled, item is already in the Trash, or $force_delete is true.
  1239. *
  1240. * The post comment count will be updated if the comment was approved and has a
  1241. * post ID available.
  1242. *
  1243. * @since 2.0.0
  1244. *
  1245. * @global wpdb $wpdb WordPress database abstraction object.
  1246. *
  1247. * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
  1248. * @param bool $force_delete Whether to bypass Trash and force deletion. Default is false.
  1249. * @return bool True on success, false on failure.
  1250. */
  1251. function wp_delete_comment( $comment_id, $force_delete = false ) {
  1252. global $wpdb;
  1253. $comment = get_comment( $comment_id );
  1254. if ( ! $comment ) {
  1255. return false;
  1256. }
  1257. if ( ! $force_delete && EMPTY_TRASH_DAYS && ! in_array( wp_get_comment_status( $comment ), array( 'trash', 'spam' ), true ) ) {
  1258. return wp_trash_comment( $comment_id );
  1259. }
  1260. /**
  1261. * Fires immediately before a comment is deleted from the database.
  1262. *
  1263. * @since 1.2.0
  1264. * @since 4.9.0 Added the `$comment` parameter.
  1265. *
  1266. * @param int $comment_id The comment ID.
  1267. * @param WP_Comment $comment The comment to be deleted.
  1268. */
  1269. do_action( 'delete_comment', $comment->comment_ID, $comment );
  1270. // Move children up a level.
  1271. $children = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_parent = %d", $comment->comment_ID ) );
  1272. if ( ! empty( $children ) ) {
  1273. $wpdb->update( $wpdb->comments, array( 'comment_parent' => $comment->comment_parent ), array( 'comment_parent' => $comment->comment_ID ) );
  1274. clean_comment_cache( $children );
  1275. }
  1276. // Delete metadata.
  1277. $meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->commentmeta WHERE comment_id = %d", $comment->comment_ID ) );
  1278. foreach ( $meta_ids as $mid ) {
  1279. delete_metadata_by_mid( 'comment', $mid );
  1280. }
  1281. if ( ! $wpdb->delete( $wpdb->comments, array( 'comment_ID' => $comment->comment_ID ) ) ) {
  1282. return false;
  1283. }
  1284. /**
  1285. * Fires immediately after a comment is deleted from the database.
  1286. *
  1287. * @since 2.9.0
  1288. * @since 4.9.0 Added the `$comment` parameter.
  1289. *
  1290. * @param int $comment_id The comment ID.
  1291. * @param WP_Comment $comment The deleted comment.
  1292. */
  1293. do_action( 'deleted_comment', $comment->comment_ID, $comment );
  1294. $post_id = $comment->comment_post_ID;
  1295. if ( $post_id && 1 == $comment->comment_approved ) {
  1296. wp_update_comment_count( $post_id );
  1297. }
  1298. clean_comment_cache( $comment->comment_ID );
  1299. /** This action is documented in wp-includes/comment.php */
  1300. do_action( 'wp_set_comment_status', $comment->comment_ID, 'delete' );
  1301. wp_transition_comment_status( 'delete', $comment->comment_approved, $comment );
  1302. return true;
  1303. }
  1304. /**
  1305. * Moves a comment to the Trash
  1306. *
  1307. * If Trash is disabled, comment is permanently deleted.
  1308. *
  1309. * @since 2.9.0
  1310. *
  1311. * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
  1312. * @return bool True on success, false on failure.
  1313. */
  1314. function wp_trash_comment( $comment_id ) {
  1315. if ( ! EMPTY_TRASH_DAYS ) {
  1316. return wp_delete_comment( $comment_id, true );
  1317. }
  1318. $comment = get_comment( $comment_id );
  1319. if ( ! $comment ) {
  1320. return false;
  1321. }
  1322. /**
  1323. * Fires immediately before a comment is sent to the Trash.
  1324. *
  1325. * @since 2.9.0
  1326. * @since 4.9.0 Added the `$comment` parameter.
  1327. *
  1328. * @param int $comment_id The comment ID.
  1329. * @param WP_Comment $comment The comment to be trashed.
  1330. */
  1331. do_action( 'trash_comment', $comment->comment_ID, $comment );
  1332. if ( wp_set_comment_status( $comment, 'trash' ) ) {
  1333. delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_status' );
  1334. delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_time' );
  1335. add_comment_meta( $comment->comment_ID, '_wp_trash_meta_status', $comment->comment_approved );
  1336. add_comment_meta( $comment->comment_ID, '_wp_trash_meta_time', time() );
  1337. /**
  1338. * Fires immediately after a comment is sent to Trash.
  1339. *
  1340. * @since 2.9.0
  1341. * @since 4.9.0 Added the `$comment` parameter.
  1342. *
  1343. * @param int $comment_id The comment ID.
  1344. * @param WP_Comment $comment The trashed comment.
  1345. */
  1346. do_action( 'trashed_comment', $comment->comment_ID, $comment );
  1347. return true;
  1348. }
  1349. return false;
  1350. }
  1351. /**
  1352. * Removes a comment from the Trash
  1353. *
  1354. * @since 2.9.0
  1355. *
  1356. * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
  1357. * @return bool True on success, false on failure.
  1358. */
  1359. function wp_untrash_comment( $comment_id ) {
  1360. $comment = get_comment( $comment_id );
  1361. if ( ! $comment ) {
  1362. return false;
  1363. }
  1364. /**
  1365. * Fires immediately before a comment is restored from the Trash.
  1366. *
  1367. * @since 2.9.0
  1368. * @since 4.9.0 Added the `$comment` parameter.
  1369. *
  1370. * @param int $comment_id The comment ID.
  1371. * @param WP_Comment $comment The comment to be untrashed.
  1372. */
  1373. do_action( 'untrash_comment', $comment->comment_ID, $comment );
  1374. $status = (string) get_comment_meta( $comment->comment_ID, '_wp_trash_meta_status', true );
  1375. if ( empty( $status ) ) {
  1376. $status = '0';
  1377. }
  1378. if ( wp_set_comment_status( $comment, $status ) ) {
  1379. delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_time' );
  1380. delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_status' );
  1381. /**
  1382. * Fires immediately after a comment is restored from the Trash.
  1383. *
  1384. * @since 2.9.0
  1385. * @since 4.9.0 Added the `$comment` parameter.
  1386. *
  1387. * @param int $comment_id The comment ID.
  1388. * @param WP_Comment $comment The untrashed comment.
  1389. */
  1390. do_action( 'untrashed_comment', $comment->comment_ID, $comment );
  1391. return true;
  1392. }
  1393. return false;
  1394. }
  1395. /**
  1396. * Marks a comment as Spam
  1397. *
  1398. * @since 2.9.0
  1399. *
  1400. * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
  1401. * @return bool True on success, false on failure.
  1402. */
  1403. function wp_spam_comment( $comment_id ) {
  1404. $comment = get_comment( $comment_id );
  1405. if ( ! $comment ) {
  1406. return false;
  1407. }
  1408. /**
  1409. * Fires immediately before a comment is marked as Spam.
  1410. *
  1411. * @since 2.9.0
  1412. * @since 4.9.0 Added the `$comment` parameter.
  1413. *
  1414. * @param int $comment_id The comment ID.
  1415. * @param WP_Comment $comment The comment to be marked as spam.
  1416. */
  1417. do_action( 'spam_comment', $comment->comment_ID, $comment );
  1418. if ( wp_set_comment_status( $comment, 'spam' ) ) {
  1419. delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_status' );
  1420. delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_time' );
  1421. add_comment_meta( $comment->comment_ID, '_wp_trash_meta_status', $comment->comment_approved );
  1422. add_comment_meta( $comment->comment_ID, '_wp_trash_meta_time', time() );
  1423. /**
  1424. * Fires immediately after a comment is marked as Spam.
  1425. *
  1426. * @since 2.9.0
  1427. * @since 4.9.0 Added the `$comment` parameter.
  1428. *
  1429. * @param int $comment_id The comment ID.
  1430. * @param WP_Comment $comment The comment marked as spam.
  1431. */
  1432. do_action( 'spammed_comment', $comment->comment_ID, $comment );
  1433. return true;
  1434. }
  1435. return false;
  1436. }
  1437. /**
  1438. * Removes a comment from the Spam
  1439. *
  1440. * @since 2.9.0
  1441. *
  1442. * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
  1443. * @return bool True on success, false on failure.
  1444. */
  1445. function wp_unspam_comment( $comment_id ) {
  1446. $comment = get_comment( $comment_id );
  1447. if ( ! $comment ) {
  1448. return false;
  1449. }
  1450. /**
  1451. * Fires immediately before a comment is unmarked as Spam.
  1452. *
  1453. * @since 2.9.0
  1454. * @since 4.9.0 Added the `$comment` parameter.
  1455. *
  1456. * @param int $comment_id The comment ID.
  1457. * @param WP_Comment $comment The comment to be unmarked as spam.
  1458. */
  1459. do_action( 'unspam_comment', $comment->comment_ID, $comment );
  1460. $status = (string) get_comment_meta( $comment->comment_ID, '_wp_trash_meta_status', true );
  1461. if ( empty( $status ) ) {
  1462. $status = '0';
  1463. }
  1464. if ( wp_set_comment_status( $comment, $status ) ) {
  1465. delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_status' );
  1466. delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_time' );
  1467. /**
  1468. * Fires immediately after a comment is unmarked as Spam.
  1469. *
  1470. * @since 2.9.0
  1471. * @since 4.9.0 Added the `$comment` parameter.
  1472. *
  1473. * @param int $comment_id The comment ID.
  1474. * @param WP_Comment $comment The comment unmarked as spam.
  1475. */
  1476. do_action( 'unspammed_comment', $comment->comment_ID, $comment );
  1477. return true;
  1478. }
  1479. return false;
  1480. }
  1481. /**
  1482. * The status of a comment by ID.
  1483. *
  1484. * @since 1.0.0
  1485. *
  1486. * @param int|WP_Comment $comment_id Comment ID or WP_Comment object
  1487. * @return string|false Status might be 'trash', 'approved', 'unapproved', 'spam'. False on failure.
  1488. */
  1489. function wp_get_comment_status( $comment_id ) {
  1490. $comment = get_comment( $comment_id );
  1491. if ( ! $comment ) {
  1492. return false;
  1493. }
  1494. $approved = $comment->comment_approved;
  1495. if ( null == $approved ) {
  1496. return false;
  1497. } elseif ( '1' == $approved ) {
  1498. return 'approved';
  1499. } elseif ( '0' == $approved ) {
  1500. return 'unapproved';
  1501. } elseif ( 'spam' == $approved ) {
  1502. return 'spam';
  1503. } elseif ( 'trash' == $approved ) {
  1504. return 'trash';
  1505. } else {
  1506. return false;
  1507. }
  1508. }
  1509. /**
  1510. * Call hooks for when a comment status transition occurs.
  1511. *
  1512. * Calls hooks for comment status transitions. If the new comment status is not the same
  1513. * as the previous comment status, then two hooks will be ran, the first is
  1514. * {@see 'transition_comment_status'} with new status, old status, and comment data.
  1515. * The next action called is {@see 'comment_$old_status_to_$new_status'}. It has
  1516. * the comment data.
  1517. *
  1518. * The final action will run whether or not the comment statuses are the same.
  1519. * The action is named {@see 'comment_$new_status_$comment->comment_type'}.
  1520. *
  1521. * @since 2.7.0
  1522. *
  1523. * @param string $new_status New comment status.
  1524. * @param string $old_status Previous comment status.
  1525. * @param WP_Comment $comment Comment object.
  1526. */
  1527. function wp_transition_comment_status( $new_status, $old_status, $comment ) {
  1528. /*
  1529. * Translate raw statuses to human-readable formats for the hooks.
  1530. * This is not a complete list of comment status, it's only the ones
  1531. * that need to be renamed.
  1532. */
  1533. $comment_statuses = array(
  1534. 0 => 'unapproved',
  1535. 'hold' => 'unapproved', // wp_set_comment_status() uses "hold".
  1536. 1 => 'approved',
  1537. 'approve' => 'approved', // wp_set_comment_status() uses "approve".
  1538. );
  1539. if ( isset( $comment_statuses[ $new_status ] ) ) {
  1540. $new_status = $comment_statuses[ $new_status ];
  1541. }
  1542. if ( isset( $comment_statuses[ $old_status ] ) ) {
  1543. $old_status = $comment_statuses[ $old_status ];
  1544. }
  1545. // Call the hooks.
  1546. if ( $new_status != $old_status ) {
  1547. /**
  1548. * Fires when the comment status is in transition.
  1549. *
  1550. * @since 2.7.0
  1551. *
  1552. * @param int|string $new_status The new comment status.
  1553. * @param int|string $old_status The old comment status.
  1554. * @param WP_Comment $comment Comment object.
  1555. */
  1556. do_action( 'transition_comment_status', $new_status, $old_status, $comment );
  1557. /**
  1558. * Fires when the comment status is in transition from one specific status to another.
  1559. *
  1560. * The dynamic portions of the hook name, `$old_status`, and `$new_status`,
  1561. * refer to the old and new comment statuses, respectively.
  1562. *
  1563. * @since 2.7.0
  1564. *
  1565. * @param WP_Comment $comment Comment object.
  1566. */
  1567. do_action( "comment_{$old_status}_to_{$new_status}", $comment );
  1568. }
  1569. /**
  1570. * Fires when the status of a specific comment type is in transition.
  1571. *
  1572. * The dynamic portions of the hook name, `$new_status`, and `$comment->comment_type`,
  1573. * refer to the new comment status, and the type of comment, respectively.
  1574. *
  1575. * Typical comment types include an empty string (standard comment), 'pingback',
  1576. * or 'trackback'.
  1577. *
  1578. * @since 2.7.0
  1579. *
  1580. * @param int $comment_ID The comment ID.
  1581. * @param WP_Comment $comment Comment object.
  1582. */
  1583. do_action( "comment_{$new_status}_{$comment->comment_type}", $comment->comment_ID, $comment );
  1584. }
  1585. /**
  1586. * Clear the lastcommentmodified cached value when a comment status is changed.
  1587. *
  1588. * Deletes the lastcommentmodified cache key when a comment enters or leaves
  1589. * 'approved' status.
  1590. *
  1591. * @since 4.7.0
  1592. * @access private
  1593. *
  1594. * @param string $new_status The new comment status.
  1595. * @param string $old_status The old comment status.
  1596. */
  1597. function _clear_modified_cache_on_transition_comment_status( $new_status, $old_status ) {
  1598. if ( 'approved' === $new_status || 'approved' === $old_status ) {
  1599. foreach ( array( 'server', 'gmt', 'blog' ) as $timezone ) {
  1600. wp_cache_delete( "lastcommentmodified:$timezone", 'timeinfo' );
  1601. }
  1602. }
  1603. }
  1604. /**
  1605. * Get current commenter's name, email, and URL.
  1606. *
  1607. * Expects cookies content to already be sanitized. User of this function might
  1608. * wish to recheck the returned array for validity.
  1609. *
  1610. * @see sanitize_comment_cookies() Use to sanitize cookies
  1611. *
  1612. * @since 2.0.4
  1613. *
  1614. * @return array {
  1615. * An array of current commenter variables.
  1616. *
  1617. * @type string $comment_author The name of the current commenter, or an empty string.
  1618. * @type string $comment_author_email The email address of the current commenter, or an empty string.
  1619. * @type string $comment_author_url The URL address of the current commenter, or an empty string.
  1620. * }
  1621. */
  1622. function wp_get_current_commenter() {
  1623. // Cookies should already be sanitized.
  1624. $comment_author = '';
  1625. if ( isset( $_COOKIE[ 'comment_author_' . COOKIEHASH ] ) ) {
  1626. $comment_author = $_COOKIE[ 'comment_author_' . COOKIEHASH ];
  1627. }
  1628. $comment_author_email = '';
  1629. if ( isset( $_COOKIE[ 'comment_author_email_' . COOKIEHASH ] ) ) {
  1630. $comment_author_email = $_COOKIE[ 'comment_author_email_' . COOKIEHASH ];
  1631. }
  1632. $comment_author_url = '';
  1633. if ( isset( $_COOKIE[ 'comment_author_url_' . COOKIEHASH ] ) ) {
  1634. $comment_author_url = $_COOKIE[ 'comment_author_url_' . COOKIEHASH ];
  1635. }
  1636. /**
  1637. * Filters the current commenter's name, email, and URL.
  1638. *
  1639. * @since 3.1.0
  1640. *
  1641. * @param array $comment_author_data {
  1642. * An array of current commenter variables.
  1643. *
  1644. * @type string $comment_author The name of the current commenter, or an empty string.
  1645. * @type string $comment_author_email The email address of the current commenter, or an empty string.
  1646. * @type string $comment_author_url The URL address of the current commenter, or an empty string.
  1647. * }
  1648. */
  1649. return apply_filters( 'wp_get_current_commenter', compact( 'comment_author', 'comment_author_email', 'comment_author_url' ) );
  1650. }
  1651. /**
  1652. * Get unapproved comment author's email.
  1653. *
  1654. * Used to allow the commenter to see their pending comment.
  1655. *
  1656. * @since 5.1.0
  1657. *
  1658. * @return string The unapproved comment author's email (when supplied).
  1659. */
  1660. function wp_get_unapproved_comment_author_email() {
  1661. $commenter_email = '';
  1662. if ( ! empty( $_GET['unapproved'] ) && ! empty( $_GET['moderation-hash'] ) ) {
  1663. $comment_id = (int) $_GET['unapproved'];
  1664. $comment = get_comment( $comment_id );
  1665. if ( $comment && hash_equals( $_GET['moderation-hash'], wp_hash( $comment->comment_date_gmt ) ) ) {
  1666. $commenter_email = $comment->comment_author_email;
  1667. }
  1668. }
  1669. if ( ! $commenter_email ) {
  1670. $commenter = wp_get_current_commenter();
  1671. $commenter_email = $commenter['comment_author_email'];
  1672. }
  1673. return $commenter_email;
  1674. }
  1675. /**
  1676. * Inserts a comment into the database.
  1677. *
  1678. * @since 2.0.0
  1679. * @since 4.4.0 Introduced the `$comment_meta` argument.
  1680. * @since 5.5.0 Default value for `$comment_type` argument changed to `comment`.
  1681. *
  1682. * @global wpdb $wpdb WordPress database abstraction object.
  1683. *
  1684. * @param array $commentdata {
  1685. * Array of arguments for inserting a new comment.
  1686. *
  1687. * @type string $comment_agent The HTTP user agent of the `$comment_author` when
  1688. * the comment was submitted. Default empty.
  1689. * @type int|string $comment_approved Whether the comment has been approved. Default 1.
  1690. * @type string $comment_author The name of the author of the comment. Default empty.
  1691. * @type string $comment_author_email The email address of the `$comment_author`. Default empty.
  1692. * @type string $comment_author_IP The IP address of the `$comment_author`. Default empty.
  1693. * @type string $comment_author_url The URL address of the `$comment_author`. Default empty.
  1694. * @type string $comment_content The content of the comment. Default empty.
  1695. * @type string $comment_date The date the comment was submitted. To set the date
  1696. * manually, `$comment_date_gmt` must also be specified.
  1697. * Default is the current time.
  1698. * @type string $comment_date_gmt The date the comment was submitted in the GMT timezone.
  1699. * Default is `$comment_date` in the site's GMT timezone.
  1700. * @type int $comment_karma The karma of the comment. Default 0.
  1701. * @type int $comment_parent ID of this comment's parent, if any. Default 0.
  1702. * @type int $comment_post_ID ID of the post that relates to the comment, if any.
  1703. * Default 0.
  1704. * @type string $comment_type Comment type. Default 'comment'.
  1705. * @type array $comment_meta Optional. Array of key/value pairs to be stored in commentmeta for the
  1706. * new comment.
  1707. * @type int $user_id ID of the user who submitted the comment. Default 0.
  1708. * }
  1709. * @return int|false The new comment's ID on success, false on failure.
  1710. */
  1711. function wp_insert_comment( $commentdata ) {
  1712. global $wpdb;
  1713. $data = wp_unslash( $commentdata );
  1714. $comment_author = ! isset( $data['comment_author'] ) ? '' : $data['comment_author'];
  1715. $comment_author_email = ! isset( $data['comment_author_email'] ) ? '' : $data['comment_author_email'];
  1716. $comment_author_url = ! isset( $data['comment_author_url'] ) ? '' : $data['comment_author_url'];
  1717. $comment_author_IP = ! isset( $data['comment_author_IP'] ) ? '' : $data['comment_author_IP'];
  1718. $comment_date = ! isset( $data['comment_date'] ) ? current_time( 'mysql' ) : $data['comment_date'];
  1719. $comment_date_gmt = ! isset( $data['comment_date_gmt'] ) ? get_gmt_from_date( $comment_date ) : $data['comment_date_gmt'];
  1720. $comment_post_ID = ! isset( $data['comment_post_ID'] ) ? 0 : $data['comment_post_ID'];
  1721. $comment_content = ! isset( $data['comment_content'] ) ? '' : $data['comment_content'];
  1722. $comment_karma = ! isset( $data['comment_karma'] ) ? 0 : $data['comment_karma'];
  1723. $comment_approved = ! isset( $data['comment_approved'] ) ? 1 : $data['comment_approved'];
  1724. $comment_agent = ! isset( $data['comment_agent'] ) ? '' : $data['comment_agent'];
  1725. $comment_type = empty( $data['comment_type'] ) ? 'comment' : $data['comment_type'];
  1726. $comment_parent = ! isset( $data['comment_parent'] ) ? 0 : $data['comment_parent'];
  1727. $user_id = ! isset( $data['user_id'] ) ? 0 : $data['user_id'];
  1728. $compacted = compact( 'comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_date', 'comment_date_gmt', 'comment_content', 'comment_karma', 'comment_approved', 'comment_agent', 'comment_type', 'comment_parent', 'user_id' );
  1729. if ( ! $wpdb->insert( $wpdb->comments, $compacted ) ) {
  1730. return false;
  1731. }
  1732. $id = (int) $wpdb->insert_id;
  1733. if ( 1 == $comment_approved ) {
  1734. wp_update_comment_count( $comment_post_ID );
  1735. foreach ( array( 'server', 'gmt', 'blog' ) as $timezone ) {
  1736. wp_cache_delete( "lastcommentmodified:$timezone", 'timeinfo' );
  1737. }
  1738. }
  1739. clean_comment_cache( $id );
  1740. $comment = get_comment( $id );
  1741. // If metadata is provided, store it.
  1742. if ( isset( $commentdata['comment_meta'] ) && is_array( $commentdata['comment_meta'] ) ) {
  1743. foreach ( $commentdata['comment_meta'] as $meta_key => $meta_value ) {
  1744. add_comment_meta( $comment->comment_ID, $meta_key, $meta_value, true );
  1745. }
  1746. }
  1747. /**
  1748. * Fires immediately after a comment is inserted into the database.
  1749. *
  1750. * @since 2.8.0
  1751. *
  1752. * @param int $id The comment ID.
  1753. * @param WP_Comment $comment Comment object.
  1754. */
  1755. do_action( 'wp_insert_comment', $id, $comment );
  1756. return $id;
  1757. }
  1758. /**
  1759. * Filters and sanitizes comment data.
  1760. *
  1761. * Sets the comment data 'filtered' field to true when finished. This can be
  1762. * checked as to whether the comment should be filtered and to keep from
  1763. * filtering the same comment more than once.
  1764. *
  1765. * @since 2.0.0
  1766. *
  1767. * @param array $commentdata Contains information on the comment.
  1768. * @return array Parsed comment information.
  1769. */
  1770. function wp_filter_comment( $commentdata ) {
  1771. if ( isset( $commentdata['user_ID'] ) ) {
  1772. /**
  1773. * Filters the comment author's user id before it is set.
  1774. *
  1775. * The first time this filter is evaluated, 'user_ID' is checked
  1776. * (for back-compat), followed by the standard 'user_id' value.
  1777. *
  1778. * @since 1.5.0
  1779. *
  1780. * @param int $user_ID The comment author's user ID.
  1781. */
  1782. $commentdata['user_id'] = apply_filters( 'pre_user_id', $commentdata['user_ID'] );
  1783. } elseif ( isset( $commentdata['user_id'] ) ) {
  1784. /** This filter is documented in wp-includes/comment.php */
  1785. $commentdata['user_id'] = apply_filters( 'pre_user_id', $commentdata['user_id'] );
  1786. }
  1787. /**
  1788. * Filters the comment author's browser user agent before it is set.
  1789. *
  1790. * @since 1.5.0
  1791. *
  1792. * @param string $comment_agent The comment author's browser user agent.
  1793. */
  1794. $commentdata['comment_agent'] = apply_filters( 'pre_comment_user_agent', ( isset( $commentdata['comment_agent'] ) ? $commentdata['comment_agent'] : '' ) );
  1795. /** This filter is documented in wp-includes/comment.php */
  1796. $commentdata['comment_author'] = apply_filters( 'pre_comment_author_name', $commentdata['comment_author'] );
  1797. /**
  1798. * Filters the comment content before it is set.
  1799. *
  1800. * @since 1.5.0
  1801. *
  1802. * @param string $comment_content The comment content.
  1803. */
  1804. $commentdata['comment_content'] = apply_filters( 'pre_comment_content', $commentdata['comment_content'] );
  1805. /**
  1806. * Filters the comment author's IP address before it is set.
  1807. *
  1808. * @since 1.5.0
  1809. *
  1810. * @param string $comment_author_ip The comment author's IP address.
  1811. */
  1812. $commentdata['comment_author_IP'] = apply_filters( 'pre_comment_user_ip', $commentdata['comment_author_IP'] );
  1813. /** This filter is documented in wp-includes/comment.php */
  1814. $commentdata['comment_author_url'] = apply_filters( 'pre_comment_author_url', $commentdata['comment_author_url'] );
  1815. /** This filter is documented in wp-includes/comment.php */
  1816. $commentdata['comment_author_email'] = apply_filters( 'pre_comment_author_email', $commentdata['comment_author_email'] );
  1817. $commentdata['filtered'] = true;
  1818. return $commentdata;
  1819. }
  1820. /**
  1821. * Whether a comment should be blocked because of comment flood.
  1822. *
  1823. * @since 2.1.0
  1824. *
  1825. * @param bool $block Whether plugin has already blocked comment.
  1826. * @param int $time_lastcomment Timestamp for last comment.
  1827. * @param int $time_newcomment Timestamp for new comment.
  1828. * @return bool Whether comment should be blocked.
  1829. */
  1830. function wp_throttle_comment_flood( $block, $time_lastcomment, $time_newcomment ) {
  1831. if ( $block ) { // A plugin has already blocked... we'll let that decision stand.
  1832. return $block;
  1833. }
  1834. if ( ( $time_newcomment - $time_lastcomment ) < 15 ) {
  1835. return true;
  1836. }
  1837. return false;
  1838. }
  1839. /**
  1840. * Adds a new comment to the database.
  1841. *
  1842. * Filters new comment to ensure that the fields are sanitized and valid before
  1843. * inserting comment into database. Calls {@see 'comment_post'} action with comment ID
  1844. * and whether comment is approved by WordPress. Also has {@see 'preprocess_comment'}
  1845. * filter for processing the comment data before the function handles it.
  1846. *
  1847. * We use `REMOTE_ADDR` here directly. If you are behind a proxy, you should ensure
  1848. * that it is properly set, such as in wp-config.php, for your environment.
  1849. *
  1850. * See {@link https://core.trac.wordpress.org/ticket/9235}
  1851. *
  1852. * @since 1.5.0
  1853. * @since 4.3.0 Introduced the `comment_agent` and `comment_author_IP` arguments.
  1854. * @since 4.7.0 The `$avoid_die` parameter was added, allowing the function to
  1855. * return a WP_Error object instead of dying.
  1856. * @since 5.5.0 Introduced the `comment_type` argument.
  1857. *
  1858. * @see wp_insert_comment()
  1859. * @global wpdb $wpdb WordPress database abstraction object.
  1860. *
  1861. * @param array $commentdata {
  1862. * Comment data.
  1863. *
  1864. * @type string $comment_author The name of the comment author.
  1865. * @type string $comment_author_email The comment author email address.
  1866. * @type string $comment_author_url The comment author URL.
  1867. * @type string $comment_content The content of the comment.
  1868. * @type string $comment_date The date the comment was submitted. Default is the current time.
  1869. * @type string $comment_date_gmt The date the comment was submitted in the GMT timezone.
  1870. * Default is `$comment_date` in the GMT timezone.
  1871. * @type string $comment_type Comment type. Default 'comment'.
  1872. * @type int $comment_parent The ID of this comment's parent, if any. Default 0.
  1873. * @type int $comment_post_ID The ID of the post that relates to the comment.
  1874. * @type int $user_id The ID of the user who submitted the comment. Default 0.
  1875. * @type int $user_ID Kept for backward-compatibility. Use `$user_id` instead.
  1876. * @type string $comment_agent Comment author user agent. Default is the value of 'HTTP_USER_AGENT'
  1877. * in the `$_SERVER` superglobal sent in the original request.
  1878. * @type string $comment_author_IP Comment author IP address in IPv4 format. Default is the value of
  1879. * 'REMOTE_ADDR' in the `$_SERVER` superglobal sent in the original request.
  1880. * }
  1881. * @param bool $avoid_die Should errors be returned as WP_Error objects instead of
  1882. * executing wp_die()? Default false.
  1883. * @return int|false|WP_Error The ID of the comment on success, false or WP_Error on failure.
  1884. */
  1885. function wp_new_comment( $commentdata, $avoid_die = false ) {
  1886. global $wpdb;
  1887. if ( isset( $commentdata['user_ID'] ) ) {
  1888. $commentdata['user_ID'] = (int) $commentdata['user_ID'];
  1889. $commentdata['user_id'] = $commentdata['user_ID'];
  1890. }
  1891. $prefiltered_user_id = ( isset( $commentdata['user_id'] ) ) ? (int) $commentdata['user_id'] : 0;
  1892. /**
  1893. * Filters a comment's data before it is sanitized and inserted into the database.
  1894. *
  1895. * @since 1.5.0
  1896. *
  1897. * @param array $commentdata Comment data.
  1898. */
  1899. $commentdata = apply_filters( 'preprocess_comment', $commentdata );
  1900. $commentdata['comment_post_ID'] = (int) $commentdata['comment_post_ID'];
  1901. if ( isset( $commentdata['user_ID'] ) && $prefiltered_user_id !== (int) $commentdata['user_ID'] ) {
  1902. $commentdata['user_ID'] = (int) $commentdata['user_ID'];
  1903. $commentdata['user_id'] = $commentdata['user_ID'];
  1904. } elseif ( isset( $commentdata['user_id'] ) ) {
  1905. $commentdata['user_id'] = (int) $commentdata['user_id'];
  1906. }
  1907. $commentdata['comment_parent'] = isset( $commentdata['comment_parent'] ) ? absint( $commentdata['comment_parent'] ) : 0;
  1908. $parent_status = ( 0 < $commentdata['comment_parent'] ) ? wp_get_comment_status( $commentdata['comment_parent'] ) : '';
  1909. $commentdata['comment_parent'] = ( 'approved' == $parent_status || 'unapproved' == $parent_status ) ? $commentdata['comment_parent'] : 0;
  1910. if ( ! isset( $commentdata['comment_author_IP'] ) ) {
  1911. $commentdata['comment_author_IP'] = $_SERVER['REMOTE_ADDR'];
  1912. }
  1913. $commentdata['comment_author_IP'] = preg_replace( '/[^0-9a-fA-F:., ]/', '', $commentdata['comment_author_IP'] );
  1914. if ( ! isset( $commentdata['comment_agent'] ) ) {
  1915. $commentdata['comment_agent'] = isset( $_SERVER['HTTP_USER_AGENT'] ) ? $_SERVER['HTTP_USER_AGENT'] : '';
  1916. }
  1917. $commentdata['comment_agent'] = substr( $commentdata['comment_agent'], 0, 254 );
  1918. if ( empty( $commentdata['comment_date'] ) ) {
  1919. $commentdata['comment_date'] = current_time( 'mysql' );
  1920. }
  1921. if ( empty( $commentdata['comment_date_gmt'] ) ) {
  1922. $commentdata['comment_date_gmt'] = current_time( 'mysql', 1 );
  1923. }
  1924. if ( empty( $commentdata['comment_type'] ) ) {
  1925. $commentdata['comment_type'] = 'comment';
  1926. }
  1927. $commentdata = wp_filter_comment( $commentdata );
  1928. $commentdata['comment_approved'] = wp_allow_comment( $commentdata, $avoid_die );
  1929. if ( is_wp_error( $commentdata['comment_approved'] ) ) {
  1930. return $commentdata['comment_approved'];
  1931. }
  1932. $comment_ID = wp_insert_comment( $commentdata );
  1933. if ( ! $comment_ID ) {
  1934. $fields = array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content' );
  1935. foreach ( $fields as $field ) {
  1936. if ( isset( $commentdata[ $field ] ) ) {
  1937. $commentdata[ $field ] = $wpdb->strip_invalid_text_for_column( $wpdb->comments, $field, $commentdata[ $field ] );
  1938. }
  1939. }
  1940. $commentdata = wp_filter_comment( $commentdata );
  1941. $commentdata['comment_approved'] = wp_allow_comment( $commentdata, $avoid_die );
  1942. if ( is_wp_error( $commentdata['comment_approved'] ) ) {
  1943. return $commentdata['comment_approved'];
  1944. }
  1945. $comment_ID = wp_insert_comment( $commentdata );
  1946. if ( ! $comment_ID ) {
  1947. return false;
  1948. }
  1949. }
  1950. /**
  1951. * Fires immediately after a comment is inserted into the database.
  1952. *
  1953. * @since 1.2.0
  1954. * @since 4.5.0 The `$commentdata` parameter was added.
  1955. *
  1956. * @param int $comment_ID The comment ID.
  1957. * @param int|string $comment_approved 1 if the comment is approved, 0 if not, 'spam' if spam.
  1958. * @param array $commentdata Comment data.
  1959. */
  1960. do_action( 'comment_post', $comment_ID, $commentdata['comment_approved'], $commentdata );
  1961. return $comment_ID;
  1962. }
  1963. /**
  1964. * Send a comment moderation notification to the comment moderator.
  1965. *
  1966. * @since 4.4.0
  1967. *
  1968. * @param int $comment_ID ID of the comment.
  1969. * @return bool True on success, false on failure.
  1970. */
  1971. function wp_new_comment_notify_moderator( $comment_ID ) {
  1972. $comment = get_comment( $comment_ID );
  1973. // Only send notifications for pending comments.
  1974. $maybe_notify = ( '0' == $comment->comment_approved );
  1975. /** This filter is documented in wp-includes/comment.php */
  1976. $maybe_notify = apply_filters( 'notify_moderator', $maybe_notify, $comment_ID );
  1977. if ( ! $maybe_notify ) {
  1978. return false;
  1979. }
  1980. return wp_notify_moderator( $comment_ID );
  1981. }
  1982. /**
  1983. * Send a notification of a new comment to the post author.
  1984. *
  1985. * @since 4.4.0
  1986. *
  1987. * Uses the {@see 'notify_post_author'} filter to determine whether the post author
  1988. * should be notified when a new comment is added, overriding site setting.
  1989. *
  1990. * @param int $comment_ID Comment ID.
  1991. * @return bool True on success, false on failure.
  1992. */
  1993. function wp_new_comment_notify_postauthor( $comment_ID ) {
  1994. $comment = get_comment( $comment_ID );
  1995. $maybe_notify = get_option( 'comments_notify' );
  1996. /**
  1997. * Filters whether to send the post author new comment notification emails,
  1998. * overriding the site setting.
  1999. *
  2000. * @since 4.4.0
  2001. *
  2002. * @param bool $maybe_notify Whether to notify the post author about the new comment.
  2003. * @param int $comment_ID The ID of the comment for the notification.
  2004. */
  2005. $maybe_notify = apply_filters( 'notify_post_author', $maybe_notify, $comment_ID );
  2006. /*
  2007. * wp_notify_postauthor() checks if notifying the author of their own comment.
  2008. * By default, it won't, but filters can override this.
  2009. */
  2010. if ( ! $maybe_notify ) {
  2011. return false;
  2012. }
  2013. // Only send notifications for approved comments.
  2014. if ( ! isset( $comment->comment_approved ) || '1' != $comment->comment_approved ) {
  2015. return false;
  2016. }
  2017. return wp_notify_postauthor( $comment_ID );
  2018. }
  2019. /**
  2020. * Sets the status of a comment.
  2021. *
  2022. * The {@see 'wp_set_comment_status'} action is called after the comment is handled.
  2023. * If the comment status is not in the list, then false is returned.
  2024. *
  2025. * @since 1.0.0
  2026. *
  2027. * @global wpdb $wpdb WordPress database abstraction object.
  2028. *
  2029. * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
  2030. * @param string $comment_status New comment status, either 'hold', 'approve', 'spam', or 'trash'.
  2031. * @param bool $wp_error Whether to return a WP_Error object if there is a failure. Default is false.
  2032. * @return bool|WP_Error True on success, false or WP_Error on failure.
  2033. */
  2034. function wp_set_comment_status( $comment_id, $comment_status, $wp_error = false ) {
  2035. global $wpdb;
  2036. switch ( $comment_status ) {
  2037. case 'hold':
  2038. case '0':
  2039. $status = '0';
  2040. break;
  2041. case 'approve':
  2042. case '1':
  2043. $status = '1';
  2044. add_action( 'wp_set_comment_status', 'wp_new_comment_notify_postauthor' );
  2045. break;
  2046. case 'spam':
  2047. $status = 'spam';
  2048. break;
  2049. case 'trash':
  2050. $status = 'trash';
  2051. break;
  2052. default:
  2053. return false;
  2054. }
  2055. $comment_old = clone get_comment( $comment_id );
  2056. if ( ! $wpdb->update( $wpdb->comments, array( 'comment_approved' => $status ), array( 'comment_ID' => $comment_old->comment_ID ) ) ) {
  2057. if ( $wp_error ) {
  2058. return new WP_Error( 'db_update_error', __( 'Could not update comment status' ), $wpdb->last_error );
  2059. } else {
  2060. return false;
  2061. }
  2062. }
  2063. clean_comment_cache( $comment_old->comment_ID );
  2064. $comment = get_comment( $comment_old->comment_ID );
  2065. /**
  2066. * Fires immediately before transitioning a comment's status from one to another
  2067. * in the database.
  2068. *
  2069. * @since 1.5.0
  2070. *
  2071. * @param int $comment_id Comment ID.
  2072. * @param string|bool $comment_status Current comment status. Possible values include
  2073. * 'hold', 'approve', 'spam', 'trash', or false.
  2074. */
  2075. do_action( 'wp_set_comment_status', $comment->comment_ID, $comment_status );
  2076. wp_transition_comment_status( $comment_status, $comment_old->comment_approved, $comment );
  2077. wp_update_comment_count( $comment->comment_post_ID );
  2078. return true;
  2079. }
  2080. /**
  2081. * Updates an existing comment in the database.
  2082. *
  2083. * Filters the comment and makes sure certain fields are valid before updating.
  2084. *
  2085. * @since 2.0.0
  2086. * @since 4.9.0 Add updating comment meta during comment update.
  2087. *
  2088. * @global wpdb $wpdb WordPress database abstraction object.
  2089. *
  2090. * @param array $commentarr Contains information on the comment.
  2091. * @return int The value 1 if the comment was updated, 0 if not updated.
  2092. */
  2093. function wp_update_comment( $commentarr ) {
  2094. global $wpdb;
  2095. // First, get all of the original fields.
  2096. $comment = get_comment( $commentarr['comment_ID'], ARRAY_A );
  2097. if ( empty( $comment ) ) {
  2098. return 0;
  2099. }
  2100. // Make sure that the comment post ID is valid (if specified).
  2101. if ( ! empty( $commentarr['comment_post_ID'] ) && ! get_post( $commentarr['comment_post_ID'] ) ) {
  2102. return 0;
  2103. }
  2104. // Escape data pulled from DB.
  2105. $comment = wp_slash( $comment );
  2106. $old_status = $comment['comment_approved'];
  2107. // Merge old and new fields with new fields overwriting old ones.
  2108. $commentarr = array_merge( $comment, $commentarr );
  2109. $commentarr = wp_filter_comment( $commentarr );
  2110. // Now extract the merged array.
  2111. $data = wp_unslash( $commentarr );
  2112. /**
  2113. * Filters the comment content before it is updated in the database.
  2114. *
  2115. * @since 1.5.0
  2116. *
  2117. * @param string $comment_content The comment data.
  2118. */
  2119. $data['comment_content'] = apply_filters( 'comment_save_pre', $data['comment_content'] );
  2120. $data['comment_date_gmt'] = get_gmt_from_date( $data['comment_date'] );
  2121. if ( ! isset( $data['comment_approved'] ) ) {
  2122. $data['comment_approved'] = 1;
  2123. } elseif ( 'hold' == $data['comment_approved'] ) {
  2124. $data['comment_approved'] = 0;
  2125. } elseif ( 'approve' == $data['comment_approved'] ) {
  2126. $data['comment_approved'] = 1;
  2127. }
  2128. $comment_ID = $data['comment_ID'];
  2129. $comment_post_ID = $data['comment_post_ID'];
  2130. /**
  2131. * Filters the comment data immediately before it is updated in the database.
  2132. *
  2133. * Note: data being passed to the filter is already unslashed.
  2134. *
  2135. * @since 4.7.0
  2136. *
  2137. * @param array $data The new, processed comment data.
  2138. * @param array $comment The old, unslashed comment data.
  2139. * @param array $commentarr The new, raw comment data.
  2140. */
  2141. $data = apply_filters( 'wp_update_comment_data', $data, $comment, $commentarr );
  2142. $keys = array( 'comment_post_ID', 'comment_content', 'comment_author', 'comment_author_email', 'comment_approved', 'comment_karma', 'comment_author_url', 'comment_date', 'comment_date_gmt', 'comment_type', 'comment_parent', 'user_id', 'comment_agent', 'comment_author_IP' );
  2143. $data = wp_array_slice_assoc( $data, $keys );
  2144. $rval = $wpdb->update( $wpdb->comments, $data, compact( 'comment_ID' ) );
  2145. // If metadata is provided, store it.
  2146. if ( isset( $commentarr['comment_meta'] ) && is_array( $commentarr['comment_meta'] ) ) {
  2147. foreach ( $commentarr['comment_meta'] as $meta_key => $meta_value ) {
  2148. update_comment_meta( $comment_ID, $meta_key, $meta_value );
  2149. }
  2150. }
  2151. clean_comment_cache( $comment_ID );
  2152. wp_update_comment_count( $comment_post_ID );
  2153. /**
  2154. * Fires immediately after a comment is updated in the database.
  2155. *
  2156. * The hook also fires immediately before comment status transition hooks are fired.
  2157. *
  2158. * @since 1.2.0
  2159. * @since 4.6.0 Added the `$data` parameter.
  2160. *
  2161. * @param int $comment_ID The comment ID.
  2162. * @param array $data Comment data.
  2163. */
  2164. do_action( 'edit_comment', $comment_ID, $data );
  2165. $comment = get_comment( $comment_ID );
  2166. wp_transition_comment_status( $comment->comment_approved, $old_status, $comment );
  2167. return $rval;
  2168. }
  2169. /**
  2170. * Whether to defer comment counting.
  2171. *
  2172. * When setting $defer to true, all post comment counts will not be updated
  2173. * until $defer is set to false. When $defer is set to false, then all
  2174. * previously deferred updated post comment counts will then be automatically
  2175. * updated without having to call wp_update_comment_count() after.
  2176. *
  2177. * @since 2.5.0
  2178. * @staticvar bool $_defer
  2179. *
  2180. * @param bool $defer
  2181. * @return bool
  2182. */
  2183. function wp_defer_comment_counting( $defer = null ) {
  2184. static $_defer = false;
  2185. if ( is_bool( $defer ) ) {
  2186. $_defer = $defer;
  2187. // Flush any deferred counts.
  2188. if ( ! $defer ) {
  2189. wp_update_comment_count( null, true );
  2190. }
  2191. }
  2192. return $_defer;
  2193. }
  2194. /**
  2195. * Updates the comment count for post(s).
  2196. *
  2197. * When $do_deferred is false (is by default) and the comments have been set to
  2198. * be deferred, the post_id will be added to a queue, which will be updated at a
  2199. * later date and only updated once per post ID.
  2200. *
  2201. * If the comments have not be set up to be deferred, then the post will be
  2202. * updated. When $do_deferred is set to true, then all previous deferred post
  2203. * IDs will be updated along with the current $post_id.
  2204. *
  2205. * @since 2.1.0
  2206. * @see wp_update_comment_count_now() For what could cause a false return value
  2207. *
  2208. * @staticvar array $_deferred
  2209. *
  2210. * @param int|null $post_id Post ID.
  2211. * @param bool $do_deferred Optional. Whether to process previously deferred
  2212. * post comment counts. Default false.
  2213. * @return bool|void True on success, false on failure or if post with ID does
  2214. * not exist.
  2215. */
  2216. function wp_update_comment_count( $post_id, $do_deferred = false ) {
  2217. static $_deferred = array();
  2218. if ( empty( $post_id ) && ! $do_deferred ) {
  2219. return false;
  2220. }
  2221. if ( $do_deferred ) {
  2222. $_deferred = array_unique( $_deferred );
  2223. foreach ( $_deferred as $i => $_post_id ) {
  2224. wp_update_comment_count_now( $_post_id );
  2225. unset( $_deferred[ $i ] );
  2226. /** @todo Move this outside of the foreach and reset $_deferred to an array instead */
  2227. }
  2228. }
  2229. if ( wp_defer_comment_counting() ) {
  2230. $_deferred[] = $post_id;
  2231. return true;
  2232. } elseif ( $post_id ) {
  2233. return wp_update_comment_count_now( $post_id );
  2234. }
  2235. }
  2236. /**
  2237. * Updates the comment count for the post.
  2238. *
  2239. * @since 2.5.0
  2240. *
  2241. * @global wpdb $wpdb WordPress database abstraction object.
  2242. *
  2243. * @param int $post_id Post ID
  2244. * @return bool True on success, false if the post does not exist.
  2245. */
  2246. function wp_update_comment_count_now( $post_id ) {
  2247. global $wpdb;
  2248. $post_id = (int) $post_id;
  2249. if ( ! $post_id ) {
  2250. return false;
  2251. }
  2252. wp_cache_delete( 'comments-0', 'counts' );
  2253. wp_cache_delete( "comments-{$post_id}", 'counts' );
  2254. $post = get_post( $post_id );
  2255. if ( ! $post ) {
  2256. return false;
  2257. }
  2258. $old = (int) $post->comment_count;
  2259. /**
  2260. * Filters a post's comment count before it is updated in the database.
  2261. *
  2262. * @since 4.5.0
  2263. *
  2264. * @param int|null $new The new comment count. Default null.
  2265. * @param int $old The old comment count.
  2266. * @param int $post_id Post ID.
  2267. */
  2268. $new = apply_filters( 'pre_wp_update_comment_count_now', null, $old, $post_id );
  2269. if ( is_null( $new ) ) {
  2270. $new = (int) $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(*) FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved = '1'", $post_id ) );
  2271. } else {
  2272. $new = (int) $new;
  2273. }
  2274. $wpdb->update( $wpdb->posts, array( 'comment_count' => $new ), array( 'ID' => $post_id ) );
  2275. clean_post_cache( $post );
  2276. /**
  2277. * Fires immediately after a post's comment count is updated in the database.
  2278. *
  2279. * @since 2.3.0
  2280. *
  2281. * @param int $post_id Post ID.
  2282. * @param int $new The new comment count.
  2283. * @param int $old The old comment count.
  2284. */
  2285. do_action( 'wp_update_comment_count', $post_id, $new, $old );
  2286. /** This action is documented in wp-includes/post.php */
  2287. do_action( "edit_post_{$post->post_type}", $post_id, $post );
  2288. /** This action is documented in wp-includes/post.php */
  2289. do_action( 'edit_post', $post_id, $post );
  2290. return true;
  2291. }
  2292. //
  2293. // Ping and trackback functions.
  2294. //
  2295. /**
  2296. * Finds a pingback server URI based on the given URL.
  2297. *
  2298. * Checks the HTML for the rel="pingback" link and x-pingback headers. It does
  2299. * a check for the x-pingback headers first and returns that, if available. The
  2300. * check for the rel="pingback" has more overhead than just the header.
  2301. *
  2302. * @since 1.5.0
  2303. *
  2304. * @param string $url URL to ping.
  2305. * @param int $deprecated Not Used.
  2306. * @return string|false String containing URI on success, false on failure.
  2307. */
  2308. function discover_pingback_server_uri( $url, $deprecated = '' ) {
  2309. if ( ! empty( $deprecated ) ) {
  2310. _deprecated_argument( __FUNCTION__, '2.7.0' );
  2311. }
  2312. $pingback_str_dquote = 'rel="pingback"';
  2313. $pingback_str_squote = 'rel=\'pingback\'';
  2314. /** @todo Should use Filter Extension or custom preg_match instead. */
  2315. $parsed_url = parse_url( $url );
  2316. if ( ! isset( $parsed_url['host'] ) ) { // Not a URL. This should never happen.
  2317. return false;
  2318. }
  2319. // Do not search for a pingback server on our own uploads.
  2320. $uploads_dir = wp_get_upload_dir();
  2321. if ( 0 === strpos( $url, $uploads_dir['baseurl'] ) ) {
  2322. return false;
  2323. }
  2324. $response = wp_safe_remote_head(
  2325. $url,
  2326. array(
  2327. 'timeout' => 2,
  2328. 'httpversion' => '1.0',
  2329. )
  2330. );
  2331. if ( is_wp_error( $response ) ) {
  2332. return false;
  2333. }
  2334. if ( wp_remote_retrieve_header( $response, 'x-pingback' ) ) {
  2335. return wp_remote_retrieve_header( $response, 'x-pingback' );
  2336. }
  2337. // Not an (x)html, sgml, or xml page, no use going further.
  2338. if ( preg_match( '#(image|audio|video|model)/#is', wp_remote_retrieve_header( $response, 'content-type' ) ) ) {
  2339. return false;
  2340. }
  2341. // Now do a GET since we're going to look in the html headers (and we're sure it's not a binary file).
  2342. $response = wp_safe_remote_get(
  2343. $url,
  2344. array(
  2345. 'timeout' => 2,
  2346. 'httpversion' => '1.0',
  2347. )
  2348. );
  2349. if ( is_wp_error( $response ) ) {
  2350. return false;
  2351. }
  2352. $contents = wp_remote_retrieve_body( $response );
  2353. $pingback_link_offset_dquote = strpos( $contents, $pingback_str_dquote );
  2354. $pingback_link_offset_squote = strpos( $contents, $pingback_str_squote );
  2355. if ( $pingback_link_offset_dquote || $pingback_link_offset_squote ) {
  2356. $quote = ( $pingback_link_offset_dquote ) ? '"' : '\'';
  2357. $pingback_link_offset = ( '"' === $quote ) ? $pingback_link_offset_dquote : $pingback_link_offset_squote;
  2358. $pingback_href_pos = strpos( $contents, 'href=', $pingback_link_offset );
  2359. $pingback_href_start = $pingback_href_pos + 6;
  2360. $pingback_href_end = strpos( $contents, $quote, $pingback_href_start );
  2361. $pingback_server_url_len = $pingback_href_end - $pingback_href_start;
  2362. $pingback_server_url = substr( $contents, $pingback_href_start, $pingback_server_url_len );
  2363. // We may find rel="pingback" but an incomplete pingback URL.
  2364. if ( $pingback_server_url_len > 0 ) { // We got it!
  2365. return $pingback_server_url;
  2366. }
  2367. }
  2368. return false;
  2369. }
  2370. /**
  2371. * Perform all pingbacks, enclosures, trackbacks, and send to pingback services.
  2372. *
  2373. * @since 2.1.0
  2374. *
  2375. * @global wpdb $wpdb WordPress database abstraction object.
  2376. */
  2377. function do_all_pings() {
  2378. global $wpdb;
  2379. // Do pingbacks.
  2380. $pings = get_posts(
  2381. array(
  2382. 'post_type' => get_post_types(),
  2383. 'suppress_filters' => false,
  2384. 'nopaging' => true,
  2385. 'meta_key' => '_pingme',
  2386. 'fields' => 'ids',
  2387. )
  2388. );
  2389. foreach ( $pings as $ping ) {
  2390. delete_post_meta( $ping, '_pingme' );
  2391. pingback( null, $ping );
  2392. }
  2393. // Do enclosures.
  2394. $enclosures = get_posts(
  2395. array(
  2396. 'post_type' => get_post_types(),
  2397. 'suppress_filters' => false,
  2398. 'nopaging' => true,
  2399. 'meta_key' => '_encloseme',
  2400. 'fields' => 'ids',
  2401. )
  2402. );
  2403. foreach ( $enclosures as $enclosure ) {
  2404. delete_post_meta( $enclosure, '_encloseme' );
  2405. do_enclose( null, $enclosure );
  2406. }
  2407. // Do trackbacks.
  2408. $trackbacks = get_posts(
  2409. array(
  2410. 'post_type' => get_post_types(),
  2411. 'suppress_filters' => false,
  2412. 'nopaging' => true,
  2413. 'meta_key' => '_trackbackme',
  2414. 'fields' => 'ids',
  2415. )
  2416. );
  2417. foreach ( $trackbacks as $trackback ) {
  2418. delete_post_meta( $trackback, '_trackbackme' );
  2419. do_trackbacks( $trackback );
  2420. }
  2421. // Do Update Services/Generic Pings.
  2422. generic_ping();
  2423. }
  2424. /**
  2425. * Perform trackbacks.
  2426. *
  2427. * @since 1.5.0
  2428. * @since 4.7.0 `$post_id` can be a WP_Post object.
  2429. *
  2430. * @global wpdb $wpdb WordPress database abstraction object.
  2431. *
  2432. * @param int|WP_Post $post_id Post object or ID to do trackbacks on.
  2433. */
  2434. function do_trackbacks( $post_id ) {
  2435. global $wpdb;
  2436. $post = get_post( $post_id );
  2437. if ( ! $post ) {
  2438. return false;
  2439. }
  2440. $to_ping = get_to_ping( $post );
  2441. $pinged = get_pung( $post );
  2442. if ( empty( $to_ping ) ) {
  2443. $wpdb->update( $wpdb->posts, array( 'to_ping' => '' ), array( 'ID' => $post->ID ) );
  2444. return;
  2445. }
  2446. if ( empty( $post->post_excerpt ) ) {
  2447. /** This filter is documented in wp-includes/post-template.php */
  2448. $excerpt = apply_filters( 'the_content', $post->post_content, $post->ID );
  2449. } else {
  2450. /** This filter is documented in wp-includes/post-template.php */
  2451. $excerpt = apply_filters( 'the_excerpt', $post->post_excerpt );
  2452. }
  2453. $excerpt = str_replace( ']]>', ']]&gt;', $excerpt );
  2454. $excerpt = wp_html_excerpt( $excerpt, 252, '&#8230;' );
  2455. /** This filter is documented in wp-includes/post-template.php */
  2456. $post_title = apply_filters( 'the_title', $post->post_title, $post->ID );
  2457. $post_title = strip_tags( $post_title );
  2458. if ( $to_ping ) {
  2459. foreach ( (array) $to_ping as $tb_ping ) {
  2460. $tb_ping = trim( $tb_ping );
  2461. if ( ! in_array( $tb_ping, $pinged, true ) ) {
  2462. trackback( $tb_ping, $post_title, $excerpt, $post->ID );
  2463. $pinged[] = $tb_ping;
  2464. } else {
  2465. $wpdb->query(
  2466. $wpdb->prepare(
  2467. "UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s,
  2468. '')) WHERE ID = %d",
  2469. $tb_ping,
  2470. $post->ID
  2471. )
  2472. );
  2473. }
  2474. }
  2475. }
  2476. }
  2477. /**
  2478. * Sends pings to all of the ping site services.
  2479. *
  2480. * @since 1.2.0
  2481. *
  2482. * @param int $post_id Post ID.
  2483. * @return int Same as Post ID from parameter
  2484. */
  2485. function generic_ping( $post_id = 0 ) {
  2486. $services = get_option( 'ping_sites' );
  2487. $services = explode( "\n", $services );
  2488. foreach ( (array) $services as $service ) {
  2489. $service = trim( $service );
  2490. if ( '' != $service ) {
  2491. weblog_ping( $service );
  2492. }
  2493. }
  2494. return $post_id;
  2495. }
  2496. /**
  2497. * Pings back the links found in a post.
  2498. *
  2499. * @since 0.71
  2500. * @since 4.7.0 `$post_id` can be a WP_Post object.
  2501. *
  2502. * @param string $content Post content to check for links. If empty will retrieve from post.
  2503. * @param int|WP_Post $post_id Post Object or ID.
  2504. */
  2505. function pingback( $content, $post_id ) {
  2506. include_once ABSPATH . WPINC . '/class-IXR.php';
  2507. include_once ABSPATH . WPINC . '/class-wp-http-ixr-client.php';
  2508. // Original code by Mort (http://mort.mine.nu:8080).
  2509. $post_links = array();
  2510. $post = get_post( $post_id );
  2511. if ( ! $post ) {
  2512. return;
  2513. }
  2514. $pung = get_pung( $post );
  2515. if ( empty( $content ) ) {
  2516. $content = $post->post_content;
  2517. }
  2518. /*
  2519. * Step 1.
  2520. * Parsing the post, external links (if any) are stored in the $post_links array.
  2521. */
  2522. $post_links_temp = wp_extract_urls( $content );
  2523. /*
  2524. * Step 2.
  2525. * Walking through the links array.
  2526. * First we get rid of links pointing to sites, not to specific files.
  2527. * Example:
  2528. * http://dummy-weblog.org
  2529. * http://dummy-weblog.org/
  2530. * http://dummy-weblog.org/post.php
  2531. * We don't wanna ping first and second types, even if they have a valid <link/>.
  2532. */
  2533. foreach ( (array) $post_links_temp as $link_test ) {
  2534. // If we haven't pung it already and it isn't a link to itself.
  2535. if ( ! in_array( $link_test, $pung, true ) && ( url_to_postid( $link_test ) != $post->ID )
  2536. // Also, let's never ping local attachments.
  2537. && ! is_local_attachment( $link_test )
  2538. ) {
  2539. $test = parse_url( $link_test );
  2540. if ( $test ) {
  2541. if ( isset( $test['query'] ) ) {
  2542. $post_links[] = $link_test;
  2543. } elseif ( isset( $test['path'] ) && ( '/' !== $test['path'] ) && ( '' !== $test['path'] ) ) {
  2544. $post_links[] = $link_test;
  2545. }
  2546. }
  2547. }
  2548. }
  2549. $post_links = array_unique( $post_links );
  2550. /**
  2551. * Fires just before pinging back links found in a post.
  2552. *
  2553. * @since 2.0.0
  2554. *
  2555. * @param string[] $post_links Array of link URLs to be checked (passed by reference).
  2556. * @param string[] $pung Array of link URLs already pinged (passed by reference).
  2557. * @param int $post_ID The post ID.
  2558. */
  2559. do_action_ref_array( 'pre_ping', array( &$post_links, &$pung, $post->ID ) );
  2560. foreach ( (array) $post_links as $pagelinkedto ) {
  2561. $pingback_server_url = discover_pingback_server_uri( $pagelinkedto );
  2562. if ( $pingback_server_url ) {
  2563. set_time_limit( 60 );
  2564. // Now, the RPC call.
  2565. $pagelinkedfrom = get_permalink( $post );
  2566. // Using a timeout of 3 seconds should be enough to cover slow servers.
  2567. $client = new WP_HTTP_IXR_Client( $pingback_server_url );
  2568. $client->timeout = 3;
  2569. /**
  2570. * Filters the user agent sent when pinging-back a URL.
  2571. *
  2572. * @since 2.9.0
  2573. *
  2574. * @param string $concat_useragent The user agent concatenated with ' -- WordPress/'
  2575. * and the WordPress version.
  2576. * @param string $useragent The useragent.
  2577. * @param string $pingback_server_url The server URL being linked to.
  2578. * @param string $pagelinkedto URL of page linked to.
  2579. * @param string $pagelinkedfrom URL of page linked from.
  2580. */
  2581. $client->useragent = apply_filters( 'pingback_useragent', $client->useragent . ' -- WordPress/' . get_bloginfo( 'version' ), $client->useragent, $pingback_server_url, $pagelinkedto, $pagelinkedfrom );
  2582. // When set to true, this outputs debug messages by itself.
  2583. $client->debug = false;
  2584. if ( $client->query( 'pingback.ping', $pagelinkedfrom, $pagelinkedto ) || ( isset( $client->error->code ) && 48 == $client->error->code ) ) { // Already registered.
  2585. add_ping( $post, $pagelinkedto );
  2586. }
  2587. }
  2588. }
  2589. }
  2590. /**
  2591. * Check whether blog is public before returning sites.
  2592. *
  2593. * @since 2.1.0
  2594. *
  2595. * @param mixed $sites Will return if blog is public, will not return if not public.
  2596. * @return mixed Empty string if blog is not public, returns $sites, if site is public.
  2597. */
  2598. function privacy_ping_filter( $sites ) {
  2599. if ( '0' != get_option( 'blog_public' ) ) {
  2600. return $sites;
  2601. } else {
  2602. return '';
  2603. }
  2604. }
  2605. /**
  2606. * Send a Trackback.
  2607. *
  2608. * Updates database when sending trackback to prevent duplicates.
  2609. *
  2610. * @since 0.71
  2611. *
  2612. * @global wpdb $wpdb WordPress database abstraction object.
  2613. *
  2614. * @param string $trackback_url URL to send trackbacks.
  2615. * @param string $title Title of post.
  2616. * @param string $excerpt Excerpt of post.
  2617. * @param int $ID Post ID.
  2618. * @return int|false|void Database query from update.
  2619. */
  2620. function trackback( $trackback_url, $title, $excerpt, $ID ) {
  2621. global $wpdb;
  2622. if ( empty( $trackback_url ) ) {
  2623. return;
  2624. }
  2625. $options = array();
  2626. $options['timeout'] = 10;
  2627. $options['body'] = array(
  2628. 'title' => $title,
  2629. 'url' => get_permalink( $ID ),
  2630. 'blog_name' => get_option( 'blogname' ),
  2631. 'excerpt' => $excerpt,
  2632. );
  2633. $response = wp_safe_remote_post( $trackback_url, $options );
  2634. if ( is_wp_error( $response ) ) {
  2635. return;
  2636. }
  2637. $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET pinged = CONCAT(pinged, '\n', %s) WHERE ID = %d", $trackback_url, $ID ) );
  2638. return $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s, '')) WHERE ID = %d", $trackback_url, $ID ) );
  2639. }
  2640. /**
  2641. * Send a pingback.
  2642. *
  2643. * @since 1.2.0
  2644. *
  2645. * @param string $server Host of blog to connect to.
  2646. * @param string $path Path to send the ping.
  2647. */
  2648. function weblog_ping( $server = '', $path = '' ) {
  2649. include_once ABSPATH . WPINC . '/class-IXR.php';
  2650. include_once ABSPATH . WPINC . '/class-wp-http-ixr-client.php';
  2651. // Using a timeout of 3 seconds should be enough to cover slow servers.
  2652. $client = new WP_HTTP_IXR_Client( $server, ( ( ! strlen( trim( $path ) ) || ( '/' == $path ) ) ? false : $path ) );
  2653. $client->timeout = 3;
  2654. $client->useragent .= ' -- WordPress/' . get_bloginfo( 'version' );
  2655. // When set to true, this outputs debug messages by itself.
  2656. $client->debug = false;
  2657. $home = trailingslashit( home_url() );
  2658. if ( ! $client->query( 'weblogUpdates.extendedPing', get_option( 'blogname' ), $home, get_bloginfo( 'rss2_url' ) ) ) { // Then try a normal ping.
  2659. $client->query( 'weblogUpdates.ping', get_option( 'blogname' ), $home );
  2660. }
  2661. }
  2662. /**
  2663. * Default filter attached to pingback_ping_source_uri to validate the pingback's Source URI
  2664. *
  2665. * @since 3.5.1
  2666. * @see wp_http_validate_url()
  2667. *
  2668. * @param string $source_uri
  2669. * @return string
  2670. */
  2671. function pingback_ping_source_uri( $source_uri ) {
  2672. return (string) wp_http_validate_url( $source_uri );
  2673. }
  2674. /**
  2675. * Default filter attached to xmlrpc_pingback_error.
  2676. *
  2677. * Returns a generic pingback error code unless the error code is 48,
  2678. * which reports that the pingback is already registered.
  2679. *
  2680. * @since 3.5.1
  2681. * @link https://www.hixie.ch/specs/pingback/pingback#TOC3
  2682. *
  2683. * @param IXR_Error $ixr_error
  2684. * @return IXR_Error
  2685. */
  2686. function xmlrpc_pingback_error( $ixr_error ) {
  2687. if ( 48 === $ixr_error->code ) {
  2688. return $ixr_error;
  2689. }
  2690. return new IXR_Error( 0, '' );
  2691. }
  2692. //
  2693. // Cache.
  2694. //
  2695. /**
  2696. * Removes a comment from the object cache.
  2697. *
  2698. * @since 2.3.0
  2699. *
  2700. * @param int|array $ids Comment ID or an array of comment IDs to remove from cache.
  2701. */
  2702. function clean_comment_cache( $ids ) {
  2703. foreach ( (array) $ids as $id ) {
  2704. wp_cache_delete( $id, 'comment' );
  2705. /**
  2706. * Fires immediately after a comment has been removed from the object cache.
  2707. *
  2708. * @since 4.5.0
  2709. *
  2710. * @param int $id Comment ID.
  2711. */
  2712. do_action( 'clean_comment_cache', $id );
  2713. }
  2714. wp_cache_set( 'last_changed', microtime(), 'comment' );
  2715. }
  2716. /**
  2717. * Updates the comment cache of given comments.
  2718. *
  2719. * Will add the comments in $comments to the cache. If comment ID already exists
  2720. * in the comment cache then it will not be updated. The comment is added to the
  2721. * cache using the comment group with the key using the ID of the comments.
  2722. *
  2723. * @since 2.3.0
  2724. * @since 4.4.0 Introduced the `$update_meta_cache` parameter.
  2725. *
  2726. * @param WP_Comment[] $comments Array of comment objects
  2727. * @param bool $update_meta_cache Whether to update commentmeta cache. Default true.
  2728. */
  2729. function update_comment_cache( $comments, $update_meta_cache = true ) {
  2730. foreach ( (array) $comments as $comment ) {
  2731. wp_cache_add( $comment->comment_ID, $comment, 'comment' );
  2732. }
  2733. if ( $update_meta_cache ) {
  2734. // Avoid `wp_list_pluck()` in case `$comments` is passed by reference.
  2735. $comment_ids = array();
  2736. foreach ( $comments as $comment ) {
  2737. $comment_ids[] = $comment->comment_ID;
  2738. }
  2739. update_meta_cache( 'comment', $comment_ids );
  2740. }
  2741. }
  2742. /**
  2743. * Adds any comments from the given IDs to the cache that do not already exist in cache.
  2744. *
  2745. * @since 4.4.0
  2746. * @access private
  2747. *
  2748. * @see update_comment_cache()
  2749. * @global wpdb $wpdb WordPress database abstraction object.
  2750. *
  2751. * @param int[] $comment_ids Array of comment IDs.
  2752. * @param bool $update_meta_cache Optional. Whether to update the meta cache. Default true.
  2753. */
  2754. function _prime_comment_caches( $comment_ids, $update_meta_cache = true ) {
  2755. global $wpdb;
  2756. $non_cached_ids = _get_non_cached_ids( $comment_ids, 'comment' );
  2757. if ( ! empty( $non_cached_ids ) ) {
  2758. $fresh_comments = $wpdb->get_results( sprintf( "SELECT $wpdb->comments.* FROM $wpdb->comments WHERE comment_ID IN (%s)", join( ',', array_map( 'intval', $non_cached_ids ) ) ) );
  2759. update_comment_cache( $fresh_comments, $update_meta_cache );
  2760. }
  2761. }
  2762. //
  2763. // Internal.
  2764. //
  2765. /**
  2766. * Close comments on old posts on the fly, without any extra DB queries. Hooked to the_posts.
  2767. *
  2768. * @access private
  2769. * @since 2.7.0
  2770. *
  2771. * @param WP_Post $posts Post data object.
  2772. * @param WP_Query $query Query object.
  2773. * @return array
  2774. */
  2775. function _close_comments_for_old_posts( $posts, $query ) {
  2776. if ( empty( $posts ) || ! $query->is_singular() || ! get_option( 'close_comments_for_old_posts' ) ) {
  2777. return $posts;
  2778. }
  2779. /**
  2780. * Filters the list of post types to automatically close comments for.
  2781. *
  2782. * @since 3.2.0
  2783. *
  2784. * @param string[] $post_types An array of post type names.
  2785. */
  2786. $post_types = apply_filters( 'close_comments_for_post_types', array( 'post' ) );
  2787. if ( ! in_array( $posts[0]->post_type, $post_types, true ) ) {
  2788. return $posts;
  2789. }
  2790. $days_old = (int) get_option( 'close_comments_days_old' );
  2791. if ( ! $days_old ) {
  2792. return $posts;
  2793. }
  2794. if ( time() - strtotime( $posts[0]->post_date_gmt ) > ( $days_old * DAY_IN_SECONDS ) ) {
  2795. $posts[0]->comment_status = 'closed';
  2796. $posts[0]->ping_status = 'closed';
  2797. }
  2798. return $posts;
  2799. }
  2800. /**
  2801. * Close comments on an old post. Hooked to comments_open and pings_open.
  2802. *
  2803. * @access private
  2804. * @since 2.7.0
  2805. *
  2806. * @param bool $open Comments open or closed
  2807. * @param int $post_id Post ID
  2808. * @return bool $open
  2809. */
  2810. function _close_comments_for_old_post( $open, $post_id ) {
  2811. if ( ! $open ) {
  2812. return $open;
  2813. }
  2814. if ( ! get_option( 'close_comments_for_old_posts' ) ) {
  2815. return $open;
  2816. }
  2817. $days_old = (int) get_option( 'close_comments_days_old' );
  2818. if ( ! $days_old ) {
  2819. return $open;
  2820. }
  2821. $post = get_post( $post_id );
  2822. /** This filter is documented in wp-includes/comment.php */
  2823. $post_types = apply_filters( 'close_comments_for_post_types', array( 'post' ) );
  2824. if ( ! in_array( $post->post_type, $post_types, true ) ) {
  2825. return $open;
  2826. }
  2827. // Undated drafts should not show up as comments closed.
  2828. if ( '0000-00-00 00:00:00' === $post->post_date_gmt ) {
  2829. return $open;
  2830. }
  2831. if ( time() - strtotime( $post->post_date_gmt ) > ( $days_old * DAY_IN_SECONDS ) ) {
  2832. return false;
  2833. }
  2834. return $open;
  2835. }
  2836. /**
  2837. * Handles the submission of a comment, usually posted to wp-comments-post.php via a comment form.
  2838. *
  2839. * This function expects unslashed data, as opposed to functions such as `wp_new_comment()` which
  2840. * expect slashed data.
  2841. *
  2842. * @since 4.4.0
  2843. *
  2844. * @param array $comment_data {
  2845. * Comment data.
  2846. *
  2847. * @type string|int $comment_post_ID The ID of the post that relates to the comment.
  2848. * @type string $author The name of the comment author.
  2849. * @type string $email The comment author email address.
  2850. * @type string $url The comment author URL.
  2851. * @type string $comment The content of the comment.
  2852. * @type string|int $comment_parent The ID of this comment's parent, if any. Default 0.
  2853. * @type string $_wp_unfiltered_html_comment The nonce value for allowing unfiltered HTML.
  2854. * }
  2855. * @return WP_Comment|WP_Error A WP_Comment object on success, a WP_Error object on failure.
  2856. */
  2857. function wp_handle_comment_submission( $comment_data ) {
  2858. $comment_post_ID = 0;
  2859. $comment_parent = 0;
  2860. $user_ID = 0;
  2861. $comment_author = null;
  2862. $comment_author_email = null;
  2863. $comment_author_url = null;
  2864. $comment_content = null;
  2865. if ( isset( $comment_data['comment_post_ID'] ) ) {
  2866. $comment_post_ID = (int) $comment_data['comment_post_ID'];
  2867. }
  2868. if ( isset( $comment_data['author'] ) && is_string( $comment_data['author'] ) ) {
  2869. $comment_author = trim( strip_tags( $comment_data['author'] ) );
  2870. }
  2871. if ( isset( $comment_data['email'] ) && is_string( $comment_data['email'] ) ) {
  2872. $comment_author_email = trim( $comment_data['email'] );
  2873. }
  2874. if ( isset( $comment_data['url'] ) && is_string( $comment_data['url'] ) ) {
  2875. $comment_author_url = trim( $comment_data['url'] );
  2876. }
  2877. if ( isset( $comment_data['comment'] ) && is_string( $comment_data['comment'] ) ) {
  2878. $comment_content = trim( $comment_data['comment'] );
  2879. }
  2880. if ( isset( $comment_data['comment_parent'] ) ) {
  2881. $comment_parent = absint( $comment_data['comment_parent'] );
  2882. }
  2883. $post = get_post( $comment_post_ID );
  2884. if ( empty( $post->comment_status ) ) {
  2885. /**
  2886. * Fires when a comment is attempted on a post that does not exist.
  2887. *
  2888. * @since 1.5.0
  2889. *
  2890. * @param int $comment_post_ID Post ID.
  2891. */
  2892. do_action( 'comment_id_not_found', $comment_post_ID );
  2893. return new WP_Error( 'comment_id_not_found' );
  2894. }
  2895. // get_post_status() will get the parent status for attachments.
  2896. $status = get_post_status( $post );
  2897. if ( ( 'private' == $status ) && ! current_user_can( 'read_post', $comment_post_ID ) ) {
  2898. return new WP_Error( 'comment_id_not_found' );
  2899. }
  2900. $status_obj = get_post_status_object( $status );
  2901. if ( ! comments_open( $comment_post_ID ) ) {
  2902. /**
  2903. * Fires when a comment is attempted on a post that has comments closed.
  2904. *
  2905. * @since 1.5.0
  2906. *
  2907. * @param int $comment_post_ID Post ID.
  2908. */
  2909. do_action( 'comment_closed', $comment_post_ID );
  2910. return new WP_Error( 'comment_closed', __( 'Sorry, comments are closed for this item.' ), 403 );
  2911. } elseif ( 'trash' == $status ) {
  2912. /**
  2913. * Fires when a comment is attempted on a trashed post.
  2914. *
  2915. * @since 2.9.0
  2916. *
  2917. * @param int $comment_post_ID Post ID.
  2918. */
  2919. do_action( 'comment_on_trash', $comment_post_ID );
  2920. return new WP_Error( 'comment_on_trash' );
  2921. } elseif ( ! $status_obj->public && ! $status_obj->private ) {
  2922. /**
  2923. * Fires when a comment is attempted on a post in draft mode.
  2924. *
  2925. * @since 1.5.1
  2926. *
  2927. * @param int $comment_post_ID Post ID.
  2928. */
  2929. do_action( 'comment_on_draft', $comment_post_ID );
  2930. if ( current_user_can( 'read_post', $comment_post_ID ) ) {
  2931. return new WP_Error( 'comment_on_draft', __( 'Sorry, comments are not allowed for this item.' ), 403 );
  2932. } else {
  2933. return new WP_Error( 'comment_on_draft' );
  2934. }
  2935. } elseif ( post_password_required( $comment_post_ID ) ) {
  2936. /**
  2937. * Fires when a comment is attempted on a password-protected post.
  2938. *
  2939. * @since 2.9.0
  2940. *
  2941. * @param int $comment_post_ID Post ID.
  2942. */
  2943. do_action( 'comment_on_password_protected', $comment_post_ID );
  2944. return new WP_Error( 'comment_on_password_protected' );
  2945. } else {
  2946. /**
  2947. * Fires before a comment is posted.
  2948. *
  2949. * @since 2.8.0
  2950. *
  2951. * @param int $comment_post_ID Post ID.
  2952. */
  2953. do_action( 'pre_comment_on_post', $comment_post_ID );
  2954. }
  2955. // If the user is logged in.
  2956. $user = wp_get_current_user();
  2957. if ( $user->exists() ) {
  2958. if ( empty( $user->display_name ) ) {
  2959. $user->display_name = $user->user_login;
  2960. }
  2961. $comment_author = $user->display_name;
  2962. $comment_author_email = $user->user_email;
  2963. $comment_author_url = $user->user_url;
  2964. $user_ID = $user->ID;
  2965. if ( current_user_can( 'unfiltered_html' ) ) {
  2966. if ( ! isset( $comment_data['_wp_unfiltered_html_comment'] )
  2967. || ! wp_verify_nonce( $comment_data['_wp_unfiltered_html_comment'], 'unfiltered-html-comment_' . $comment_post_ID )
  2968. ) {
  2969. kses_remove_filters(); // Start with a clean slate.
  2970. kses_init_filters(); // Set up the filters.
  2971. remove_filter( 'pre_comment_content', 'wp_filter_post_kses' );
  2972. add_filter( 'pre_comment_content', 'wp_filter_kses' );
  2973. }
  2974. }
  2975. } else {
  2976. if ( get_option( 'comment_registration' ) ) {
  2977. return new WP_Error( 'not_logged_in', __( 'Sorry, you must be logged in to comment.' ), 403 );
  2978. }
  2979. }
  2980. $comment_type = 'comment';
  2981. if ( get_option( 'require_name_email' ) && ! $user->exists() ) {
  2982. if ( '' == $comment_author_email || '' == $comment_author ) {
  2983. return new WP_Error( 'require_name_email', __( '<strong>Error</strong>: Please fill the required fields (name, email).' ), 200 );
  2984. } elseif ( ! is_email( $comment_author_email ) ) {
  2985. return new WP_Error( 'require_valid_email', __( '<strong>Error</strong>: Please enter a valid email address.' ), 200 );
  2986. }
  2987. }
  2988. $commentdata = compact(
  2989. 'comment_post_ID',
  2990. 'comment_author',
  2991. 'comment_author_email',
  2992. 'comment_author_url',
  2993. 'comment_content',
  2994. 'comment_type',
  2995. 'comment_parent',
  2996. 'user_ID'
  2997. );
  2998. /**
  2999. * Filters whether an empty comment should be allowed.
  3000. *
  3001. * @since 5.1.0
  3002. *
  3003. * @param bool $allow_empty_comment Whether to allow empty comments. Default false.
  3004. * @param array $commentdata Array of comment data to be sent to wp_insert_comment().
  3005. */
  3006. $allow_empty_comment = apply_filters( 'allow_empty_comment', false, $commentdata );
  3007. if ( '' === $comment_content && ! $allow_empty_comment ) {
  3008. return new WP_Error( 'require_valid_comment', __( '<strong>Error</strong>: Please type a comment.' ), 200 );
  3009. }
  3010. $check_max_lengths = wp_check_comment_data_max_lengths( $commentdata );
  3011. if ( is_wp_error( $check_max_lengths ) ) {
  3012. return $check_max_lengths;
  3013. }
  3014. $comment_id = wp_new_comment( wp_slash( $commentdata ), true );
  3015. if ( is_wp_error( $comment_id ) ) {
  3016. return $comment_id;
  3017. }
  3018. if ( ! $comment_id ) {
  3019. return new WP_Error( 'comment_save_error', __( '<strong>Error</strong>: The comment could not be saved. Please try again later.' ), 500 );
  3020. }
  3021. return get_comment( $comment_id );
  3022. }
  3023. /**
  3024. * Registers the personal data exporter for comments.
  3025. *
  3026. * @since 4.9.6
  3027. *
  3028. * @param array $exporters An array of personal data exporters.
  3029. * @return array An array of personal data exporters.
  3030. */
  3031. function wp_register_comment_personal_data_exporter( $exporters ) {
  3032. $exporters['wordpress-comments'] = array(
  3033. 'exporter_friendly_name' => __( 'WordPress Comments' ),
  3034. 'callback' => 'wp_comments_personal_data_exporter',
  3035. );
  3036. return $exporters;
  3037. }
  3038. /**
  3039. * Finds and exports personal data associated with an email address from the comments table.
  3040. *
  3041. * @since 4.9.6
  3042. *
  3043. * @param string $email_address The comment author email address.
  3044. * @param int $page Comment page.
  3045. * @return array An array of personal data.
  3046. */
  3047. function wp_comments_personal_data_exporter( $email_address, $page = 1 ) {
  3048. // Limit us to 500 comments at a time to avoid timing out.
  3049. $number = 500;
  3050. $page = (int) $page;
  3051. $data_to_export = array();
  3052. $comments = get_comments(
  3053. array(
  3054. 'author_email' => $email_address,
  3055. 'number' => $number,
  3056. 'paged' => $page,
  3057. 'order_by' => 'comment_ID',
  3058. 'order' => 'ASC',
  3059. 'update_comment_meta_cache' => false,
  3060. )
  3061. );
  3062. $comment_prop_to_export = array(
  3063. 'comment_author' => __( 'Comment Author' ),
  3064. 'comment_author_email' => __( 'Comment Author Email' ),
  3065. 'comment_author_url' => __( 'Comment Author URL' ),
  3066. 'comment_author_IP' => __( 'Comment Author IP' ),
  3067. 'comment_agent' => __( 'Comment Author User Agent' ),
  3068. 'comment_date' => __( 'Comment Date' ),
  3069. 'comment_content' => __( 'Comment Content' ),
  3070. 'comment_link' => __( 'Comment URL' ),
  3071. );
  3072. foreach ( (array) $comments as $comment ) {
  3073. $comment_data_to_export = array();
  3074. foreach ( $comment_prop_to_export as $key => $name ) {
  3075. $value = '';
  3076. switch ( $key ) {
  3077. case 'comment_author':
  3078. case 'comment_author_email':
  3079. case 'comment_author_url':
  3080. case 'comment_author_IP':
  3081. case 'comment_agent':
  3082. case 'comment_date':
  3083. $value = $comment->{$key};
  3084. break;
  3085. case 'comment_content':
  3086. $value = get_comment_text( $comment->comment_ID );
  3087. break;
  3088. case 'comment_link':
  3089. $value = get_comment_link( $comment->comment_ID );
  3090. $value = sprintf(
  3091. '<a href="%s" target="_blank" rel="noreferrer noopener">%s</a>',
  3092. esc_url( $value ),
  3093. esc_html( $value )
  3094. );
  3095. break;
  3096. }
  3097. if ( ! empty( $value ) ) {
  3098. $comment_data_to_export[] = array(
  3099. 'name' => $name,
  3100. 'value' => $value,
  3101. );
  3102. }
  3103. }
  3104. $data_to_export[] = array(
  3105. 'group_id' => 'comments',
  3106. 'group_label' => __( 'Comments' ),
  3107. 'group_description' => __( 'User&#8217;s comment data.' ),
  3108. 'item_id' => "comment-{$comment->comment_ID}",
  3109. 'data' => $comment_data_to_export,
  3110. );
  3111. }
  3112. $done = count( $comments ) < $number;
  3113. return array(
  3114. 'data' => $data_to_export,
  3115. 'done' => $done,
  3116. );
  3117. }
  3118. /**
  3119. * Registers the personal data eraser for comments.
  3120. *
  3121. * @since 4.9.6
  3122. *
  3123. * @param array $erasers An array of personal data erasers.
  3124. * @return array An array of personal data erasers.
  3125. */
  3126. function wp_register_comment_personal_data_eraser( $erasers ) {
  3127. $erasers['wordpress-comments'] = array(
  3128. 'eraser_friendly_name' => __( 'WordPress Comments' ),
  3129. 'callback' => 'wp_comments_personal_data_eraser',
  3130. );
  3131. return $erasers;
  3132. }
  3133. /**
  3134. * Erases personal data associated with an email address from the comments table.
  3135. *
  3136. * @since 4.9.6
  3137. *
  3138. * @param string $email_address The comment author email address.
  3139. * @param int $page Comment page.
  3140. * @return array
  3141. */
  3142. function wp_comments_personal_data_eraser( $email_address, $page = 1 ) {
  3143. global $wpdb;
  3144. if ( empty( $email_address ) ) {
  3145. return array(
  3146. 'items_removed' => false,
  3147. 'items_retained' => false,
  3148. 'messages' => array(),
  3149. 'done' => true,
  3150. );
  3151. }
  3152. // Limit us to 500 comments at a time to avoid timing out.
  3153. $number = 500;
  3154. $page = (int) $page;
  3155. $items_removed = false;
  3156. $items_retained = false;
  3157. $comments = get_comments(
  3158. array(
  3159. 'author_email' => $email_address,
  3160. 'number' => $number,
  3161. 'paged' => $page,
  3162. 'order_by' => 'comment_ID',
  3163. 'order' => 'ASC',
  3164. 'include_unapproved' => true,
  3165. )
  3166. );
  3167. /* translators: Name of a comment's author after being anonymized. */
  3168. $anon_author = __( 'Anonymous' );
  3169. $messages = array();
  3170. foreach ( (array) $comments as $comment ) {
  3171. $anonymized_comment = array();
  3172. $anonymized_comment['comment_agent'] = '';
  3173. $anonymized_comment['comment_author'] = $anon_author;
  3174. $anonymized_comment['comment_author_email'] = '';
  3175. $anonymized_comment['comment_author_IP'] = wp_privacy_anonymize_data( 'ip', $comment->comment_author_IP );
  3176. $anonymized_comment['comment_author_url'] = '';
  3177. $anonymized_comment['user_id'] = 0;
  3178. $comment_id = (int) $comment->comment_ID;
  3179. /**
  3180. * Filters whether to anonymize the comment.
  3181. *
  3182. * @since 4.9.6
  3183. *
  3184. * @param bool|string $anon_message Whether to apply the comment anonymization (bool) or a custom
  3185. * message (string). Default true.
  3186. * @param WP_Comment $comment WP_Comment object.
  3187. * @param array $anonymized_comment Anonymized comment data.
  3188. */
  3189. $anon_message = apply_filters( 'wp_anonymize_comment', true, $comment, $anonymized_comment );
  3190. if ( true !== $anon_message ) {
  3191. if ( $anon_message && is_string( $anon_message ) ) {
  3192. $messages[] = esc_html( $anon_message );
  3193. } else {
  3194. /* translators: %d: Comment ID. */
  3195. $messages[] = sprintf( __( 'Comment %d contains personal data but could not be anonymized.' ), $comment_id );
  3196. }
  3197. $items_retained = true;
  3198. continue;
  3199. }
  3200. $args = array(
  3201. 'comment_ID' => $comment_id,
  3202. );
  3203. $updated = $wpdb->update( $wpdb->comments, $anonymized_comment, $args );
  3204. if ( $updated ) {
  3205. $items_removed = true;
  3206. clean_comment_cache( $comment_id );
  3207. } else {
  3208. $items_retained = true;
  3209. }
  3210. }
  3211. $done = count( $comments ) < $number;
  3212. return array(
  3213. 'items_removed' => $items_removed,
  3214. 'items_retained' => $items_retained,
  3215. 'messages' => $messages,
  3216. 'done' => $done,
  3217. );
  3218. }
  3219. /**
  3220. * Sets the last changed time for the 'comment' cache group.
  3221. *
  3222. * @since 5.0.0
  3223. */
  3224. function wp_cache_set_comments_last_changed() {
  3225. wp_cache_set( 'last_changed', microtime(), 'comment' );
  3226. }
  3227. /**
  3228. * Updates the comment type for a batch of comments.
  3229. *
  3230. * @since 5.5.0
  3231. *
  3232. * @global wpdb $wpdb WordPress database abstraction object.
  3233. */
  3234. function _wp_batch_update_comment_type() {
  3235. global $wpdb;
  3236. $lock_name = 'update_comment_type.lock';
  3237. // Try to lock.
  3238. $lock_result = $wpdb->query( $wpdb->prepare( "INSERT IGNORE INTO `$wpdb->options` ( `option_name`, `option_value`, `autoload` ) VALUES (%s, %s, 'no') /* LOCK */", $lock_name, time() ) );
  3239. if ( ! $lock_result ) {
  3240. $lock_result = get_option( $lock_name );
  3241. // Bail if we were unable to create a lock, or if the existing lock is still valid.
  3242. if ( ! $lock_result || ( $lock_result > ( time() - HOUR_IN_SECONDS ) ) ) {
  3243. wp_schedule_single_event( time() + ( 5 * MINUTE_IN_SECONDS ), 'wp_update_comment_type_batch' );
  3244. return;
  3245. }
  3246. }
  3247. // Update the lock, as by this point we've definitely got a lock, just need to fire the actions.
  3248. update_option( $lock_name, time() );
  3249. // Check if there's still an empty comment type.
  3250. $empty_comment_type = $wpdb->get_var(
  3251. "SELECT comment_ID FROM $wpdb->comments
  3252. WHERE comment_type = ''
  3253. LIMIT 1"
  3254. );
  3255. // No empty comment type, we're done here.
  3256. if ( ! $empty_comment_type ) {
  3257. update_option( 'finished_updating_comment_type', true );
  3258. delete_option( $lock_name );
  3259. return;
  3260. }
  3261. // Empty comment type found? We'll need to run this script again.
  3262. wp_schedule_single_event( time() + ( 2 * MINUTE_IN_SECONDS ), 'wp_update_comment_type_batch' );
  3263. // Update the `comment_type` field value to be `comment` for the next 100 rows of comments.
  3264. $wpdb->query(
  3265. "UPDATE {$wpdb->comments}
  3266. SET comment_type = 'comment'
  3267. WHERE comment_type = ''
  3268. ORDER BY comment_ID DESC
  3269. LIMIT 100"
  3270. );
  3271. delete_option( $lock_name );
  3272. }
  3273. /**
  3274. * In order to avoid the _wp_batch_update_comment_type() job being accidentally removed,
  3275. * check that it's still scheduled while we haven't finished updating comment types.
  3276. *
  3277. * @ignore
  3278. * @since 5.5.0
  3279. */
  3280. function _wp_check_for_scheduled_update_comment_type() {
  3281. if ( ! get_option( 'finished_updating_comment_type' ) && ! wp_next_scheduled( 'wp_update_comment_type_batch' ) ) {
  3282. wp_schedule_single_event( time() + MINUTE_IN_SECONDS, 'wp_update_comment_type_batch' );
  3283. }
  3284. }