PageRenderTime 58ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/comment.php

https://bitbucket.org/acipriani/madeinapulia.com
PHP | 2847 lines | 1272 code | 346 blank | 1229 comment | 301 complexity | 5a0e6d428fe58583f12326e7dc184db2 MD5 | raw file
Possible License(s): GPL-3.0, MIT, BSD-3-Clause, LGPL-2.1, GPL-2.0, Apache-2.0

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * Manages WordPress comments
  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. /** This filter is documented in wp-includes/comment-template.php */
  44. $comment = apply_filters( 'comment_text', $comment );
  45. // Check for the number of external links if a max allowed number is set.
  46. if ( $max_links = get_option( 'comment_max_links' ) ) {
  47. $num_links = preg_match_all( '/<a [^>]*href/i', $comment, $out );
  48. /**
  49. * Filter the maximum number of links allowed in a comment.
  50. *
  51. * @since 3.0.0
  52. *
  53. * @param int $num_links The number of links allowed.
  54. * @param string $url Comment author's URL. Included in allowed links total.
  55. */
  56. $num_links = apply_filters( 'comment_max_links_url', $num_links, $url );
  57. /*
  58. * If the number of links in the comment exceeds the allowed amount,
  59. * fail the check by returning false.
  60. */
  61. if ( $num_links >= $max_links )
  62. return false;
  63. }
  64. $mod_keys = trim(get_option('moderation_keys'));
  65. // If moderation 'keys' (keywords) are set, process them.
  66. if ( !empty($mod_keys) ) {
  67. $words = explode("\n", $mod_keys );
  68. foreach ( (array) $words as $word) {
  69. $word = trim($word);
  70. // Skip empty lines.
  71. if ( empty($word) )
  72. continue;
  73. /*
  74. * Do some escaping magic so that '#' (number of) characters in the spam
  75. * words don't break things:
  76. */
  77. $word = preg_quote($word, '#');
  78. /*
  79. * Check the comment fields for moderation keywords. If any are found,
  80. * fail the check for the given field by returning false.
  81. */
  82. $pattern = "#$word#i";
  83. if ( preg_match($pattern, $author) ) return false;
  84. if ( preg_match($pattern, $email) ) return false;
  85. if ( preg_match($pattern, $url) ) return false;
  86. if ( preg_match($pattern, $comment) ) return false;
  87. if ( preg_match($pattern, $user_ip) ) return false;
  88. if ( preg_match($pattern, $user_agent) ) return false;
  89. }
  90. }
  91. /*
  92. * Check if the option to approve comments by previously-approved authors is enabled.
  93. *
  94. * If it is enabled, check whether the comment author has a previously-approved comment,
  95. * as well as whether there are any moderation keywords (if set) present in the author
  96. * email address. If both checks pass, return true. Otherwise, return false.
  97. */
  98. if ( 1 == get_option('comment_whitelist')) {
  99. if ( 'trackback' != $comment_type && 'pingback' != $comment_type && $author != '' && $email != '' ) {
  100. // expected_slashed ($author, $email)
  101. $ok_to_comment = $wpdb->get_var("SELECT comment_approved FROM $wpdb->comments WHERE comment_author = '$author' AND comment_author_email = '$email' and comment_approved = '1' LIMIT 1");
  102. if ( ( 1 == $ok_to_comment ) &&
  103. ( empty($mod_keys) || false === strpos( $email, $mod_keys) ) )
  104. return true;
  105. else
  106. return false;
  107. } else {
  108. return false;
  109. }
  110. }
  111. return true;
  112. }
  113. /**
  114. * Retrieve the approved comments for post $post_id.
  115. *
  116. * @since 2.0.0
  117. * @since 4.1.0 Refactored to leverage {@see WP_Comment_Query} over a direct query.
  118. *
  119. * @param int $post_id The ID of the post.
  120. * @param array $args Optional. See {@see WP_Comment_Query::query()} for information
  121. * on accepted arguments.
  122. * @return int|array $comments The approved comments, or number of comments if `$count`
  123. * argument is true.
  124. */
  125. function get_approved_comments( $post_id, $args = array() ) {
  126. if ( ! $post_id ) {
  127. return array();
  128. }
  129. $defaults = array(
  130. 'status' => 1,
  131. 'post_id' => $post_id,
  132. 'order' => 'ASC',
  133. );
  134. $r = wp_parse_args( $args, $defaults );
  135. $query = new WP_Comment_Query;
  136. return $query->query( $r );
  137. }
  138. /**
  139. * Retrieves comment data given a comment ID or comment object.
  140. *
  141. * If an object is passed then the comment data will be cached and then returned
  142. * after being passed through a filter. If the comment is empty, then the global
  143. * comment variable will be used, if it is set.
  144. *
  145. * @since 2.0.0
  146. *
  147. * @global wpdb $wpdb WordPress database abstraction object.
  148. *
  149. * @param object|string|int $comment Comment to retrieve.
  150. * @param string $output Optional. OBJECT or ARRAY_A or ARRAY_N constants.
  151. * @return object|array|null Depends on $output value.
  152. */
  153. function get_comment(&$comment, $output = OBJECT) {
  154. global $wpdb;
  155. if ( empty($comment) ) {
  156. if ( isset($GLOBALS['comment']) )
  157. $_comment = & $GLOBALS['comment'];
  158. else
  159. $_comment = null;
  160. } elseif ( is_object($comment) ) {
  161. wp_cache_add($comment->comment_ID, $comment, 'comment');
  162. $_comment = $comment;
  163. } else {
  164. if ( isset($GLOBALS['comment']) && ($GLOBALS['comment']->comment_ID == $comment) ) {
  165. $_comment = & $GLOBALS['comment'];
  166. } elseif ( ! $_comment = wp_cache_get($comment, 'comment') ) {
  167. $_comment = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_ID = %d LIMIT 1", $comment));
  168. if ( ! $_comment )
  169. return null;
  170. wp_cache_add($_comment->comment_ID, $_comment, 'comment');
  171. }
  172. }
  173. /**
  174. * Fires after a comment is retrieved.
  175. *
  176. * @since 2.3.0
  177. *
  178. * @param mixed $_comment Comment data.
  179. */
  180. $_comment = apply_filters( 'get_comment', $_comment );
  181. if ( $output == OBJECT ) {
  182. return $_comment;
  183. } elseif ( $output == ARRAY_A ) {
  184. $__comment = get_object_vars($_comment);
  185. return $__comment;
  186. } elseif ( $output == ARRAY_N ) {
  187. $__comment = array_values(get_object_vars($_comment));
  188. return $__comment;
  189. } else {
  190. return $_comment;
  191. }
  192. }
  193. /**
  194. * Retrieve a list of comments.
  195. *
  196. * The comment list can be for the blog as a whole or for an individual post.
  197. *
  198. * @since 2.7.0
  199. *
  200. * @global wpdb $wpdb WordPress database abstraction object.
  201. *
  202. * @param string|array $args Optional. Array or string of arguments. See {@see WP_Comment_Query::query()}
  203. * for information on accepted arguments. Default empty.
  204. * @return int|array List of comments or number of found comments if `$count` argument is true.
  205. */
  206. function get_comments( $args = '' ) {
  207. $query = new WP_Comment_Query;
  208. return $query->query( $args );
  209. }
  210. /**
  211. * WordPress Comment Query class.
  212. *
  213. * See {@see WP_Comment_Query::query()} for accepted arguments.
  214. *
  215. * @since 3.1.0
  216. */
  217. class WP_Comment_Query {
  218. /**
  219. * SQL for database query.
  220. *
  221. * @since 4.0.1
  222. * @access public
  223. * @var string
  224. */
  225. public $request;
  226. /**
  227. * Metadata query container
  228. *
  229. * @since 3.5.0
  230. * @access public
  231. * @var object WP_Meta_Query
  232. */
  233. public $meta_query = false;
  234. /**
  235. * Date query container
  236. *
  237. * @since 3.7.0
  238. * @access public
  239. * @var object WP_Date_Query
  240. */
  241. public $date_query = false;
  242. /**
  243. * @var array
  244. */
  245. public $query_vars;
  246. /**
  247. * @var array
  248. */
  249. public $comments;
  250. /**
  251. * Make private/protected methods readable for backwards compatibility.
  252. *
  253. * @since 4.0.0
  254. * @access public
  255. *
  256. * @param callable $name Method to call.
  257. * @param array $arguments Arguments to pass when calling.
  258. * @return mixed|bool Return value of the callback, false otherwise.
  259. */
  260. public function __call( $name, $arguments ) {
  261. return call_user_func_array( array( $this, $name ), $arguments );
  262. }
  263. /**
  264. * Execute the query
  265. *
  266. * @since 3.1.0
  267. * @since 4.1.0 Introduced 'comment__in', 'comment__not_in', 'post_author__in',
  268. * 'post_author__not_in', 'author__in', 'author__not_in', 'post__in',
  269. * 'post__not_in', 'include_unapproved', 'type__in', and 'type__not_in'
  270. * arguments to $query_vars.
  271. *
  272. * @param string|array $query_vars {
  273. * Optional. Array or query string of comment query parameters.
  274. *
  275. * @type string $author_email Comment author email address. Default empty.
  276. * @type array $author__in Array of author IDs to include comments for. Default empty.
  277. * @type array $author__not_in Array of author IDs to exclude comments for. Default empty.
  278. * @type array $comment__in Array of comment IDs to include. Default empty.
  279. * @type array $comment__not_in Array of comment IDs to exclude. Default empty.
  280. * @type bool $count Whether to return a comment count (true) or array of comment
  281. * objects (false). Default false.
  282. * @type array $date_query Date query clauses to limit comments by. See {@see WP_Date_Query}.
  283. * Default null.
  284. * @type string $fields Comment fields to return. Accepts 'ids' for comment IDs only or
  285. * empty for all fields. Default empty.
  286. * @type int $ID Currently unused.
  287. * @type array $include_unapproved Array of IDs or email addresses of users whose unapproved comments
  288. * will be returned by the query regardless of `$status`. Default empty.
  289. * @type int $karma Karma score to retrieve matching comments for. Default empty.
  290. * @type string $meta_key Include comments with a matching comment meta key. Default empty.
  291. * @type string $meta_value Include comments with a matching comment meta value. Requires
  292. * `$meta_key` to be set. Default empty.
  293. * @type array $meta_query Meta query clauses to limit retrieved comments by.
  294. * See {@see WP_Meta_Query}. Default empty.
  295. * @type int $number Maximum number of comments to retrieve. Default null (no limit).
  296. * @type int $offset Number of comments to offset the query. Used to build LIMIT clause.
  297. * Default 0.
  298. * @type string|array $orderby Comment status or array of statuses. Accepts 'comment_agent',
  299. * 'comment_approved', 'comment_author', 'comment_author_email',
  300. * 'comment_author_IP', 'comment_author_url', 'comment_content',
  301. * 'comment_date', 'comment_date_gmt', 'comment_ID', 'comment_karma',
  302. * 'comment_parent', 'comment_post_ID', 'comment_type', 'user_id',
  303. * 'meta_value', 'meta_value_num', or value of $meta_key.
  304. * Also accepts false, empty array, or 'none' to disable `ORDER BY`
  305. * clause. Default: 'comment_date_gmt'.
  306. * @type string $order How to order retrieved comments. Accepts 'ASC', 'DESC'.
  307. * Default: 'DESC'.
  308. * @type int $parent Parent ID of comment to retrieve children of. Default empty.
  309. * @type array $post_author__in Array of author IDs to retrieve comments for. Default empty.
  310. * @type array $post_author__not_in Array of author IDs *not* to retrieve comments for. Default empty.
  311. * @type int $post_ID Currently unused.
  312. * @type int $post_id Limit results to those affiliated with a given post ID. Default 0.
  313. * @type array $post__in Array of post IDs to include affiliated comments for. Default empty.
  314. * @type array $post__not_in Array of post IDs to exclude affiliated comments for. Default empty.
  315. * @type int $post_author Comment author ID to limit results by. Default empty.
  316. * @type string $post_status Post status to retrieve affiliated comments for. Default empty.
  317. * @type string $post_type Post type to retrieve affiliated comments for. Default empty.
  318. * @type string $post_name Post name to retrieve affiliated comments for. Default empty.
  319. * @type int $post_parent Post parent ID to retrieve affiliated comments for. Default empty.
  320. * @type string $search Search term(s) to retrieve matching comments for. Default empty.
  321. * @type string $status Comment status to limit results by. Accepts 'hold'
  322. * (`comment_status=0`), 'approve' (`comment_status=1`), 'all', or a
  323. * custom comment status. Default 'all'.
  324. * @type string|array $type Include comments of a given type, or array of types. Accepts
  325. * 'comment', 'pings' (includes 'pingback' and 'trackback'), or any
  326. * custom type string. Default empty.
  327. * @type array $type__in Include comments from a given array of comment types. Default empty.
  328. * @type array $type__not_in Exclude comments from a given array of comment types. Default empty.
  329. * @type int $user_id Include comments for a specific user ID. Default empty.
  330. * }
  331. * @return int|array Array of comments or number of found comments if `$count` is set to true.
  332. */
  333. public function query( $query_vars ) {
  334. global $wpdb;
  335. $defaults = array(
  336. 'author_email' => '',
  337. 'author__in' => '',
  338. 'author__not_in' => '',
  339. 'include_unapproved' => '',
  340. 'fields' => '',
  341. 'ID' => '',
  342. 'comment__in' => '',
  343. 'comment__not_in' => '',
  344. 'karma' => '',
  345. 'number' => '',
  346. 'offset' => '',
  347. 'orderby' => '',
  348. 'order' => 'DESC',
  349. 'parent' => '',
  350. 'post_author__in' => '',
  351. 'post_author__not_in' => '',
  352. 'post_ID' => '',
  353. 'post_id' => 0,
  354. 'post__in' => '',
  355. 'post__not_in' => '',
  356. 'post_author' => '',
  357. 'post_name' => '',
  358. 'post_parent' => '',
  359. 'post_status' => '',
  360. 'post_type' => '',
  361. 'status' => 'all',
  362. 'type' => '',
  363. 'type__in' => '',
  364. 'type__not_in' => '',
  365. 'user_id' => '',
  366. 'search' => '',
  367. 'count' => false,
  368. 'meta_key' => '',
  369. 'meta_value' => '',
  370. 'meta_query' => '',
  371. 'date_query' => null, // See WP_Date_Query
  372. );
  373. $groupby = '';
  374. $this->query_vars = wp_parse_args( $query_vars, $defaults );
  375. // Parse meta query
  376. $this->meta_query = new WP_Meta_Query();
  377. $this->meta_query->parse_query_vars( $this->query_vars );
  378. /**
  379. * Fires before comments are retrieved.
  380. *
  381. * @since 3.1.0
  382. *
  383. * @param WP_Comment_Query &$this Current instance of WP_Comment_Query, passed by reference.
  384. */
  385. do_action_ref_array( 'pre_get_comments', array( &$this ) );
  386. // $args can be whatever, only use the args defined in defaults to compute the key
  387. $key = md5( serialize( wp_array_slice_assoc( $this->query_vars, array_keys( $defaults ) ) ) );
  388. $last_changed = wp_cache_get( 'last_changed', 'comment' );
  389. if ( ! $last_changed ) {
  390. $last_changed = microtime();
  391. wp_cache_set( 'last_changed', $last_changed, 'comment' );
  392. }
  393. $cache_key = "get_comments:$key:$last_changed";
  394. if ( $cache = wp_cache_get( $cache_key, 'comment' ) ) {
  395. return $cache;
  396. }
  397. $where = array();
  398. // Assemble clauses related to 'comment_approved'.
  399. $approved_clauses = array();
  400. // 'status' accepts an array or a comma-separated string.
  401. $status_clauses = array();
  402. $statuses = $this->query_vars['status'];
  403. if ( ! is_array( $statuses ) ) {
  404. $statuses = preg_split( '/[\s,]+/', $statuses );
  405. }
  406. // 'any' overrides other statuses.
  407. if ( ! in_array( 'any', $statuses ) ) {
  408. foreach ( $statuses as $status ) {
  409. switch ( $status ) {
  410. case 'hold' :
  411. $status_clauses[] = "comment_approved = '0'";
  412. break;
  413. case 'approve' :
  414. $status_clauses[] = "comment_approved = '1'";
  415. break;
  416. case 'all' :
  417. case '' :
  418. $status_clauses[] = "( comment_approved = '0' OR comment_approved = '1' )";
  419. break;
  420. default :
  421. $status_clauses[] = $wpdb->prepare( "comment_approved = %s", $status );
  422. break;
  423. }
  424. }
  425. if ( ! empty( $status_clauses ) ) {
  426. $approved_clauses[] = '( ' . implode( ' OR ', $status_clauses ) . ' )';
  427. }
  428. }
  429. // User IDs or emails whose unapproved comments are included, regardless of $status.
  430. if ( ! empty( $this->query_vars['include_unapproved'] ) ) {
  431. $include_unapproved = $this->query_vars['include_unapproved'];
  432. // Accepts arrays or comma-separated strings.
  433. if ( ! is_array( $include_unapproved ) ) {
  434. $include_unapproved = preg_split( '/[\s,]+/', $include_unapproved );
  435. }
  436. $unapproved_ids = $unapproved_emails = array();
  437. foreach ( $include_unapproved as $unapproved_identifier ) {
  438. // Numeric values are assumed to be user ids.
  439. if ( is_numeric( $unapproved_identifier ) ) {
  440. $approved_clauses[] = $wpdb->prepare( "( user_id = %d AND comment_approved = '0' )", $unapproved_identifier );
  441. // Otherwise we match against email addresses.
  442. } else {
  443. $approved_clauses[] = $wpdb->prepare( "( comment_author_email = %s AND comment_approved = '0' )", $unapproved_identifier );
  444. }
  445. }
  446. }
  447. // Collapse comment_approved clauses into a single OR-separated clause.
  448. if ( ! empty( $approved_clauses ) ) {
  449. if ( 1 === count( $approved_clauses ) ) {
  450. $where[] = $approved_clauses[0];
  451. } else {
  452. $where[] = '( ' . implode( ' OR ', $approved_clauses ) . ' )';
  453. }
  454. }
  455. $order = ( 'ASC' == strtoupper( $this->query_vars['order'] ) ) ? 'ASC' : 'DESC';
  456. // Disable ORDER BY with 'none', an empty array, or boolean false.
  457. if ( in_array( $this->query_vars['orderby'], array( 'none', array(), false ), true ) ) {
  458. $orderby = '';
  459. } else if ( ! empty( $this->query_vars['orderby'] ) ) {
  460. $ordersby = is_array( $this->query_vars['orderby'] ) ?
  461. $this->query_vars['orderby'] :
  462. preg_split( '/[,\s]/', $this->query_vars['orderby'] );
  463. $allowed_keys = array(
  464. 'comment_agent',
  465. 'comment_approved',
  466. 'comment_author',
  467. 'comment_author_email',
  468. 'comment_author_IP',
  469. 'comment_author_url',
  470. 'comment_content',
  471. 'comment_date',
  472. 'comment_date_gmt',
  473. 'comment_ID',
  474. 'comment_karma',
  475. 'comment_parent',
  476. 'comment_post_ID',
  477. 'comment_type',
  478. 'user_id',
  479. );
  480. if ( ! empty( $this->query_vars['meta_key'] ) ) {
  481. $allowed_keys[] = $this->query_vars['meta_key'];
  482. $allowed_keys[] = 'meta_value';
  483. $allowed_keys[] = 'meta_value_num';
  484. }
  485. $ordersby = array_intersect( $ordersby, $allowed_keys );
  486. foreach ( $ordersby as $key => $value ) {
  487. if ( $value == $this->query_vars['meta_key'] || $value == 'meta_value' ) {
  488. $ordersby[ $key ] = "$wpdb->commentmeta.meta_value";
  489. } elseif ( $value == 'meta_value_num' ) {
  490. $ordersby[ $key ] = "$wpdb->commentmeta.meta_value+0";
  491. }
  492. }
  493. $orderby = empty( $ordersby ) ? 'comment_date_gmt' : implode(', ', $ordersby);
  494. } else {
  495. $orderby = 'comment_date_gmt';
  496. }
  497. $number = absint( $this->query_vars['number'] );
  498. $offset = absint( $this->query_vars['offset'] );
  499. if ( ! empty( $number ) ) {
  500. if ( $offset ) {
  501. $limits = 'LIMIT ' . $offset . ',' . $number;
  502. } else {
  503. $limits = 'LIMIT ' . $number;
  504. }
  505. } else {
  506. $limits = '';
  507. }
  508. if ( $this->query_vars['count'] ) {
  509. $fields = 'COUNT(*)';
  510. } else {
  511. switch ( strtolower( $this->query_vars['fields'] ) ) {
  512. case 'ids':
  513. $fields = "$wpdb->comments.comment_ID";
  514. break;
  515. default:
  516. $fields = "*";
  517. break;
  518. }
  519. }
  520. $join = '';
  521. $post_id = absint( $this->query_vars['post_id'] );
  522. if ( ! empty( $post_id ) ) {
  523. $where[] = $wpdb->prepare( 'comment_post_ID = %d', $post_id );
  524. }
  525. // Parse comment IDs for an IN clause.
  526. if ( ! empty( $this->query_vars['comment__in'] ) ) {
  527. $where[] = 'comment_ID IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['comment__in'] ) ) . ' )';
  528. }
  529. // Parse comment IDs for a NOT IN clause.
  530. if ( ! empty( $this->query_vars['comment__not_in'] ) ) {
  531. $where[] = 'comment_ID NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['comment__not_in'] ) ) . ' )';
  532. }
  533. // Parse comment post IDs for an IN clause.
  534. if ( ! empty( $this->query_vars['post__in'] ) ) {
  535. $where[] = 'comment_post_ID IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post__in'] ) ) . ' )';
  536. }
  537. // Parse comment post IDs for a NOT IN clause.
  538. if ( ! empty( $this->query_vars['post__not_in'] ) ) {
  539. $where[] = 'comment_post_ID NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post__not_in'] ) ) . ' )';
  540. }
  541. if ( '' !== $this->query_vars['author_email'] ) {
  542. $where[] = $wpdb->prepare( 'comment_author_email = %s', $this->query_vars['author_email'] );
  543. }
  544. if ( '' !== $this->query_vars['karma'] ) {
  545. $where[] = $wpdb->prepare( 'comment_karma = %d', $this->query_vars['karma'] );
  546. }
  547. // Filtering by comment_type: 'type', 'type__in', 'type__not_in'.
  548. $raw_types = array(
  549. 'IN' => array_merge( (array) $this->query_vars['type'], (array) $this->query_vars['type__in'] ),
  550. 'NOT IN' => (array) $this->query_vars['type__not_in'],
  551. );
  552. $comment_types = array();
  553. foreach ( $raw_types as $operator => $_raw_types ) {
  554. $_raw_types = array_unique( $_raw_types );
  555. foreach ( $_raw_types as $type ) {
  556. switch ( $type ) {
  557. // An empty translates to 'all', for backward compatibility
  558. case '':
  559. case 'all' :
  560. break;
  561. case 'comment':
  562. case 'comments':
  563. $comment_types[ $operator ][] = "''";
  564. break;
  565. case 'pings':
  566. $comment_types[ $operator ][] = "'pingback'";
  567. $comment_types[ $operator ][] = "'trackback'";
  568. break;
  569. default:
  570. $comment_types[ $operator ][] = $wpdb->prepare( '%s', $type );
  571. break;
  572. }
  573. }
  574. if ( ! empty( $comment_types[ $operator ] ) ) {
  575. $types_sql = implode( ', ', $comment_types[ $operator ] );
  576. $where[] = "comment_type $operator ($types_sql)";
  577. }
  578. }
  579. if ( '' !== $this->query_vars['parent'] ) {
  580. $where[] = $wpdb->prepare( 'comment_parent = %d', $this->query_vars['parent'] );
  581. }
  582. if ( is_array( $this->query_vars['user_id'] ) ) {
  583. $where[] = 'user_id IN (' . implode( ',', array_map( 'absint', $this->query_vars['user_id'] ) ) . ')';
  584. } elseif ( '' !== $this->query_vars['user_id'] ) {
  585. $where[] = $wpdb->prepare( 'user_id = %d', $this->query_vars['user_id'] );
  586. }
  587. if ( '' !== $this->query_vars['search'] ) {
  588. $search_sql = $this->get_search_sql(
  589. $this->query_vars['search'],
  590. array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_content' )
  591. );
  592. // Strip leading 'AND'.
  593. $where[] = preg_replace( '/^\s*AND\s*/', '', $search_sql );
  594. }
  595. // If any post-related query vars are passed, join the posts table.
  596. $join_posts_table = false;
  597. $plucked = wp_array_slice_assoc( $this->query_vars, array( 'post_author', 'post_name', 'post_parent', 'post_status', 'post_type' ) );
  598. $post_fields = array_filter( $plucked );
  599. if ( ! empty( $post_fields ) ) {
  600. $join_posts_table = true;
  601. foreach ( $post_fields as $field_name => $field_value ) {
  602. $where[] = $wpdb->prepare( " {$wpdb->posts}.{$field_name} = %s", $field_value );
  603. }
  604. }
  605. // Comment author IDs for an IN clause.
  606. if ( ! empty( $this->query_vars['author__in'] ) ) {
  607. $where[] = 'user_id IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['author__in'] ) ) . ' )';
  608. }
  609. // Comment author IDs for a NOT IN clause.
  610. if ( ! empty( $this->query_vars['author__not_in'] ) ) {
  611. $where[] = 'user_id NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['author__not_in'] ) ) . ' )';
  612. }
  613. // Post author IDs for an IN clause.
  614. if ( ! empty( $this->query_vars['post_author__in'] ) ) {
  615. $join_posts_table = true;
  616. $where[] = 'post_author IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__in'] ) ) . ' )';
  617. }
  618. // Post author IDs for a NOT IN clause.
  619. if ( ! empty( $this->query_vars['post_author__not_in'] ) ) {
  620. $join_posts_table = true;
  621. $where[] = 'post_author NOT IN ( ' . implode( ',', wp_parse_id_list( $this->query_vars['post_author__not_in'] ) ) . ' )';
  622. }
  623. if ( $join_posts_table ) {
  624. $join = "JOIN $wpdb->posts ON $wpdb->posts.ID = $wpdb->comments.comment_post_ID";
  625. }
  626. if ( ! empty( $this->meta_query->queries ) ) {
  627. $clauses = $this->meta_query->get_sql( 'comment', $wpdb->comments, 'comment_ID', $this );
  628. $join .= $clauses['join'];
  629. // Strip leading 'AND'.
  630. $where[] = preg_replace( '/^\s*AND\s*/', '', $clauses['where'] );
  631. if ( ! $this->query_vars['count'] ) {
  632. $groupby = "{$wpdb->comments}.comment_ID";
  633. }
  634. }
  635. $date_query = $this->query_vars['date_query'];
  636. if ( ! empty( $date_query ) && is_array( $date_query ) ) {
  637. $date_query_object = new WP_Date_Query( $date_query, 'comment_date' );
  638. $where[] = preg_replace( '/^\s*AND\s*/', '', $date_query_object->get_sql() );
  639. }
  640. $where = implode( ' AND ', $where );
  641. $pieces = array( 'fields', 'join', 'where', 'orderby', 'order', 'limits', 'groupby' );
  642. /**
  643. * Filter the comment query clauses.
  644. *
  645. * @since 3.1.0
  646. *
  647. * @param array $pieces A compacted array of comment query clauses.
  648. * @param WP_Comment_Query &$this Current instance of WP_Comment_Query, passed by reference.
  649. */
  650. $clauses = apply_filters_ref_array( 'comments_clauses', array( compact( $pieces ), &$this ) );
  651. $fields = isset( $clauses[ 'fields' ] ) ? $clauses[ 'fields' ] : '';
  652. $join = isset( $clauses[ 'join' ] ) ? $clauses[ 'join' ] : '';
  653. $where = isset( $clauses[ 'where' ] ) ? $clauses[ 'where' ] : '';
  654. $orderby = isset( $clauses[ 'orderby' ] ) ? $clauses[ 'orderby' ] : '';
  655. $order = isset( $clauses[ 'order' ] ) ? $clauses[ 'order' ] : '';
  656. $limits = isset( $clauses[ 'limits' ] ) ? $clauses[ 'limits' ] : '';
  657. $groupby = isset( $clauses[ 'groupby' ] ) ? $clauses[ 'groupby' ] : '';
  658. if ( $where ) {
  659. $where = 'WHERE ' . $where;
  660. }
  661. if ( $groupby ) {
  662. $groupby = 'GROUP BY ' . $groupby;
  663. }
  664. if ( $orderby ) {
  665. $orderby = "ORDER BY $orderby $order";
  666. }
  667. $this->request = "SELECT $fields FROM $wpdb->comments $join $where $groupby $orderby $limits";
  668. if ( $this->query_vars['count'] ) {
  669. return $wpdb->get_var( $this->request );
  670. }
  671. if ( 'ids' == $this->query_vars['fields'] ) {
  672. $this->comments = $wpdb->get_col( $this->request );
  673. return array_map( 'intval', $this->comments );
  674. }
  675. $results = $wpdb->get_results( $this->request );
  676. /**
  677. * Filter the comment query results.
  678. *
  679. * @since 3.1.0
  680. *
  681. * @param array $results An array of comments.
  682. * @param WP_Comment_Query &$this Current instance of WP_Comment_Query, passed by reference.
  683. */
  684. $comments = apply_filters_ref_array( 'the_comments', array( $results, &$this ) );
  685. wp_cache_add( $cache_key, $comments, 'comment' );
  686. return $comments;
  687. }
  688. /**
  689. * Used internally to generate an SQL string for searching across multiple columns
  690. *
  691. * @access protected
  692. * @since 3.1.0
  693. *
  694. * @param string $string
  695. * @param array $cols
  696. * @return string
  697. */
  698. protected function get_search_sql( $string, $cols ) {
  699. global $wpdb;
  700. $like = '%' . $wpdb->esc_like( $string ) . '%';
  701. $searches = array();
  702. foreach ( $cols as $col ) {
  703. $searches[] = $wpdb->prepare( "$col LIKE %s", $like );
  704. }
  705. return ' AND (' . implode(' OR ', $searches) . ')';
  706. }
  707. }
  708. /**
  709. * Retrieve all of the WordPress supported comment statuses.
  710. *
  711. * Comments have a limited set of valid status values, this provides the comment
  712. * status values and descriptions.
  713. *
  714. * @since 2.7.0
  715. *
  716. * @return array List of comment statuses.
  717. */
  718. function get_comment_statuses() {
  719. $status = array(
  720. 'hold' => __('Unapproved'),
  721. /* translators: comment status */
  722. 'approve' => _x('Approved', 'adjective'),
  723. /* translators: comment status */
  724. 'spam' => _x('Spam', 'adjective'),
  725. );
  726. return $status;
  727. }
  728. /**
  729. * The date the last comment was modified.
  730. *
  731. * @since 1.5.0
  732. *
  733. * @global wpdb $wpdb WordPress database abstraction object.
  734. *
  735. * @param string $timezone Which timezone to use in reference to 'gmt', 'blog',
  736. * or 'server' locations.
  737. * @return string Last comment modified date.
  738. */
  739. function get_lastcommentmodified($timezone = 'server') {
  740. global $wpdb;
  741. static $cache_lastcommentmodified = array();
  742. if ( isset($cache_lastcommentmodified[$timezone]) )
  743. return $cache_lastcommentmodified[$timezone];
  744. $add_seconds_server = date('Z');
  745. switch ( strtolower($timezone)) {
  746. case 'gmt':
  747. $lastcommentmodified = $wpdb->get_var("SELECT comment_date_gmt FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
  748. break;
  749. case 'blog':
  750. $lastcommentmodified = $wpdb->get_var("SELECT comment_date FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
  751. break;
  752. case 'server':
  753. $lastcommentmodified = $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));
  754. break;
  755. }
  756. $cache_lastcommentmodified[$timezone] = $lastcommentmodified;
  757. return $lastcommentmodified;
  758. }
  759. /**
  760. * The amount of comments in a post or total comments.
  761. *
  762. * A lot like {@link wp_count_comments()}, in that they both return comment
  763. * stats (albeit with different types). The {@link wp_count_comments()} actual
  764. * caches, but this function does not.
  765. *
  766. * @since 2.0.0
  767. *
  768. * @global wpdb $wpdb WordPress database abstraction object.
  769. *
  770. * @param int $post_id Optional. Comment amount in post if > 0, else total comments blog wide.
  771. * @return array The amount of spam, approved, awaiting moderation, and total comments.
  772. */
  773. function get_comment_count( $post_id = 0 ) {
  774. global $wpdb;
  775. $post_id = (int) $post_id;
  776. $where = '';
  777. if ( $post_id > 0 ) {
  778. $where = $wpdb->prepare("WHERE comment_post_ID = %d", $post_id);
  779. }
  780. $totals = (array) $wpdb->get_results("
  781. SELECT comment_approved, COUNT( * ) AS total
  782. FROM {$wpdb->comments}
  783. {$where}
  784. GROUP BY comment_approved
  785. ", ARRAY_A);
  786. $comment_count = array(
  787. "approved" => 0,
  788. "awaiting_moderation" => 0,
  789. "spam" => 0,
  790. "total_comments" => 0
  791. );
  792. foreach ( $totals as $row ) {
  793. switch ( $row['comment_approved'] ) {
  794. case 'spam':
  795. $comment_count['spam'] = $row['total'];
  796. $comment_count["total_comments"] += $row['total'];
  797. break;
  798. case 1:
  799. $comment_count['approved'] = $row['total'];
  800. $comment_count['total_comments'] += $row['total'];
  801. break;
  802. case 0:
  803. $comment_count['awaiting_moderation'] = $row['total'];
  804. $comment_count['total_comments'] += $row['total'];
  805. break;
  806. default:
  807. break;
  808. }
  809. }
  810. return $comment_count;
  811. }
  812. //
  813. // Comment meta functions
  814. //
  815. /**
  816. * Add meta data field to a comment.
  817. *
  818. * @since 2.9.0
  819. * @link http://codex.wordpress.org/Function_Reference/add_comment_meta
  820. *
  821. * @param int $comment_id Comment ID.
  822. * @param string $meta_key Metadata name.
  823. * @param mixed $meta_value Metadata value.
  824. * @param bool $unique Optional, default is false. Whether the same key should not be added.
  825. * @return int|bool Meta ID on success, false on failure.
  826. */
  827. function add_comment_meta($comment_id, $meta_key, $meta_value, $unique = false) {
  828. return add_metadata('comment', $comment_id, $meta_key, $meta_value, $unique);
  829. }
  830. /**
  831. * Remove metadata matching criteria from a comment.
  832. *
  833. * You can match based on the key, or key and value. Removing based on key and
  834. * value, will keep from removing duplicate metadata with the same key. It also
  835. * allows removing all metadata matching key, if needed.
  836. *
  837. * @since 2.9.0
  838. * @link http://codex.wordpress.org/Function_Reference/delete_comment_meta
  839. *
  840. * @param int $comment_id comment ID
  841. * @param string $meta_key Metadata name.
  842. * @param mixed $meta_value Optional. Metadata value.
  843. * @return bool True on success, false on failure.
  844. */
  845. function delete_comment_meta($comment_id, $meta_key, $meta_value = '') {
  846. return delete_metadata('comment', $comment_id, $meta_key, $meta_value);
  847. }
  848. /**
  849. * Retrieve comment meta field for a comment.
  850. *
  851. * @since 2.9.0
  852. * @link http://codex.wordpress.org/Function_Reference/get_comment_meta
  853. *
  854. * @param int $comment_id Comment ID.
  855. * @param string $key Optional. The meta key to retrieve. By default, returns data for all keys.
  856. * @param bool $single Whether to return a single value.
  857. * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
  858. * is true.
  859. */
  860. function get_comment_meta($comment_id, $key = '', $single = false) {
  861. return get_metadata('comment', $comment_id, $key, $single);
  862. }
  863. /**
  864. * Update comment meta field based on comment ID.
  865. *
  866. * Use the $prev_value parameter to differentiate between meta fields with the
  867. * same key and comment ID.
  868. *
  869. * If the meta field for the comment does not exist, it will be added.
  870. *
  871. * @since 2.9.0
  872. * @link http://codex.wordpress.org/Function_Reference/update_comment_meta
  873. *
  874. * @param int $comment_id Comment ID.
  875. * @param string $meta_key Metadata key.
  876. * @param mixed $meta_value Metadata value.
  877. * @param mixed $prev_value Optional. Previous value to check before removing.
  878. * @return int|bool Meta ID if the key didn't exist, true on successful update, false on failure.
  879. */
  880. function update_comment_meta($comment_id, $meta_key, $meta_value, $prev_value = '') {
  881. return update_metadata('comment', $comment_id, $meta_key, $meta_value, $prev_value);
  882. }
  883. /**
  884. * Sets the cookies used to store an unauthenticated commentator's identity. Typically used
  885. * to recall previous comments by this commentator that are still held in moderation.
  886. *
  887. * @param object $comment Comment object.
  888. * @param object $user Comment author's object.
  889. *
  890. * @since 3.4.0
  891. */
  892. function wp_set_comment_cookies($comment, $user) {
  893. if ( $user->exists() )
  894. return;
  895. /**
  896. * Filter the lifetime of the comment cookie in seconds.
  897. *
  898. * @since 2.8.0
  899. *
  900. * @param int $seconds Comment cookie lifetime. Default 30000000.
  901. */
  902. $comment_cookie_lifetime = apply_filters( 'comment_cookie_lifetime', 30000000 );
  903. $secure = ( 'https' === parse_url( home_url(), PHP_URL_SCHEME ) );
  904. setcookie( 'comment_author_' . COOKIEHASH, $comment->comment_author, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure );
  905. setcookie( 'comment_author_email_' . COOKIEHASH, $comment->comment_author_email, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure );
  906. setcookie( 'comment_author_url_' . COOKIEHASH, esc_url($comment->comment_author_url), time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN, $secure );
  907. }
  908. /**
  909. * Sanitizes the cookies sent to the user already.
  910. *
  911. * Will only do anything if the cookies have already been created for the user.
  912. * Mostly used after cookies had been sent to use elsewhere.
  913. *
  914. * @since 2.0.4
  915. */
  916. function sanitize_comment_cookies() {
  917. if ( isset( $_COOKIE['comment_author_' . COOKIEHASH] ) ) {
  918. /**
  919. * Filter the comment author's name cookie before it is set.
  920. *
  921. * When this filter hook is evaluated in wp_filter_comment(),
  922. * the comment author's name string is passed.
  923. *
  924. * @since 1.5.0
  925. *
  926. * @param string $author_cookie The comment author name cookie.
  927. */
  928. $comment_author = apply_filters( 'pre_comment_author_name', $_COOKIE['comment_author_' . COOKIEHASH] );
  929. $comment_author = wp_unslash($comment_author);
  930. $comment_author = esc_attr($comment_author);
  931. $_COOKIE['comment_author_' . COOKIEHASH] = $comment_author;
  932. }
  933. if ( isset( $_COOKIE['comment_author_email_' . COOKIEHASH] ) ) {
  934. /**
  935. * Filter the comment author's email cookie before it is set.
  936. *
  937. * When this filter hook is evaluated in wp_filter_comment(),
  938. * the comment author's email string is passed.
  939. *
  940. * @since 1.5.0
  941. *
  942. * @param string $author_email_cookie The comment author email cookie.
  943. */
  944. $comment_author_email = apply_filters( 'pre_comment_author_email', $_COOKIE['comment_author_email_' . COOKIEHASH] );
  945. $comment_author_email = wp_unslash($comment_author_email);
  946. $comment_author_email = esc_attr($comment_author_email);
  947. $_COOKIE['comment_author_email_'.COOKIEHASH] = $comment_author_email;
  948. }
  949. if ( isset( $_COOKIE['comment_author_url_' . COOKIEHASH] ) ) {
  950. /**
  951. * Filter the comment author's URL cookie before it is set.
  952. *
  953. * When this filter hook is evaluated in wp_filter_comment(),
  954. * the comment author's URL string is passed.
  955. *
  956. * @since 1.5.0
  957. *
  958. * @param string $author_url_cookie The comment author URL cookie.
  959. */
  960. $comment_author_url = apply_filters( 'pre_comment_author_url', $_COOKIE['comment_author_url_' . COOKIEHASH] );
  961. $comment_author_url = wp_unslash($comment_author_url);
  962. $_COOKIE['comment_author_url_'.COOKIEHASH] = $comment_author_url;
  963. }
  964. }
  965. /**
  966. * Validates whether this comment is allowed to be made.
  967. *
  968. * @since 2.0.0
  969. *
  970. * @global wpdb $wpdb WordPress database abstraction object.
  971. *
  972. * @param array $commentdata Contains information on the comment
  973. * @return mixed Signifies the approval status (0|1|'spam')
  974. */
  975. function wp_allow_comment( $commentdata ) {
  976. global $wpdb;
  977. // Simple duplicate check
  978. // expected_slashed ($comment_post_ID, $comment_author, $comment_author_email, $comment_content)
  979. $dupe = $wpdb->prepare(
  980. "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_parent = %s AND comment_approved != 'trash' AND ( comment_author = %s ",
  981. wp_unslash( $commentdata['comment_post_ID'] ),
  982. wp_unslash( $commentdata['comment_parent'] ),
  983. wp_unslash( $commentdata['comment_author'] )
  984. );
  985. if ( $commentdata['comment_author_email'] ) {
  986. $dupe .= $wpdb->prepare(
  987. "OR comment_author_email = %s ",
  988. wp_unslash( $commentdata['comment_author_email'] )
  989. );
  990. }
  991. $dupe .= $wpdb->prepare(
  992. ") AND comment_content = %s LIMIT 1",
  993. wp_unslash( $commentdata['comment_content'] )
  994. );
  995. if ( $wpdb->get_var( $dupe ) ) {
  996. /**
  997. * Fires immediately after a duplicate comment is detected.
  998. *
  999. * @since 3.0.0
  1000. *
  1001. * @param array $commentdata Comment data.
  1002. */
  1003. do_action( 'comment_duplicate_trigger', $commentdata );
  1004. if ( defined( 'DOING_AJAX' ) ) {
  1005. die( __('Duplicate comment detected; it looks as though you&#8217;ve already said that!') );
  1006. }
  1007. wp_die( __( 'Duplicate comment detected; it looks as though you&#8217;ve already said that!' ), 409 );
  1008. }
  1009. /**
  1010. * Fires immediately before a comment is marked approved.
  1011. *
  1012. * Allows checking for comment flooding.
  1013. *
  1014. * @since 2.3.0
  1015. *
  1016. * @param string $comment_author_IP Comment author's IP address.
  1017. * @param string $comment_author_email Comment author's email.
  1018. * @param string $comment_date_gmt GMT date the comment was posted.
  1019. */
  1020. do_action(
  1021. 'check_comment_flood',
  1022. $commentdata['comment_author_IP'],
  1023. $commentdata['comment_author_email'],
  1024. $commentdata['comment_date_gmt']
  1025. );
  1026. if ( ! empty( $commentdata['user_id'] ) ) {
  1027. $user = get_userdata( $commentdata['user_id'] );
  1028. $post_author = $wpdb->get_var( $wpdb->prepare(
  1029. "SELECT post_author FROM $wpdb->posts WHERE ID = %d LIMIT 1",
  1030. $commentdata['comment_post_ID']
  1031. ) );
  1032. }
  1033. if ( isset( $user ) && ( $commentdata['user_id'] == $post_author || $user->has_cap( 'moderate_comments' ) ) ) {
  1034. // The author and the admins get respect.
  1035. $approved = 1;
  1036. } else {
  1037. // Everyone else's comments will be checked.
  1038. if ( check_comment(
  1039. $commentdata['comment_author'],
  1040. $commentdata['comment_author_email'],
  1041. $commentdata['comment_author_url'],
  1042. $commentdata['comment_content'],
  1043. $commentdata['comment_author_IP'],
  1044. $commentdata['comment_agent'],
  1045. $commentdata['comment_type']
  1046. ) ) {
  1047. $approved = 1;
  1048. } else {
  1049. $approved = 0;
  1050. }
  1051. if ( wp_blacklist_check(
  1052. $commentdata['comment_author'],
  1053. $commentdata['comment_author_email'],
  1054. $commentdata['comment_author_url'],
  1055. $commentdata['comment_content'],
  1056. $commentdata['comment_author_IP'],
  1057. $commentdata['comment_agent']
  1058. ) ) {
  1059. $approved = 'spam';
  1060. }
  1061. }
  1062. /**
  1063. * Filter a comment's approval status before it is set.
  1064. *
  1065. * @since 2.1.0
  1066. *
  1067. * @param bool|string $approved The approval status. Accepts 1, 0, or 'spam'.
  1068. * @param array $commentdata Comment data.
  1069. */
  1070. $approved = apply_filters( 'pre_comment_approved', $approved, $commentdata );
  1071. return $approved;
  1072. }
  1073. /**
  1074. * Check whether comment flooding is occurring.
  1075. *
  1076. * Won't run, if current user can manage options, so to not block
  1077. * administrators.
  1078. *
  1079. * @since 2.3.0
  1080. *
  1081. * @global wpdb $wpdb WordPress database abstraction object.
  1082. *
  1083. * @param string $ip Comment IP.
  1084. * @param string $email Comment author email address.
  1085. * @param string $date MySQL time string.
  1086. */
  1087. function check_comment_flood_db( $ip, $email, $date ) {
  1088. global $wpdb;
  1089. if ( current_user_can( 'manage_options' ) )
  1090. return; // don't throttle admins
  1091. $hour_ago = gmdate( 'Y-m-d H:i:s', time() - HOUR_IN_SECONDS );
  1092. if ( $lasttime = $wpdb->get_var( $wpdb->prepare( "SELECT `comment_date_gmt` FROM `$wpdb->comments` WHERE `comment_date_gmt` >= %s AND ( `comment_author_IP` = %s OR `comment_author_email` = %s ) ORDER BY `comment_date_gmt` DESC LIMIT 1", $hour_ago, $ip, $email ) ) ) {
  1093. $time_lastcomment = mysql2date('U', $lasttime, false);
  1094. $time_newcomment = mysql2date('U', $date, false);
  1095. /**
  1096. * Filter the comment flood status.
  1097. *
  1098. * @since 2.1.0
  1099. *
  1100. * @param bool $bool Whether a comment flood is occurring. Default false.
  1101. * @param int $time_lastcomment Timestamp of when the last comment was posted.
  1102. * @param int $time_newcomment Timestamp of when the new comment was posted.
  1103. */
  1104. $flood_die = apply_filters( 'comment_flood_filter', false, $time_lastcomment, $time_newcomment );
  1105. if ( $flood_die ) {
  1106. /**
  1107. * Fires before the comment flood message is triggered.
  1108. *
  1109. * @since 1.5.0
  1110. *
  1111. * @param int $time_lastcomment Timestamp of when the last comment was posted.
  1112. * @param int $time_newcomment Timestamp of when the new comment was posted.
  1113. */
  1114. do_action( 'comment_flood_trigger', $time_lastcomment, $time_newcomment );
  1115. if ( defined('DOING_AJAX') )
  1116. die( __('You are posting comments too quickly. Slow down.') );
  1117. wp_die( __( 'You are posting comments too quickly. Slow down.' ), 429 );
  1118. }
  1119. }
  1120. }
  1121. /**
  1122. * Separates an array of comments into an array keyed by comment_type.
  1123. *
  1124. * @since 2.7.0
  1125. *
  1126. * @param array $comments Array of comments
  1127. * @return array Array of comments keyed by comment_type.
  1128. */
  1129. function separate_comments(&$comments) {
  1130. $comments_by_type = array('comment' => array(), 'trackback' => array(), 'pingback' => array(), 'pings' => array());
  1131. $count = count($comments);
  1132. for ( $i = 0; $i < $count; $i++ ) {
  1133. $type = $comments[$i]->comment_type;
  1134. if ( empty($type) )
  1135. $type = 'comment';
  1136. $comments_by_type[$type][] = &$comments[$i];
  1137. if ( 'trackback' == $type || 'pingback' == $type )
  1138. $comments_by_type['pings'][] = &$comments[$i];
  1139. }
  1140. return $comments_by_type;
  1141. }
  1142. /**
  1143. * Calculate the total number of comment pages.
  1144. *
  1145. * @since 2.7.0
  1146. *
  1147. * @uses Walker_Comment
  1148. *
  1149. * @param array $comments Optional array of comment objects. Defaults to $wp_query->comments
  1150. * @param int $per_page Optional comments per page.
  1151. * @param boolean $threaded Optional control over flat or threaded comments.
  1152. * @return int Number of comment pages.
  1153. */
  1154. function get_comment_pages_count( $comments = null, $per_page = null, $threaded = null ) {
  1155. global $wp_query;
  1156. if ( null === $comments && null === $per_page && null === $threaded && !empty($wp_query->max_num_comment_pages) )
  1157. return $wp_query->max_num_comment_pages;
  1158. if ( ( ! $comments || ! is_array( $comments ) ) && ! empty( $wp_query->comments ) )
  1159. $comments = $wp_query->comments;
  1160. if ( empty($comments) )
  1161. return 0;
  1162. if ( ! get_option( 'page_comments' ) )
  1163. return 1;
  1164. if ( !isset($per_page) )
  1165. $per_page = (int) get_query_var('comments_per_page');
  1166. if ( 0 === $per_page )
  1167. $per_page = (int) get_option('comments_per_page');
  1168. if ( 0 === $per_page )
  1169. return 1;
  1170. if ( !isset($threaded) )
  1171. $threaded = get_option('thread_comments');
  1172. if ( $threaded ) {
  1173. $walker = new Walker_Comment;
  1174. $count = ceil( $walker->get_number_of_root_elements( $comments ) / $per_page );
  1175. } else {
  1176. $count = ceil( count( $comments ) / $per_page );
  1177. }
  1178. return $count;
  1179. }
  1180. /**
  1181. * Calculate what page number a comment will appear on for comment paging.
  1182. *
  1183. * @since 2.7.0
  1184. *
  1185. * @param int $comment_ID Comment ID.
  1186. * @param array $args Optional args.
  1187. * @return int|null Comment page number or null on error.
  1188. */
  1189. function get_page_of_comment( $comment_ID, $args = array() ) {
  1190. global $wpdb;
  1191. if ( !$comment = get_comment( $comment_ID ) )
  1192. return;
  1193. $defaults = array( 'type' => 'all', 'page' => '', 'per_page' => '', 'max_depth' => '' );
  1194. $args = wp_parse_args( $args, $defaults );
  1195. if ( '' === $args['per_page'] && get_option('page_comments') )
  1196. $args['per_page'] = get_query_var('comments_per_page');
  1197. if ( empty($args['per_page']) ) {
  1198. $args['per_page'] = 0;
  1199. $args['page'] = 0;
  1200. }
  1201. if ( $args['per_page'] < 1 )
  1202. return 1;
  1203. if ( '' === $args['max_depth'] ) {
  1204. if ( get_option('thread_comments') )
  1205. $args['max_depth'] = get_option('thread_comments_depth');
  1206. else
  1207. $args['max_depth'] = -1;
  1208. }
  1209. // Find this comment's top level parent if threading is enabled
  1210. if ( $args['max_depth'] > 1 && 0 != $comment->comment_parent )
  1211. return get_page_of_comment( $comment->comment_parent, $args );
  1212. $allowedtypes = array(
  1213. 'comment' => '',
  1214. 'pingback' => 'pingback',
  1215. 'trackback' => 'trackback',
  1216. );
  1217. $comtypewhere = ( 'all' != $args['type'] && isset($allowedtypes[$args['type']]) ) ? " AND comment_type = '" . $allowedtypes[$args['type']] . "'" : '';
  1218. // Count comments older than this one
  1219. $oldercoms = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(comment_ID) FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_parent = 0 AND comment_approved = '1' AND comment_date_gmt < '%s'" . $comtypewhere, $comment->comment_post_ID, $comment->comment_date_gmt ) );
  1220. // No older comments? Then it's page #1.
  1221. if ( 0 == $oldercoms )
  1222. return 1;
  1223. // Divide comments older than this one by comments per page to get this comment's page number
  1224. return ceil( ( $oldercoms + 1 ) / $args['per_page'] );
  1225. }
  1226. /**
  1227. * Does comment contain blacklisted characters or words.
  1228. *
  1229. * @since 1.5.0
  1230. *
  1231. * @param string $author The author of the comment
  1232. * @param string $email The email of the comment
  1233. * @param string $url The url used in the comment
  1234. * @param string $comment The comment content
  1235. * @param string $user_ip The comment author IP address
  1236. * @param string $user_agent The author's browser user agent
  1237. * @return bool True if comment contains blacklisted content, false if comment does not
  1238. */
  1239. function wp_blacklist_check($author, $email, $url, $comment, $user_ip, $user_agent) {
  1240. /**
  1241. * Fires before the comment is tested for blacklisted characters or words.
  1242. *
  1243. * @since 1.5.0
  1244. *
  1245. * @param string $author Comment author.
  1246. * @param string $email Comment author's email.
  1247. * @param string $url Comment author's URL.
  1248. * @param string $comment Comment content.
  1249. * @param string $user_ip Comment author's IP address.
  1250. * @param string $user_agent Comment author's browser user agent.
  1251. */
  1252. do_action( 'wp_blacklist_check', $author, $email, $url, $comment, $user_ip, $user_agent );
  1253. $mod_keys = trim( get_option('blacklist_keys') );
  1254. if ( '' == $mod_keys )
  1255. return false; // If moderation keys are empty
  1256. $words = explode("\n", $mod_keys );
  1257. foreach ( (array) $words as $word ) {
  1258. $word = trim($word);
  1259. // Skip empty lines
  1260. if ( empty($word) ) { continue; }
  1261. // Do some escaping magic so that '#' chars in the
  1262. // spam words don't break things:
  1263. $word = preg_quote($word, '#');
  1264. $pattern = "#$word#i";
  1265. if (
  1266. preg_match($pattern, $author)
  1267. || preg_match($pattern, $email)
  1268. || preg_match($pattern, $url)
  1269. || preg_match($pattern, $comment)
  1270. || preg_match($pattern, $user_ip)
  1271. || preg_match($pattern, $user_agent)
  1272. )
  1273. return true;
  1274. }
  1275. return false;
  1276. }
  1277. /**
  1278. * Retrieve total comments for blog or single post.
  1279. *
  1280. * The properties of the returned object contain the 'moderated', 'approved',
  1281. * and spam comments for either the entire blog or single post. Those properties
  1282. * contain the amount of comments that match the status. The 'total_comments'
  1283. * property contains the integer of total comments.
  1284. *
  1285. * The comment stats are cached and then retrieved, if they already exist in the
  1286. * cache.
  1287. *
  1288. * @since 2.5.0
  1289. *
  1290. * @param int $post_id Optional. Post ID.
  1291. * @return object Comment stats.
  1292. */
  1293. function wp_count_comments( $post_id = 0 ) {
  1294. global $wpdb;
  1295. $post_id = (int) $post_id;
  1296. /**
  1297. * Filter the comments count for a given post.
  1298. *
  1299. * @since 2.7.0
  1300. *

Large files files are truncated, but you can click here to view the full file