PageRenderTime 29ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/htdocs/wp-includes/comment.php

https://gitlab.com/VTTE/sitios-vtte
PHP | 1531 lines | 684 code | 158 blank | 689 comment | 160 complexity | bef03caaa3c135284be8af61c89d8bab MD5 | raw file
  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|string $approved The number of approved comments.
  336. * @type int|string $awaiting_moderation The number of comments awaiting moderation (a.k.a. pending).
  337. * @type int|string $spam The number of spam comments.
  338. * @type int|string $trash The number of trashed comments.
  339. * @type int|string $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 $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.
  409. * @param bool $unique Optional, default is false. Whether the same key should not be added.
  410. * @return int|bool Meta ID on success, false on failure.
  411. */
  412. function add_comment_meta( $comment_id, $meta_key, $meta_value, $unique = false ) {
  413. return add_metadata( 'comment', $comment_id, $meta_key, $meta_value, $unique );
  414. }
  415. /**
  416. * Remove metadata matching criteria from a comment.
  417. *
  418. * You can match based on the key, or key and value. Removing based on key and
  419. * value, will keep from removing duplicate metadata with the same key. It also
  420. * allows removing all metadata matching key, if needed.
  421. *
  422. * @since 2.9.0
  423. * @link https://developer.wordpress.org/reference/functions/delete_comment_meta/
  424. *
  425. * @param int $comment_id comment ID
  426. * @param string $meta_key Metadata name.
  427. * @param mixed $meta_value Optional. Metadata value.
  428. * @return bool True on success, false on failure.
  429. */
  430. function delete_comment_meta( $comment_id, $meta_key, $meta_value = '' ) {
  431. return delete_metadata( 'comment', $comment_id, $meta_key, $meta_value );
  432. }
  433. /**
  434. * Retrieve comment meta field for a comment.
  435. *
  436. * @since 2.9.0
  437. * @link https://developer.wordpress.org/reference/functions/get_comment_meta/
  438. *
  439. * @param int $comment_id Comment ID.
  440. * @param string $key Optional. The meta key to retrieve. By default, returns data for all keys.
  441. * @param bool $single Whether to return a single value.
  442. * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
  443. * is true.
  444. */
  445. function get_comment_meta( $comment_id, $key = '', $single = false ) {
  446. return get_metadata( 'comment', $comment_id, $key, $single );
  447. }
  448. /**
  449. * Update comment meta field based on comment ID.
  450. *
  451. * Use the $prev_value parameter to differentiate between meta fields with the
  452. * same key and comment ID.
  453. *
  454. * If the meta field for the comment does not exist, it will be added.
  455. *
  456. * @since 2.9.0
  457. * @link https://developer.wordpress.org/reference/functions/update_comment_meta/
  458. *
  459. * @param int $comment_id Comment ID.
  460. * @param string $meta_key Metadata key.
  461. * @param mixed $meta_value Metadata value.
  462. * @param mixed $prev_value Optional. Previous value to check before removing.
  463. * @return int|bool Meta ID if the key didn't exist, true on successful update, false on failure.
  464. */
  465. function update_comment_meta( $comment_id, $meta_key, $meta_value, $prev_value = '' ) {
  466. return update_metadata( 'comment', $comment_id, $meta_key, $meta_value, $prev_value );
  467. }
  468. /**
  469. * Queues comments for metadata lazy-loading.
  470. *
  471. * @since 4.5.0
  472. *
  473. * @param WP_Comment[] $comments Array of comment objects.
  474. */
  475. function wp_queue_comments_for_comment_meta_lazyload( $comments ) {
  476. // Don't use `wp_list_pluck()` to avoid by-reference manipulation.
  477. $comment_ids = array();
  478. if ( is_array( $comments ) ) {
  479. foreach ( $comments as $comment ) {
  480. if ( $comment instanceof WP_Comment ) {
  481. $comment_ids[] = $comment->comment_ID;
  482. }
  483. }
  484. }
  485. if ( $comment_ids ) {
  486. $lazyloader = wp_metadata_lazyloader();
  487. $lazyloader->queue_objects( 'comment', $comment_ids );
  488. }
  489. }
  490. /**
  491. * Sets the cookies used to store an unauthenticated commentator's identity. Typically used
  492. * to recall previous comments by this commentator that are still held in moderation.
  493. *
  494. * @since 3.4.0
  495. * @since 4.9.6 The `$cookies_consent` parameter was added.
  496. *
  497. * @param WP_Comment $comment Comment object.
  498. * @param WP_User $user Comment author's user object. The user may not exist.
  499. * @param boolean $cookies_consent Optional. Comment author's consent to store cookies. Default true.
  500. */
  501. function wp_set_comment_cookies( $comment, $user, $cookies_consent = true ) {
  502. // If the user already exists, or the user opted out of cookies, don't set cookies.
  503. if ( $user->exists() ) {
  504. return;
  505. }
  506. if ( false === $cookies_consent ) {
  507. // Remove any existing cookies.
  508. $past = time() - YEAR_IN_SECONDS;
  509. setcookie( 'comment_author_' . COOKIEHASH, ' ', $past, COOKIEPATH, COOKIE_DOMAIN );
  510. setcookie( 'comment_author_email_' . COOKIEHASH, ' ', $past, COOKIEPATH, COOKIE_DOMAIN );
  511. setcookie( 'comment_author_url_' . COOKIEHASH, ' ', $past, COOKIEPATH, COOKIE_DOMAIN );
  512. return;
  513. }
  514. /**
  515. * Filters the lifetime of the comment cookie in seconds.
  516. *
  517. * @since 2.8.0
  518. *
  519. * @param int $seconds Comment cookie lifetime. Default 30000000.
  520. */
  521. $comment_cookie_lifetime = time() + apply_filters( 'comment_cookie_lifetime', 30000000 );
  522. $secure = ( 'https' === parse_url( home_url(), PHP_URL_SCHEME ) );
  523. setcookie( 'comment_author_' . COOKIEHASH, $comment->comment_author, $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure );
  524. setcookie( 'comment_author_email_' . COOKIEHASH, $comment->comment_author_email, $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure );
  525. setcookie( 'comment_author_url_' . COOKIEHASH, esc_url( $comment->comment_author_url ), $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure );
  526. }
  527. /**
  528. * Sanitizes the cookies sent to the user already.
  529. *
  530. * Will only do anything if the cookies have already been created for the user.
  531. * Mostly used after cookies had been sent to use elsewhere.
  532. *
  533. * @since 2.0.4
  534. */
  535. function sanitize_comment_cookies() {
  536. if ( isset( $_COOKIE[ 'comment_author_' . COOKIEHASH ] ) ) {
  537. /**
  538. * Filters the comment author's name cookie before it is set.
  539. *
  540. * When this filter hook is evaluated in wp_filter_comment(),
  541. * the comment author's name string is passed.
  542. *
  543. * @since 1.5.0
  544. *
  545. * @param string $author_cookie The comment author name cookie.
  546. */
  547. $comment_author = apply_filters( 'pre_comment_author_name', $_COOKIE[ 'comment_author_' . COOKIEHASH ] );
  548. $comment_author = wp_unslash( $comment_author );
  549. $comment_author = esc_attr( $comment_author );
  550. $_COOKIE[ 'comment_author_' . COOKIEHASH ] = $comment_author;
  551. }
  552. if ( isset( $_COOKIE[ 'comment_author_email_' . COOKIEHASH ] ) ) {
  553. /**
  554. * Filters the comment author's email cookie before it is set.
  555. *
  556. * When this filter hook is evaluated in wp_filter_comment(),
  557. * the comment author's email string is passed.
  558. *
  559. * @since 1.5.0
  560. *
  561. * @param string $author_email_cookie The comment author email cookie.
  562. */
  563. $comment_author_email = apply_filters( 'pre_comment_author_email', $_COOKIE[ 'comment_author_email_' . COOKIEHASH ] );
  564. $comment_author_email = wp_unslash( $comment_author_email );
  565. $comment_author_email = esc_attr( $comment_author_email );
  566. $_COOKIE[ 'comment_author_email_' . COOKIEHASH ] = $comment_author_email;
  567. }
  568. if ( isset( $_COOKIE[ 'comment_author_url_' . COOKIEHASH ] ) ) {
  569. /**
  570. * Filters the comment author's URL cookie before it is set.
  571. *
  572. * When this filter hook is evaluated in wp_filter_comment(),
  573. * the comment author's URL string is passed.
  574. *
  575. * @since 1.5.0
  576. *
  577. * @param string $author_url_cookie The comment author URL cookie.
  578. */
  579. $comment_author_url = apply_filters( 'pre_comment_author_url', $_COOKIE[ 'comment_author_url_' . COOKIEHASH ] );
  580. $comment_author_url = wp_unslash( $comment_author_url );
  581. $_COOKIE[ 'comment_author_url_' . COOKIEHASH ] = $comment_author_url;
  582. }
  583. }
  584. /**
  585. * Validates whether this comment is allowed to be made.
  586. *
  587. * @since 2.0.0
  588. * @since 4.7.0 The `$avoid_die` parameter was added, allowing the function to
  589. * return a WP_Error object instead of dying.
  590. *
  591. * @global wpdb $wpdb WordPress database abstraction object.
  592. *
  593. * @param array $commentdata Contains information on the comment.
  594. * @param bool $avoid_die When true, a disallowed comment will result in the function
  595. * returning a WP_Error object, rather than executing wp_die().
  596. * Default false.
  597. * @return int|string|WP_Error Allowed comments return the approval status (0|1|'spam'|'trash').
  598. * If `$avoid_die` is true, disallowed comments return a WP_Error.
  599. */
  600. function wp_allow_comment( $commentdata, $avoid_die = false ) {
  601. global $wpdb;
  602. // Simple duplicate check.
  603. // expected_slashed ($comment_post_ID, $comment_author, $comment_author_email, $comment_content)
  604. $dupe = $wpdb->prepare(
  605. "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_parent = %s AND comment_approved != 'trash' AND ( comment_author = %s ",
  606. wp_unslash( $commentdata['comment_post_ID'] ),
  607. wp_unslash( $commentdata['comment_parent'] ),
  608. wp_unslash( $commentdata['comment_author'] )
  609. );
  610. if ( $commentdata['comment_author_email'] ) {
  611. $dupe .= $wpdb->prepare(
  612. 'AND comment_author_email = %s ',
  613. wp_unslash( $commentdata['comment_author_email'] )
  614. );
  615. }
  616. $dupe .= $wpdb->prepare(
  617. ') AND comment_content = %s LIMIT 1',
  618. wp_unslash( $commentdata['comment_content'] )
  619. );
  620. $dupe_id = $wpdb->get_var( $dupe );
  621. /**
  622. * Filters the ID, if any, of the duplicate comment found when creating a new comment.
  623. *
  624. * Return an empty value from this filter to allow what WP considers a duplicate comment.
  625. *
  626. * @since 4.4.0
  627. *
  628. * @param int $dupe_id ID of the comment identified as a duplicate.
  629. * @param array $commentdata Data for the comment being created.
  630. */
  631. $dupe_id = apply_filters( 'duplicate_comment_id', $dupe_id, $commentdata );
  632. if ( $dupe_id ) {
  633. /**
  634. * Fires immediately after a duplicate comment is detected.
  635. *
  636. * @since 3.0.0
  637. *
  638. * @param array $commentdata Comment data.
  639. */
  640. do_action( 'comment_duplicate_trigger', $commentdata );
  641. /**
  642. * Filters duplicate comment error message.
  643. *
  644. * @since 5.2.0
  645. *
  646. * @param string $comment_duplicate_message Duplicate comment error message.
  647. */
  648. $comment_duplicate_message = apply_filters( 'comment_duplicate_message', __( 'Duplicate comment detected; it looks as though you&#8217;ve already said that!' ) );
  649. if ( true === $avoid_die ) {
  650. return new WP_Error( 'comment_duplicate', $comment_duplicate_message, 409 );
  651. } else {
  652. if ( wp_doing_ajax() ) {
  653. die( $comment_duplicate_message );
  654. }
  655. wp_die( $comment_duplicate_message, 409 );
  656. }
  657. }
  658. /**
  659. * Fires immediately before a comment is marked approved.
  660. *
  661. * Allows checking for comment flooding.
  662. *
  663. * @since 2.3.0
  664. * @since 4.7.0 The `$avoid_die` parameter was added.
  665. *
  666. * @param string $comment_author_IP Comment author's IP address.
  667. * @param string $comment_author_email Comment author's email.
  668. * @param string $comment_date_gmt GMT date the comment was posted.
  669. * @param bool $avoid_die Whether to prevent executing wp_die()
  670. * or die() if a comment flood is occurring.
  671. */
  672. do_action(
  673. 'check_comment_flood',
  674. $commentdata['comment_author_IP'],
  675. $commentdata['comment_author_email'],
  676. $commentdata['comment_date_gmt'],
  677. $avoid_die
  678. );
  679. /**
  680. * Filters whether a comment is part of a comment flood.
  681. *
  682. * The default check is wp_check_comment_flood(). See check_comment_flood_db().
  683. *
  684. * @since 4.7.0
  685. *
  686. * @param bool $is_flood Is a comment flooding occurring? Default false.
  687. * @param string $comment_author_IP Comment author's IP address.
  688. * @param string $comment_author_email Comment author's email.
  689. * @param string $comment_date_gmt GMT date the comment was posted.
  690. * @param bool $avoid_die Whether to prevent executing wp_die()
  691. * or die() if a comment flood is occurring.
  692. */
  693. $is_flood = apply_filters(
  694. 'wp_is_comment_flood',
  695. false,
  696. $commentdata['comment_author_IP'],
  697. $commentdata['comment_author_email'],
  698. $commentdata['comment_date_gmt'],
  699. $avoid_die
  700. );
  701. if ( $is_flood ) {
  702. /** This filter is documented in wp-includes/comment-template.php */
  703. $comment_flood_message = apply_filters( 'comment_flood_message', __( 'You are posting comments too quickly. Slow down.' ) );
  704. return new WP_Error( 'comment_flood', $comment_flood_message, 429 );
  705. }
  706. if ( ! empty( $commentdata['user_id'] ) ) {
  707. $user = get_userdata( $commentdata['user_id'] );
  708. $post_author = $wpdb->get_var(
  709. $wpdb->prepare(
  710. "SELECT post_author FROM $wpdb->posts WHERE ID = %d LIMIT 1",
  711. $commentdata['comment_post_ID']
  712. )
  713. );
  714. }
  715. if ( isset( $user ) && ( $commentdata['user_id'] == $post_author || $user->has_cap( 'moderate_comments' ) ) ) {
  716. // The author and the admins get respect.
  717. $approved = 1;
  718. } else {
  719. // Everyone else's comments will be checked.
  720. if ( check_comment(
  721. $commentdata['comment_author'],
  722. $commentdata['comment_author_email'],
  723. $commentdata['comment_author_url'],
  724. $commentdata['comment_content'],
  725. $commentdata['comment_author_IP'],
  726. $commentdata['comment_agent'],
  727. $commentdata['comment_type']
  728. ) ) {
  729. $approved = 1;
  730. } else {
  731. $approved = 0;
  732. }
  733. if ( wp_blacklist_check(
  734. $commentdata['comment_author'],
  735. $commentdata['comment_author_email'],
  736. $commentdata['comment_author_url'],
  737. $commentdata['comment_content'],
  738. $commentdata['comment_author_IP'],
  739. $commentdata['comment_agent']
  740. ) ) {
  741. $approved = EMPTY_TRASH_DAYS ? 'trash' : 'spam';
  742. }
  743. }
  744. /**
  745. * Filters a comment's approval status before it is set.
  746. *
  747. * @since 2.1.0
  748. * @since 4.9.0 Returning a WP_Error value from the filter will shortcircuit comment insertion
  749. * and allow skipping further processing.
  750. *
  751. * @param int|string|WP_Error $approved The approval status. Accepts 1, 0, 'spam', 'trash',
  752. * or WP_Error.
  753. * @param array $commentdata Comment data.
  754. */
  755. return apply_filters( 'pre_comment_approved', $approved, $commentdata );
  756. }
  757. /**
  758. * Hooks WP's native database-based comment-flood check.
  759. *
  760. * This wrapper maintains backward compatibility with plugins that expect to
  761. * be able to unhook the legacy check_comment_flood_db() function from
  762. * 'check_comment_flood' using remove_action().
  763. *
  764. * @since 2.3.0
  765. * @since 4.7.0 Converted to be an add_filter() wrapper.
  766. */
  767. function check_comment_flood_db() {
  768. add_filter( 'wp_is_comment_flood', 'wp_check_comment_flood', 10, 5 );
  769. }
  770. /**
  771. * Checks whether comment flooding is occurring.
  772. *
  773. * Won't run, if current user can manage options, so to not block
  774. * administrators.
  775. *
  776. * @since 4.7.0
  777. *
  778. * @global wpdb $wpdb WordPress database abstraction object.
  779. *
  780. * @param bool $is_flood Is a comment flooding occurring?
  781. * @param string $ip Comment author's IP address.
  782. * @param string $email Comment author's email address.
  783. * @param string $date MySQL time string.
  784. * @param bool $avoid_die When true, a disallowed comment will result in the function
  785. * returning a WP_Error object, rather than executing wp_die().
  786. * Default false.
  787. * @return bool Whether comment flooding is occurring.
  788. */
  789. function wp_check_comment_flood( $is_flood, $ip, $email, $date, $avoid_die = false ) {
  790. global $wpdb;
  791. // Another callback has declared a flood. Trust it.
  792. if ( true === $is_flood ) {
  793. return $is_flood;
  794. }
  795. // Don't throttle admins or moderators.
  796. if ( current_user_can( 'manage_options' ) || current_user_can( 'moderate_comments' ) ) {
  797. return false;
  798. }
  799. $hour_ago = gmdate( 'Y-m-d H:i:s', time() - HOUR_IN_SECONDS );
  800. if ( is_user_logged_in() ) {
  801. $user = get_current_user_id();
  802. $check_column = '`user_id`';
  803. } else {
  804. $user = $ip;
  805. $check_column = '`comment_author_IP`';
  806. }
  807. $sql = $wpdb->prepare(
  808. "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",
  809. $hour_ago,
  810. $user,
  811. $email
  812. );
  813. $lasttime = $wpdb->get_var( $sql );
  814. if ( $lasttime ) {
  815. $time_lastcomment = mysql2date( 'U', $lasttime, false );
  816. $time_newcomment = mysql2date( 'U', $date, false );
  817. /**
  818. * Filters the comment flood status.
  819. *
  820. * @since 2.1.0
  821. *
  822. * @param bool $bool Whether a comment flood is occurring. Default false.
  823. * @param int $time_lastcomment Timestamp of when the last comment was posted.
  824. * @param int $time_newcomment Timestamp of when the new comment was posted.
  825. */
  826. $flood_die = apply_filters( 'comment_flood_filter', false, $time_lastcomment, $time_newcomment );
  827. if ( $flood_die ) {
  828. /**
  829. * Fires before the comment flood message is triggered.
  830. *
  831. * @since 1.5.0
  832. *
  833. * @param int $time_lastcomment Timestamp of when the last comment was posted.
  834. * @param int $time_newcomment Timestamp of when the new comment was posted.
  835. */
  836. do_action( 'comment_flood_trigger', $time_lastcomment, $time_newcomment );
  837. if ( true === $avoid_die ) {
  838. return true;
  839. } else {
  840. /**
  841. * Filters the comment flood error message.
  842. *
  843. * @since 5.2.0
  844. *
  845. * @param string $comment_flood_message Comment flood error message.
  846. */
  847. $comment_flood_message = apply_filters( 'comment_flood_message', __( 'You are posting comments too quickly. Slow down.' ) );
  848. if ( wp_doing_ajax() ) {
  849. die( $comment_flood_message );
  850. }
  851. wp_die( $comment_flood_message, 429 );
  852. }
  853. }
  854. }
  855. return false;
  856. }
  857. /**
  858. * Separates an array of comments into an array keyed by comment_type.
  859. *
  860. * @since 2.7.0
  861. *
  862. * @param WP_Comment[] $comments Array of comments
  863. * @return WP_Comment[] Array of comments keyed by comment_type.
  864. */
  865. function separate_comments( &$comments ) {
  866. $comments_by_type = array(
  867. 'comment' => array(),
  868. 'trackback' => array(),
  869. 'pingback' => array(),
  870. 'pings' => array(),
  871. );
  872. $count = count( $comments );
  873. for ( $i = 0; $i < $count; $i++ ) {
  874. $type = $comments[ $i ]->comment_type;
  875. if ( empty( $type ) ) {
  876. $type = 'comment';
  877. }
  878. $comments_by_type[ $type ][] = &$comments[ $i ];
  879. if ( 'trackback' == $type || 'pingback' == $type ) {
  880. $comments_by_type['pings'][] = &$comments[ $i ];
  881. }
  882. }
  883. return $comments_by_type;
  884. }
  885. /**
  886. * Calculate the total number of comment pages.
  887. *
  888. * @since 2.7.0
  889. *
  890. * @uses Walker_Comment
  891. *
  892. * @global WP_Query $wp_query WordPress Query object.
  893. *
  894. * @param WP_Comment[] $comments Optional. Array of WP_Comment objects. Defaults to $wp_query->comments.
  895. * @param int $per_page Optional. Comments per page.
  896. * @param bool $threaded Optional. Control over flat or threaded comments.
  897. * @return int Number of comment pages.
  898. */
  899. function get_comment_pages_count( $comments = null, $per_page = null, $threaded = null ) {
  900. global $wp_query;
  901. if ( null === $comments && null === $per_page && null === $threaded && ! empty( $wp_query->max_num_comment_pages ) ) {
  902. return $wp_query->max_num_comment_pages;
  903. }
  904. if ( ( ! $comments || ! is_array( $comments ) ) && ! empty( $wp_query->comments ) ) {
  905. $comments = $wp_query->comments;
  906. }
  907. if ( empty( $comments ) ) {
  908. return 0;
  909. }
  910. if ( ! get_option( 'page_comments' ) ) {
  911. return 1;
  912. }
  913. if ( ! isset( $per_page ) ) {
  914. $per_page = (int) get_query_var( 'comments_per_page' );
  915. }
  916. if ( 0 === $per_page ) {
  917. $per_page = (int) get_option( 'comments_per_page' );
  918. }
  919. if ( 0 === $per_page ) {
  920. return 1;
  921. }
  922. if ( ! isset( $threaded ) ) {
  923. $threaded = get_option( 'thread_comments' );
  924. }
  925. if ( $threaded ) {
  926. $walker = new Walker_Comment;
  927. $count = ceil( $walker->get_number_of_root_elements( $comments ) / $per_page );
  928. } else {
  929. $count = ceil( count( $comments ) / $per_page );
  930. }
  931. return $count;
  932. }
  933. /**
  934. * Calculate what page number a comment will appear on for comment paging.
  935. *
  936. * @since 2.7.0
  937. *
  938. * @global wpdb $wpdb WordPress database abstraction object.
  939. *
  940. * @param int $comment_ID Comment ID.
  941. * @param array $args {
  942. * Array of optional arguments.
  943. * @type string $type Limit paginated comments to those matching a given type. Accepts 'comment',
  944. * 'trackback', 'pingback', 'pings' (trackbacks and pingbacks), or 'all'.
  945. * Default is 'all'.
  946. * @type int $per_page Per-page count to use when calculating pagination. Defaults to the value of the
  947. * 'comments_per_page' option.
  948. * @type int|string $max_depth If greater than 1, comment page will be determined for the top-level parent of
  949. * `$comment_ID`. Defaults to the value of the 'thread_comments_depth' option.
  950. * } *
  951. * @return int|null Comment page number or null on error.
  952. */
  953. function get_page_of_comment( $comment_ID, $args = array() ) {
  954. global $wpdb;
  955. $page = null;
  956. $comment = get_comment( $comment_ID );
  957. if ( ! $comment ) {
  958. return;
  959. }
  960. $defaults = array(
  961. 'type' => 'all',
  962. 'page' => '',
  963. 'per_page' => '',
  964. 'max_depth' => '',
  965. );
  966. $args = wp_parse_args( $args, $defaults );
  967. $original_args = $args;
  968. // Order of precedence: 1. `$args['per_page']`, 2. 'comments_per_page' query_var, 3. 'comments_per_page' option.
  969. if ( get_option( 'page_comments' ) ) {
  970. if ( '' === $args['per_page'] ) {
  971. $args['per_page'] = get_query_var( 'comments_per_page' );
  972. }
  973. if ( '' === $args['per_page'] ) {
  974. $args['per_page'] = get_option( 'comments_per_page' );
  975. }
  976. }
  977. if ( empty( $args['per_page'] ) ) {
  978. $args['per_page'] = 0;
  979. $args['page'] = 0;
  980. }
  981. if ( $args['per_page'] < 1 ) {
  982. $page = 1;
  983. }
  984. if ( null === $page ) {
  985. if ( '' === $args['max_depth'] ) {
  986. if ( get_option( 'thread_comments' ) ) {
  987. $args['max_depth'] = get_option( 'thread_comments_depth' );
  988. } else {
  989. $args['max_depth'] = -1;
  990. }
  991. }
  992. // Find this comment's top-level parent if threading is enabled.
  993. if ( $args['max_depth'] > 1 && 0 != $comment->comment_parent ) {
  994. return get_page_of_comment( $comment->comment_parent, $args );
  995. }
  996. $comment_args = array(
  997. 'type' => $args['type'],
  998. 'post_id' => $comment->comment_post_ID,
  999. 'fields' => 'ids',
  1000. 'count' => true,
  1001. 'status' => 'approve',
  1002. 'parent' => 0,
  1003. 'date_query' => array(
  1004. array(
  1005. 'column' => "$wpdb->comments.comment_date_gmt",
  1006. 'before' => $comment->comment_date_gmt,
  1007. ),
  1008. ),
  1009. );
  1010. $comment_query = new WP_Comment_Query();
  1011. $older_comment_count = $comment_query->query( $comment_args );
  1012. // No older comments? Then it's page #1.
  1013. if ( 0 == $older_comment_count ) {
  1014. $page = 1;
  1015. // Divide comments older than this one by comments per page to get this comment's page number.
  1016. } else {
  1017. $page = ceil( ( $older_comment_count + 1 ) / $args['per_page'] );
  1018. }
  1019. }
  1020. /**
  1021. * Filters the calculated page on which a comment appears.
  1022. *
  1023. * @since 4.4.0
  1024. * @since 4.7.0 Introduced the `$comment_ID` parameter.
  1025. *
  1026. * @param int $page Comment page.
  1027. * @param array $args {
  1028. * Arguments used to calculate pagination. These include arguments auto-detected by the function,
  1029. * based on query vars, system settings, etc. For pristine arguments passed to the function,
  1030. * see `$original_args`.
  1031. *
  1032. * @type string $type Type of comments to count.
  1033. * @type int $page Calculated current page.
  1034. * @type int $per_page Calculated number of comments per page.
  1035. * @type int $max_depth Maximum comment threading depth allowed.
  1036. * }
  1037. * @param array $original_args {
  1038. * Array of arguments passed to the function. Some or all of these may not be set.
  1039. *
  1040. * @type string $type Type of comments to count.
  1041. * @type int $page Current comment page.
  1042. * @type int $per_page Number of comments per page.
  1043. * @type int $max_depth Maximum comment threading depth allowed.
  1044. * }
  1045. * @param int $comment_ID ID of the comment.
  1046. */
  1047. return apply_filters( 'get_page_of_comment', (int) $page, $args, $original_args, $comment_ID );
  1048. }
  1049. /**
  1050. * Retrieves the maximum character lengths for the comment form fields.
  1051. *
  1052. * @since 4.5.0
  1053. *
  1054. * @global wpdb $wpdb WordPress database abstraction object.
  1055. *
  1056. * @return int[] Array of maximum lengths keyed by field name.
  1057. */
  1058. function wp_get_comment_fields_max_lengths() {
  1059. global $wpdb;
  1060. $lengths = array(
  1061. 'comment_author' => 245,
  1062. 'comment_author_email' => 100,
  1063. 'comment_author_url' => 200,
  1064. 'comment_content' => 65525,
  1065. );
  1066. if ( $wpdb->is_mysql ) {
  1067. foreach ( $lengths as $column => $length ) {
  1068. $col_length = $wpdb->get_col_length( $wpdb->comments, $column );
  1069. $max_length = 0;
  1070. // No point if we can't get the DB column lengths.
  1071. if ( is_wp_error( $col_length ) ) {
  1072. break;
  1073. }
  1074. if ( ! is_array( $col_length ) && (int) $col_length > 0 ) {
  1075. $max_length = (int) $col_length;
  1076. } elseif ( is_array( $col_length ) && isset( $col_length['length'] ) && intval( $col_length['length'] ) > 0 ) {
  1077. $max_length = (int) $col_length['length'];
  1078. if ( ! empty( $col_length['type'] ) && 'byte' === $col_length['type'] ) {
  1079. $max_length = $max_length - 10;
  1080. }
  1081. }
  1082. if ( $max_length > 0 ) {
  1083. $lengths[ $column ] = $max_length;
  1084. }
  1085. }
  1086. }
  1087. /**
  1088. * Filters the lengths for the comment form fields.
  1089. *
  1090. * @since 4.5.0
  1091. *
  1092. * @param int[] $lengths Array of maximum lengths keyed by field name.
  1093. */
  1094. return apply_filters( 'wp_get_comment_fields_max_lengths', $lengths );
  1095. }
  1096. /**
  1097. * Compares the lengths of comment data against the maximum character limits.
  1098. *
  1099. * @since 4.7.0
  1100. *
  1101. * @param array $comment_data Array of arguments for inserting a comment.
  1102. * @return WP_Error|true WP_Error when a comment field exceeds the limit,
  1103. * otherwise true.
  1104. */
  1105. function wp_check_comment_data_max_lengths( $comment_data ) {
  1106. $max_lengths = wp_get_comment_fields_max_lengths();
  1107. if ( isset( $comment_data['comment_author'] ) && mb_strlen( $comment_data['comment_author'], '8bit' ) > $max_lengths['comment_author'] ) {
  1108. return new WP_Error( 'comment_author_column_length', __( '<strong>Error</strong>: Your name is too long.' ), 200 );
  1109. }
  1110. if ( isset( $comment_data['comment_author_email'] ) && strlen( $comment_data['comment_author_email'] ) > $max_lengths['comment_author_email'] ) {
  1111. return new WP_Error( 'comment_author_email_column_length', __( '<strong>Error</strong>: Your email address is too long.' ), 200 );
  1112. }
  1113. if ( isset( $comment_data['comment_author_url'] ) && strlen( $comment_data['comment_author_url'] ) > $max_lengths['comment_author_url'] ) {
  1114. return new WP_Error( 'comment_author_url_column_length', __( '<strong>Error</strong>: Your URL is too long.' ), 200 );
  1115. }
  1116. if ( isset( $comment_data['comment_content'] ) && mb_strlen( $comment_data['comment_content'], '8bit' ) > $max_lengths['comment_content'] ) {
  1117. return new WP_Error( 'comment_content_column_length', __( '<strong>Error</strong>: Your comment is too long.' ), 200 );
  1118. }
  1119. return true;
  1120. }
  1121. /**
  1122. * Does comment contain blacklisted characters or words.
  1123. *
  1124. * @since 1.5.0
  1125. *
  1126. * @param string $author The author of the comment
  1127. * @param string $email The email of the comment
  1128. * @param string $url The url used in the comment
  1129. * @param string $comment The comment content
  1130. * @param string $user_ip The comment author's IP address
  1131. * @param string $user_agent The author's browser user agent
  1132. * @return bool True if comment contains blacklisted content, false if comment does not
  1133. */
  1134. function wp_blacklist_check( $author, $email, $url, $comment, $user_ip, $user_agent ) {
  1135. /**
  1136. * Fires before the comment is tested for blacklisted characters or words.
  1137. *
  1138. * @since 1.5.0
  1139. *
  1140. * @param string $author Comment author.
  1141. * @param string $email Comment author's email.
  1142. * @param string $url Comment author's URL.
  1143. * @param string $comment Comment content.
  1144. * @param string $user_ip Comment author's IP address.
  1145. * @param string $user_agent Comment author's browser user agent.
  1146. */
  1147. do_action( 'wp_blacklist_check', $author, $email, $url, $comment, $user_ip, $user_agent );
  1148. $mod_keys = trim( get_option( 'blacklist_keys' ) );
  1149. if ( '' == $mod_keys ) {
  1150. return false; // If moderation keys are empty.
  1151. }
  1152. // Ensure HTML tags are not being used to bypass the blacklist.
  1153. $comment_without_html = wp_strip_all_tags( $comment );
  1154. $words = explode( "\n", $mod_keys );
  1155. foreach ( (array) $words as $word ) {
  1156. $word = trim( $word );
  1157. // Skip empty lines.
  1158. if ( empty( $word ) ) {
  1159. continue; }
  1160. // Do some escaping magic so that '#' chars
  1161. // in the spam words don't break things:
  1162. $word = preg_quote( $word, '#' );
  1163. $pattern = "#$word#i";
  1164. if ( preg_match( $pattern, $author )
  1165. || preg_match( $pattern, $email )
  1166. || preg_match( $pattern, $url )
  1167. || preg_match( $pattern, $comment )
  1168. || preg_match( $pattern, $comment_without_html )
  1169. || preg_match( $pattern, $user_ip )
  1170. || preg_match( $pattern, $user_agent )
  1171. ) {
  1172. return true;
  1173. }
  1174. }
  1175. return false;
  1176. }
  1177. /**
  1178. * Retrieves the total comment counts for the whole site or a single post.
  1179. *
  1180. * The comment stats are cached and then retrieved, if they already exist in the
  1181. * cache.
  1182. *
  1183. * @see get_comment_count() Which handles fetching the live comment counts.
  1184. *
  1185. * @since 2.5.0
  1186. *
  1187. * @param int $post_id Optional. Restrict the comment counts to the given post. Default 0, which indicates that
  1188. * comment counts for the whole site will be retrieved.
  1189. * @return stdClass {
  1190. * The number of comments keyed by their status.
  1191. *
  1192. * @type int|string $approved The number of approved comments.
  1193. * @type int|string $moderated The number of comments awaiting moderation (a.k.a. pending).
  1194. * @type int|string $spam The number of spam comments.
  1195. * @type int|string $trash The number of trashed comments.
  1196. * @type int|string $post-trashed The number of comments for posts that are in the trash.
  1197. * @type int $total_comments The total number of non-trashed comments, including spam.
  1198. * @type int $all The total number of pending or approved comments.
  1199. * }
  1200. */
  1201. function wp_count_comments( $post_id = 0 ) {
  1202. $post_id = (int) $post_id;
  1203. /**
  1204. * Filters the comments count for a given post or the whole site.
  1205. *
  1206. * @since 2.7.0
  1207. *
  1208. * @param array|stdClass $count An empty array or an object containing comment counts.
  1209. * @param int $post_id The post ID. Can be 0 to represent the whole site.
  1210. */
  1211. $filtered = apply_filters( 'wp_count_comments', array(), $post_id );
  1212. if ( ! empty( $filtered ) ) {
  1213. return $filtered;
  1214. }
  1215. $count = wp_cache_get( "comments-{$post_id}", 'counts' );
  1216. if ( false !== $count ) {
  1217. return $count;
  1218. }
  1219. $stats = get_comment_count( $post_id );
  1220. $stats['moderated'] = $stats['awaiting_moderation'];
  1221. unset( $stats['awaiting_moderation'] );
  1222. $stats_object = (object) $stats;
  1223. wp_cache_set( "comments-{$post_id}", $stats_object, 'counts' );
  1224. return $stats_object;
  1225. }
  1226. /**
  1227. * Trashes or deletes a comment.
  1228. *
  1229. * The comment is moved to Trash instead of permanently deleted unless Trash is
  1230. * disabled, item is already in the Trash, or $force_delete is true.
  1231. *
  1232. * The post comment count will be updated if the comment was approved and has a
  1233. * post ID available.
  1234. *
  1235. * @since 2.0.0
  1236. *
  1237. * @global wpdb $wpdb WordPress database abstraction object.
  1238. *
  1239. * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
  1240. * @param bool $force_delete Whether to bypass Trash and force deletion. Default is false.
  1241. * @return bool True on success, false on failure.
  1242. */
  1243. function wp_delete_comment( $comment_id, $force_delete = false ) {
  1244. global $wpdb;
  1245. $comment = get_comment( $comment_id );
  1246. if ( ! $comment ) {
  1247. return false;
  1248. }
  1249. if ( ! $force_delete && EMPTY_TRASH_DAYS && ! in_array( wp_get_comment_status( $comment ), array( 'trash', 'spam' ) ) ) {
  1250. return wp_trash_comment( $comment_id );
  1251. }
  1252. /**
  1253. * Fires immediately before a comment is deleted from the database.
  1254. *
  1255. * @since 1.2.0
  1256. * @since 4.9.0 Added the `$comment` parameter.
  1257. *
  1258. * @param int $comment_id The comment ID.
  1259. * @param WP_Comment $comment The comment to be deleted.
  1260. */
  1261. do_action( 'delete_comment', $comment->comment_ID, $comment );
  1262. // Move children up a level.
  1263. $children = $wpdb->get_col( $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_parent = %d", $comment->comment_ID ) );
  1264. if ( ! empty( $children ) ) {
  1265. $wpdb->update( $wpdb->comments, array( 'comment_parent' => $comment->comment_parent ), array( 'comment_parent' => $comment->comment_ID ) );
  1266. clean_comment_cache( $children );
  1267. }
  1268. // Delete metadata.
  1269. $meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->commentmeta WHERE comment_id = %d", $comment->comment_ID ) );
  1270. foreach ( $meta_ids as $mid ) {
  1271. delete_metadata_by_mid( 'comment', $mid );
  1272. }
  1273. if ( ! $wpdb->delete( $wpdb->comments, array( 'comment_ID' => $comment->comment_ID ) ) ) {
  1274. return false;
  1275. }
  1276. /**
  1277. * Fires immediately after a comment is deleted from the database.
  1278. *
  1279. * @since 2.9.0
  1280. * @since 4.9.0 Added the `$comment` parameter.
  1281. *
  1282. * @param int $comment_id The comment ID.
  1283. * @param WP_Comment $comment The deleted comment.
  1284. */
  1285. do_action( 'deleted_comment', $comment->comment_ID, $comment );
  1286. $post_id = $comment->comment_post_ID;
  1287. if ( $post_id && 1 == $comment->comment_approved ) {
  1288. wp_update_comment_count( $post_id );
  1289. }
  1290. clean_comment_cache( $comment->comment_ID );
  1291. /** This action is documented in wp-includes/comment.php */
  1292. do_action( 'wp_set_comment_status', $comment->comment_ID, 'delete' );
  1293. wp_transition_comment_status( 'delete', $comment->comment_approved, $comment );
  1294. return true;
  1295. }
  1296. /**
  1297. * Moves a comment to the Trash
  1298. *
  1299. * If Trash is disabled, comment is permanently deleted.
  1300. *
  1301. * @since 2.9.0
  1302. *
  1303. * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
  1304. * @return bool True on success, false on failure.
  1305. */
  1306. function wp_trash_comment( $comment_id ) {
  1307. if ( ! EMPTY_TRASH_DAYS ) {
  1308. return wp_delete_comment( $comment_id, true );
  1309. }
  1310. $comment = get_comment( $comment_id );
  1311. if ( ! $comment ) {
  1312. return false;
  1313. }
  1314. /**
  1315. * Fires immediately before a comment is sent to the Trash.
  1316. *
  1317. * @since 2.9.0
  1318. * @since 4.9.0 Added the `$comment` parameter.
  1319. *
  1320. * @param int $comment_id The comment ID.
  1321. * @param WP_Comment $comment The comment to be trashed.
  1322. */
  1323. do_action( 'trash_comment', $comment->comment_ID, $comment );
  1324. if ( wp_set_comment_status( $comment, 'trash' ) ) {
  1325. delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_status' );
  1326. delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_time' );
  1327. add_comment_meta( $comment->comment_ID, '_wp_trash_meta_status', $comment->comment_approved );
  1328. add_comment_meta( $comment->comment_ID, '_wp_trash_meta_time', time() );
  1329. /**
  1330. * Fires immediately after a comment is sent to Trash.
  1331. *
  1332. * @since 2.9.0
  1333. * @since 4.9.0 Added the `$comment` parameter.
  1334. *
  1335. * @param int $comment_id The comment ID.
  1336. * @param WP_Comment $comment The trashed comment.
  1337. */
  1338. do_action( 'trashed_comment', $comment->comment_ID, $comment );
  1339. return true;
  1340. }
  1341. return false;
  1342. }
  1343. /**
  1344. * Removes a comment from the Trash
  1345. *
  1346. * @since 2.9.0
  1347. *
  1348. * @param int|WP_Comment $comment_id Comment ID or WP_Comment object.
  1349. * @return bool True on success, false on failure.
  1350. */
  1351. function wp_untrash_comment( $comment_id ) {
  1352. $comment = get_comment( $comment_id );
  1353. if ( ! $comment ) {
  1354. return false;
  1355. }
  1356. /**
  1357. * Fires immediately before a comment is restored from the Trash.
  1358. *
  1359. * @since 2.9.0
  1360. * @since 4.9.0 Added the `$comment` parameter.
  1361. *
  1362. * @param int $comment_id The comment ID.
  1363. * @param WP_Comment $comment The comment to be untrashed.
  1364. */
  1365. do_action( 'untrash_comment', $comment->comment_ID, $comment );
  1366. $status = (string) get_comment_meta( $comment->comment_ID, '_wp_trash_meta_status', true );
  1367. if ( empty( $status ) ) {
  1368. $status = '0';
  1369. }
  1370. if ( wp_set_comment_status( $comment, $status ) ) {
  1371. delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_time' );
  1372. delete_comment_meta( $comment->comment_ID, '_wp_trash_meta_status' );
  1373. /**