PageRenderTime 66ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/comment.php

https://github.com/eMicroGraph/choices
PHP | 2456 lines | 1053 code | 291 blank | 1112 comment | 279 complexity | a25173b54eed2eeb1649d123422d5093 MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0
  1. <?php
  2. /**
  3. * Manages WordPress comments
  4. *
  5. * @package WordPress
  6. * @subpackage Comment
  7. */
  8. /**
  9. * Checks whether a comment passes internal checks to be allowed to add.
  10. *
  11. * If comment moderation is set in the administration, then all comments,
  12. * regardless of their type and whitelist will be set to false. If the number of
  13. * links exceeds the amount in the administration, then the check fails. If any
  14. * of the parameter contents match the blacklist of words, then the check fails.
  15. *
  16. * If the number of links exceeds the amount in the administration, then the
  17. * check fails. If any of the parameter contents match the blacklist of words,
  18. * then the check fails.
  19. *
  20. * If the comment author was approved before, then the comment is
  21. * automatically whitelisted.
  22. *
  23. * If none of the checks fail, then the failback is to set the check to pass
  24. * (return true).
  25. *
  26. * @since 1.2.0
  27. * @uses $wpdb
  28. *
  29. * @param string $author Comment Author's name
  30. * @param string $email Comment Author's email
  31. * @param string $url Comment Author's URL
  32. * @param string $comment Comment contents
  33. * @param string $user_ip Comment Author's IP address
  34. * @param string $user_agent Comment Author's User Agent
  35. * @param string $comment_type Comment type, either user submitted comment,
  36. * trackback, or pingback
  37. * @return bool Whether the checks passed (true) and the comments should be
  38. * displayed or set to moderated
  39. */
  40. function check_comment($author, $email, $url, $comment, $user_ip, $user_agent, $comment_type) {
  41. global $wpdb;
  42. if ( 1 == get_option('comment_moderation') )
  43. return false; // If moderation is set to manual
  44. /** This filter is documented in wp-includes/comment-template.php */
  45. $comment = apply_filters( 'comment_text', $comment );
  46. // Check # of external links
  47. if ( $max_links = get_option( 'comment_max_links' ) ) {
  48. $num_links = preg_match_all( '/<a [^>]*href/i', $comment, $out );
  49. /**
  50. * Filter the maximum number of links allowed in a comment.
  51. *
  52. * @since 3.0.0
  53. *
  54. * @param int $num_links The number of links allowed.
  55. * @param string $url Comment author's URL. Included in allowed links total.
  56. */
  57. $num_links = apply_filters( 'comment_max_links_url', $num_links, $url );
  58. if ( $num_links >= $max_links )
  59. return false;
  60. }
  61. $mod_keys = trim(get_option('moderation_keys'));
  62. if ( !empty($mod_keys) ) {
  63. $words = explode("\n", $mod_keys );
  64. foreach ( (array) $words as $word) {
  65. $word = trim($word);
  66. // Skip empty lines
  67. if ( empty($word) )
  68. continue;
  69. // Do some escaping magic so that '#' chars in the
  70. // spam words don't break things:
  71. $word = preg_quote($word, '#');
  72. $pattern = "#$word#i";
  73. if ( preg_match($pattern, $author) ) return false;
  74. if ( preg_match($pattern, $email) ) return false;
  75. if ( preg_match($pattern, $url) ) return false;
  76. if ( preg_match($pattern, $comment) ) return false;
  77. if ( preg_match($pattern, $user_ip) ) return false;
  78. if ( preg_match($pattern, $user_agent) ) return false;
  79. }
  80. }
  81. // Comment whitelisting:
  82. if ( 1 == get_option('comment_whitelist')) {
  83. if ( 'trackback' != $comment_type && 'pingback' != $comment_type && $author != '' && $email != '' ) {
  84. // expected_slashed ($author, $email)
  85. $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");
  86. if ( ( 1 == $ok_to_comment ) &&
  87. ( empty($mod_keys) || false === strpos( $email, $mod_keys) ) )
  88. return true;
  89. else
  90. return false;
  91. } else {
  92. return false;
  93. }
  94. }
  95. return true;
  96. }
  97. /**
  98. * Retrieve the approved comments for post $post_id.
  99. *
  100. * @since 2.0.0
  101. * @uses $wpdb
  102. *
  103. * @param int $post_id The ID of the post
  104. * @return array $comments The approved comments
  105. */
  106. function get_approved_comments($post_id) {
  107. global $wpdb;
  108. return $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved = '1' ORDER BY comment_date", $post_id));
  109. }
  110. /**
  111. * Retrieves comment data given a comment ID or comment object.
  112. *
  113. * If an object is passed then the comment data will be cached and then returned
  114. * after being passed through a filter. If the comment is empty, then the global
  115. * comment variable will be used, if it is set.
  116. *
  117. * @since 2.0.0
  118. * @uses $wpdb
  119. *
  120. * @param object|string|int $comment Comment to retrieve.
  121. * @param string $output Optional. OBJECT or ARRAY_A or ARRAY_N constants.
  122. * @return object|array|null Depends on $output value.
  123. */
  124. function get_comment(&$comment, $output = OBJECT) {
  125. global $wpdb;
  126. if ( empty($comment) ) {
  127. if ( isset($GLOBALS['comment']) )
  128. $_comment = & $GLOBALS['comment'];
  129. else
  130. $_comment = null;
  131. } elseif ( is_object($comment) ) {
  132. wp_cache_add($comment->comment_ID, $comment, 'comment');
  133. $_comment = $comment;
  134. } else {
  135. if ( isset($GLOBALS['comment']) && ($GLOBALS['comment']->comment_ID == $comment) ) {
  136. $_comment = & $GLOBALS['comment'];
  137. } elseif ( ! $_comment = wp_cache_get($comment, 'comment') ) {
  138. $_comment = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_ID = %d LIMIT 1", $comment));
  139. if ( ! $_comment )
  140. return null;
  141. wp_cache_add($_comment->comment_ID, $_comment, 'comment');
  142. }
  143. }
  144. /**
  145. * Fires after a comment is retrieved.
  146. *
  147. * @since 2.3.0
  148. *
  149. * @param mixed $_comment Comment data.
  150. */
  151. $_comment = apply_filters( 'get_comment', $_comment );
  152. if ( $output == OBJECT ) {
  153. return $_comment;
  154. } elseif ( $output == ARRAY_A ) {
  155. $__comment = get_object_vars($_comment);
  156. return $__comment;
  157. } elseif ( $output == ARRAY_N ) {
  158. $__comment = array_values(get_object_vars($_comment));
  159. return $__comment;
  160. } else {
  161. return $_comment;
  162. }
  163. }
  164. /**
  165. * Retrieve a list of comments.
  166. *
  167. * The comment list can be for the blog as a whole or for an individual post.
  168. *
  169. * The list of comment arguments are 'status', 'orderby', 'comment_date_gmt',
  170. * 'order', 'number', 'offset', and 'post_id'.
  171. *
  172. * @since 2.7.0
  173. * @uses $wpdb
  174. *
  175. * @param mixed $args Optional. Array or string of options to override defaults.
  176. * @return array List of comments.
  177. */
  178. function get_comments( $args = '' ) {
  179. $query = new WP_Comment_Query;
  180. return $query->query( $args );
  181. }
  182. /**
  183. * WordPress Comment Query class.
  184. *
  185. * @since 3.1.0
  186. */
  187. class WP_Comment_Query {
  188. /**
  189. * Metadata query container
  190. *
  191. * @since 3.5.0
  192. * @access public
  193. * @var object WP_Meta_Query
  194. */
  195. var $meta_query = false;
  196. /**
  197. * Date query container
  198. *
  199. * @since 3.7.0
  200. * @access public
  201. * @var object WP_Date_Query
  202. */
  203. var $date_query = false;
  204. /**
  205. * Execute the query
  206. *
  207. * @since 3.1.0
  208. *
  209. * @param string|array $query_vars
  210. * @return int|array
  211. */
  212. function query( $query_vars ) {
  213. global $wpdb;
  214. $defaults = array(
  215. 'author_email' => '',
  216. 'ID' => '',
  217. 'karma' => '',
  218. 'number' => '',
  219. 'offset' => '',
  220. 'orderby' => '',
  221. 'order' => 'DESC',
  222. 'parent' => '',
  223. 'post_ID' => '',
  224. 'post_id' => 0,
  225. 'post_author' => '',
  226. 'post_name' => '',
  227. 'post_parent' => '',
  228. 'post_status' => '',
  229. 'post_type' => '',
  230. 'status' => '',
  231. 'type' => '',
  232. 'user_id' => '',
  233. 'search' => '',
  234. 'count' => false,
  235. 'meta_key' => '',
  236. 'meta_value' => '',
  237. 'meta_query' => '',
  238. 'date_query' => null, // See WP_Date_Query
  239. );
  240. $groupby = '';
  241. $this->query_vars = wp_parse_args( $query_vars, $defaults );
  242. // Parse meta query
  243. $this->meta_query = new WP_Meta_Query();
  244. $this->meta_query->parse_query_vars( $this->query_vars );
  245. /**
  246. * Fires before comments are retrieved.
  247. *
  248. * @since 3.1.0
  249. *
  250. * @param WP_Comment_Query &$this Current instance of WP_Comment_Query, passed by reference.
  251. */
  252. do_action_ref_array( 'pre_get_comments', array( &$this ) );
  253. extract( $this->query_vars, EXTR_SKIP );
  254. // $args can be whatever, only use the args defined in defaults to compute the key
  255. $key = md5( serialize( compact(array_keys($defaults)) ) );
  256. $last_changed = wp_cache_get( 'last_changed', 'comment' );
  257. if ( ! $last_changed ) {
  258. $last_changed = microtime();
  259. wp_cache_set( 'last_changed', $last_changed, 'comment' );
  260. }
  261. $cache_key = "get_comments:$key:$last_changed";
  262. if ( $cache = wp_cache_get( $cache_key, 'comment' ) )
  263. return $cache;
  264. $post_id = absint($post_id);
  265. if ( 'hold' == $status )
  266. $approved = "comment_approved = '0'";
  267. elseif ( 'approve' == $status )
  268. $approved = "comment_approved = '1'";
  269. elseif ( ! empty( $status ) && 'all' != $status )
  270. $approved = $wpdb->prepare( "comment_approved = %s", $status );
  271. else
  272. $approved = "( comment_approved = '0' OR comment_approved = '1' )";
  273. $order = ( 'ASC' == strtoupper($order) ) ? 'ASC' : 'DESC';
  274. if ( ! empty( $orderby ) ) {
  275. $ordersby = is_array($orderby) ? $orderby : preg_split('/[,\s]/', $orderby);
  276. $allowed_keys = array(
  277. 'comment_agent',
  278. 'comment_approved',
  279. 'comment_author',
  280. 'comment_author_email',
  281. 'comment_author_IP',
  282. 'comment_author_url',
  283. 'comment_content',
  284. 'comment_date',
  285. 'comment_date_gmt',
  286. 'comment_ID',
  287. 'comment_karma',
  288. 'comment_parent',
  289. 'comment_post_ID',
  290. 'comment_type',
  291. 'user_id',
  292. );
  293. if ( ! empty( $this->query_vars['meta_key'] ) ) {
  294. $allowed_keys[] = $this->query_vars['meta_key'];
  295. $allowed_keys[] = 'meta_value';
  296. $allowed_keys[] = 'meta_value_num';
  297. }
  298. $ordersby = array_intersect( $ordersby, $allowed_keys );
  299. foreach ( $ordersby as $key => $value ) {
  300. if ( $value == $this->query_vars['meta_key'] || $value == 'meta_value' ) {
  301. $ordersby[ $key ] = "$wpdb->commentmeta.meta_value";
  302. } elseif ( $value == 'meta_value_num' ) {
  303. $ordersby[ $key ] = "$wpdb->commentmeta.meta_value+0";
  304. }
  305. }
  306. $orderby = empty( $ordersby ) ? 'comment_date_gmt' : implode(', ', $ordersby);
  307. } else {
  308. $orderby = 'comment_date_gmt';
  309. }
  310. $number = absint($number);
  311. $offset = absint($offset);
  312. if ( !empty($number) ) {
  313. if ( $offset )
  314. $limits = 'LIMIT ' . $offset . ',' . $number;
  315. else
  316. $limits = 'LIMIT ' . $number;
  317. } else {
  318. $limits = '';
  319. }
  320. if ( $count )
  321. $fields = 'COUNT(*)';
  322. else
  323. $fields = '*';
  324. $join = '';
  325. $where = $approved;
  326. if ( ! empty($post_id) )
  327. $where .= $wpdb->prepare( ' AND comment_post_ID = %d', $post_id );
  328. if ( '' !== $author_email )
  329. $where .= $wpdb->prepare( ' AND comment_author_email = %s', $author_email );
  330. if ( '' !== $karma )
  331. $where .= $wpdb->prepare( ' AND comment_karma = %d', $karma );
  332. if ( 'comment' == $type ) {
  333. $where .= " AND comment_type = ''";
  334. } elseif( 'pings' == $type ) {
  335. $where .= ' AND comment_type IN ("pingback", "trackback")';
  336. } elseif ( ! empty( $type ) ) {
  337. $where .= $wpdb->prepare( ' AND comment_type = %s', $type );
  338. }
  339. if ( '' !== $parent )
  340. $where .= $wpdb->prepare( ' AND comment_parent = %d', $parent );
  341. if ( is_array( $user_id ) ) {
  342. $where .= ' AND user_id IN (' . implode( ',', array_map( 'absint', $user_id ) ) . ')';
  343. } elseif ( '' !== $user_id ) {
  344. $where .= $wpdb->prepare( ' AND user_id = %d', $user_id );
  345. }
  346. if ( '' !== $search )
  347. $where .= $this->get_search_sql( $search, array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_content' ) );
  348. $post_fields = array_filter( compact( array( 'post_author', 'post_name', 'post_parent', 'post_status', 'post_type', ) ) );
  349. if ( ! empty( $post_fields ) ) {
  350. $join = "JOIN $wpdb->posts ON $wpdb->posts.ID = $wpdb->comments.comment_post_ID";
  351. foreach( $post_fields as $field_name => $field_value )
  352. $where .= $wpdb->prepare( " AND {$wpdb->posts}.{$field_name} = %s", $field_value );
  353. }
  354. if ( ! empty( $this->meta_query->queries ) ) {
  355. $clauses = $this->meta_query->get_sql( 'comment', $wpdb->comments, 'comment_ID', $this );
  356. $join .= $clauses['join'];
  357. $where .= $clauses['where'];
  358. $groupby = "{$wpdb->comments}.comment_ID";
  359. }
  360. if ( ! empty( $date_query ) && is_array( $date_query ) ) {
  361. $date_query_object = new WP_Date_Query( $date_query, 'comment_date' );
  362. $where .= $date_query_object->get_sql();
  363. }
  364. $pieces = array( 'fields', 'join', 'where', 'orderby', 'order', 'limits', 'groupby' );
  365. /**
  366. * Filter the comment query clauses.
  367. *
  368. * @since 3.1.0
  369. *
  370. * @param array $pieces A compacted array of comment query clauses.
  371. * @param WP_Comment_Query &$this Current instance of WP_Comment_Query, passed by reference.
  372. */
  373. $clauses = apply_filters_ref_array( 'comments_clauses', array( compact( $pieces ), &$this ) );
  374. foreach ( $pieces as $piece )
  375. $$piece = isset( $clauses[ $piece ] ) ? $clauses[ $piece ] : '';
  376. if ( $groupby )
  377. $groupby = 'GROUP BY ' . $groupby;
  378. $query = "SELECT $fields FROM $wpdb->comments $join WHERE $where $groupby ORDER BY $orderby $order $limits";
  379. if ( $count )
  380. return $wpdb->get_var( $query );
  381. $comments = $wpdb->get_results( $query );
  382. /**
  383. * Filter the comment query results.
  384. *
  385. * @since 3.1.0
  386. *
  387. * @param array $comments An array of comments.
  388. * @param WP_Comment_Query &$this Current instance of WP_Comment_Query, passed by reference.
  389. */
  390. $comments = apply_filters_ref_array( 'the_comments', array( $comments, &$this ) );
  391. wp_cache_add( $cache_key, $comments, 'comment' );
  392. return $comments;
  393. }
  394. /**
  395. * Used internally to generate an SQL string for searching across multiple columns
  396. *
  397. * @access protected
  398. * @since 3.1.0
  399. *
  400. * @param string $string
  401. * @param array $cols
  402. * @return string
  403. */
  404. function get_search_sql( $string, $cols ) {
  405. $string = esc_sql( like_escape( $string ) );
  406. $searches = array();
  407. foreach ( $cols as $col )
  408. $searches[] = "$col LIKE '%$string%'";
  409. return ' AND (' . implode(' OR ', $searches) . ')';
  410. }
  411. }
  412. /**
  413. * Retrieve all of the WordPress supported comment statuses.
  414. *
  415. * Comments have a limited set of valid status values, this provides the comment
  416. * status values and descriptions.
  417. *
  418. * @since 2.7.0
  419. *
  420. * @return array List of comment statuses.
  421. */
  422. function get_comment_statuses() {
  423. $status = array(
  424. 'hold' => __('Unapproved'),
  425. /* translators: comment status */
  426. 'approve' => _x('Approved', 'adjective'),
  427. /* translators: comment status */
  428. 'spam' => _x('Spam', 'adjective'),
  429. );
  430. return $status;
  431. }
  432. /**
  433. * The date the last comment was modified.
  434. *
  435. * @since 1.5.0
  436. * @uses $wpdb
  437. *
  438. * @param string $timezone Which timezone to use in reference to 'gmt', 'blog',
  439. * or 'server' locations.
  440. * @return string Last comment modified date.
  441. */
  442. function get_lastcommentmodified($timezone = 'server') {
  443. global $wpdb;
  444. static $cache_lastcommentmodified = array();
  445. if ( isset($cache_lastcommentmodified[$timezone]) )
  446. return $cache_lastcommentmodified[$timezone];
  447. $add_seconds_server = date('Z');
  448. switch ( strtolower($timezone)) {
  449. case 'gmt':
  450. $lastcommentmodified = $wpdb->get_var("SELECT comment_date_gmt FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
  451. break;
  452. case 'blog':
  453. $lastcommentmodified = $wpdb->get_var("SELECT comment_date FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
  454. break;
  455. case 'server':
  456. $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));
  457. break;
  458. }
  459. $cache_lastcommentmodified[$timezone] = $lastcommentmodified;
  460. return $lastcommentmodified;
  461. }
  462. /**
  463. * The amount of comments in a post or total comments.
  464. *
  465. * A lot like {@link wp_count_comments()}, in that they both return comment
  466. * stats (albeit with different types). The {@link wp_count_comments()} actual
  467. * caches, but this function does not.
  468. *
  469. * @since 2.0.0
  470. * @uses $wpdb
  471. *
  472. * @param int $post_id Optional. Comment amount in post if > 0, else total comments blog wide.
  473. * @return array The amount of spam, approved, awaiting moderation, and total comments.
  474. */
  475. function get_comment_count( $post_id = 0 ) {
  476. global $wpdb;
  477. $post_id = (int) $post_id;
  478. $where = '';
  479. if ( $post_id > 0 ) {
  480. $where = $wpdb->prepare("WHERE comment_post_ID = %d", $post_id);
  481. }
  482. $totals = (array) $wpdb->get_results("
  483. SELECT comment_approved, COUNT( * ) AS total
  484. FROM {$wpdb->comments}
  485. {$where}
  486. GROUP BY comment_approved
  487. ", ARRAY_A);
  488. $comment_count = array(
  489. "approved" => 0,
  490. "awaiting_moderation" => 0,
  491. "spam" => 0,
  492. "total_comments" => 0
  493. );
  494. foreach ( $totals as $row ) {
  495. switch ( $row['comment_approved'] ) {
  496. case 'spam':
  497. $comment_count['spam'] = $row['total'];
  498. $comment_count["total_comments"] += $row['total'];
  499. break;
  500. case 1:
  501. $comment_count['approved'] = $row['total'];
  502. $comment_count['total_comments'] += $row['total'];
  503. break;
  504. case 0:
  505. $comment_count['awaiting_moderation'] = $row['total'];
  506. $comment_count['total_comments'] += $row['total'];
  507. break;
  508. default:
  509. break;
  510. }
  511. }
  512. return $comment_count;
  513. }
  514. //
  515. // Comment meta functions
  516. //
  517. /**
  518. * Add meta data field to a comment.
  519. *
  520. * @since 2.9.0
  521. * @uses add_metadata
  522. * @link http://codex.wordpress.org/Function_Reference/add_comment_meta
  523. *
  524. * @param int $comment_id Comment ID.
  525. * @param string $meta_key Metadata name.
  526. * @param mixed $meta_value Metadata value.
  527. * @param bool $unique Optional, default is false. Whether the same key should not be added.
  528. * @return int|bool Meta ID on success, false on failure.
  529. */
  530. function add_comment_meta($comment_id, $meta_key, $meta_value, $unique = false) {
  531. return add_metadata('comment', $comment_id, $meta_key, $meta_value, $unique);
  532. }
  533. /**
  534. * Remove metadata matching criteria from a comment.
  535. *
  536. * You can match based on the key, or key and value. Removing based on key and
  537. * value, will keep from removing duplicate metadata with the same key. It also
  538. * allows removing all metadata matching key, if needed.
  539. *
  540. * @since 2.9.0
  541. * @uses delete_metadata
  542. * @link http://codex.wordpress.org/Function_Reference/delete_comment_meta
  543. *
  544. * @param int $comment_id comment ID
  545. * @param string $meta_key Metadata name.
  546. * @param mixed $meta_value Optional. Metadata value.
  547. * @return bool True on success, false on failure.
  548. */
  549. function delete_comment_meta($comment_id, $meta_key, $meta_value = '') {
  550. return delete_metadata('comment', $comment_id, $meta_key, $meta_value);
  551. }
  552. /**
  553. * Retrieve comment meta field for a comment.
  554. *
  555. * @since 2.9.0
  556. * @uses get_metadata
  557. * @link http://codex.wordpress.org/Function_Reference/get_comment_meta
  558. *
  559. * @param int $comment_id Comment ID.
  560. * @param string $key Optional. The meta key to retrieve. By default, returns data for all keys.
  561. * @param bool $single Whether to return a single value.
  562. * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
  563. * is true.
  564. */
  565. function get_comment_meta($comment_id, $key = '', $single = false) {
  566. return get_metadata('comment', $comment_id, $key, $single);
  567. }
  568. /**
  569. * Update comment meta field based on comment ID.
  570. *
  571. * Use the $prev_value parameter to differentiate between meta fields with the
  572. * same key and comment ID.
  573. *
  574. * If the meta field for the comment does not exist, it will be added.
  575. *
  576. * @since 2.9.0
  577. * @uses update_metadata
  578. * @link http://codex.wordpress.org/Function_Reference/update_comment_meta
  579. *
  580. * @param int $comment_id Comment ID.
  581. * @param string $meta_key Metadata key.
  582. * @param mixed $meta_value Metadata value.
  583. * @param mixed $prev_value Optional. Previous value to check before removing.
  584. * @return int|bool Meta ID if the key didn't exist, true on successful update, false on failure.
  585. */
  586. function update_comment_meta($comment_id, $meta_key, $meta_value, $prev_value = '') {
  587. return update_metadata('comment', $comment_id, $meta_key, $meta_value, $prev_value);
  588. }
  589. /**
  590. * Sets the cookies used to store an unauthenticated commentator's identity. Typically used
  591. * to recall previous comments by this commentator that are still held in moderation.
  592. *
  593. * @param object $comment Comment object.
  594. * @param object $user Comment author's object.
  595. *
  596. * @since 3.4.0
  597. */
  598. function wp_set_comment_cookies($comment, $user) {
  599. if ( $user->exists() )
  600. return;
  601. /**
  602. * Filter the lifetime of the comment cookie in seconds.
  603. *
  604. * @since 2.8.0
  605. *
  606. * @param int $seconds Comment cookie lifetime. Default 30000000.
  607. */
  608. $comment_cookie_lifetime = apply_filters( 'comment_cookie_lifetime', 30000000 );
  609. setcookie('comment_author_' . COOKIEHASH, $comment->comment_author, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN);
  610. setcookie('comment_author_email_' . COOKIEHASH, $comment->comment_author_email, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN);
  611. setcookie('comment_author_url_' . COOKIEHASH, esc_url($comment->comment_author_url), time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN);
  612. }
  613. /**
  614. * Sanitizes the cookies sent to the user already.
  615. *
  616. * Will only do anything if the cookies have already been created for the user.
  617. * Mostly used after cookies had been sent to use elsewhere.
  618. *
  619. * @since 2.0.4
  620. */
  621. function sanitize_comment_cookies() {
  622. if ( isset( $_COOKIE['comment_author_' . COOKIEHASH] ) ) {
  623. /**
  624. * Filter the comment author's name cookie before it is set.
  625. *
  626. * When this filter hook is evaluated in wp_filter_comment(),
  627. * the comment author's name string is passed.
  628. *
  629. * @since 1.5.0
  630. *
  631. * @param string $author_cookie The comment author name cookie.
  632. */
  633. $comment_author = apply_filters( 'pre_comment_author_name', $_COOKIE['comment_author_' . COOKIEHASH] );
  634. $comment_author = wp_unslash($comment_author);
  635. $comment_author = esc_attr($comment_author);
  636. $_COOKIE['comment_author_' . COOKIEHASH] = $comment_author;
  637. }
  638. if ( isset( $_COOKIE['comment_author_email_' . COOKIEHASH] ) ) {
  639. /**
  640. * Filter the comment author's email cookie before it is set.
  641. *
  642. * When this filter hook is evaluated in wp_filter_comment(),
  643. * the comment author's email string is passed.
  644. *
  645. * @since 1.5.0
  646. *
  647. * @param string $author_email_cookie The comment author email cookie.
  648. */
  649. $comment_author_email = apply_filters( 'pre_comment_author_email', $_COOKIE['comment_author_email_' . COOKIEHASH] );
  650. $comment_author_email = wp_unslash($comment_author_email);
  651. $comment_author_email = esc_attr($comment_author_email);
  652. $_COOKIE['comment_author_email_'.COOKIEHASH] = $comment_author_email;
  653. }
  654. if ( isset( $_COOKIE['comment_author_url_' . COOKIEHASH] ) ) {
  655. /**
  656. * Filter the comment author's URL cookie before it is set.
  657. *
  658. * When this filter hook is evaluated in wp_filter_comment(),
  659. * the comment author's URL string is passed.
  660. *
  661. * @since 1.5.0
  662. *
  663. * @param string $author_url_cookie The comment author URL cookie.
  664. */
  665. $comment_author_url = apply_filters( 'pre_comment_author_url', $_COOKIE['comment_author_url_' . COOKIEHASH] );
  666. $comment_author_url = wp_unslash($comment_author_url);
  667. $_COOKIE['comment_author_url_'.COOKIEHASH] = $comment_author_url;
  668. }
  669. }
  670. /**
  671. * Validates whether this comment is allowed to be made.
  672. *
  673. * @since 2.0.0
  674. * @uses $wpdb
  675. *
  676. * @param array $commentdata Contains information on the comment
  677. * @return mixed Signifies the approval status (0|1|'spam')
  678. */
  679. function wp_allow_comment($commentdata) {
  680. global $wpdb;
  681. extract($commentdata, EXTR_SKIP);
  682. // Simple duplicate check
  683. // expected_slashed ($comment_post_ID, $comment_author, $comment_author_email, $comment_content)
  684. $dupe = $wpdb->prepare( "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_parent = %s AND comment_approved != 'trash' AND ( comment_author = %s ", wp_unslash( $comment_post_ID ), wp_unslash( $comment_parent ), wp_unslash( $comment_author ) );
  685. if ( $comment_author_email )
  686. $dupe .= $wpdb->prepare( "OR comment_author_email = %s ", wp_unslash( $comment_author_email ) );
  687. $dupe .= $wpdb->prepare( ") AND comment_content = %s LIMIT 1", wp_unslash( $comment_content ) );
  688. if ( $wpdb->get_var($dupe) ) {
  689. /**
  690. * Fires immediately after a duplicate comment is detected.
  691. *
  692. * @since 3.0.0
  693. *
  694. * @param array $commentdata Comment data.
  695. */
  696. do_action( 'comment_duplicate_trigger', $commentdata );
  697. if ( defined('DOING_AJAX') )
  698. die( __('Duplicate comment detected; it looks as though you&#8217;ve already said that!') );
  699. wp_die( __('Duplicate comment detected; it looks as though you&#8217;ve already said that!') );
  700. }
  701. /**
  702. * Fires immediately before a comment is marked approved.
  703. *
  704. * Allows checking for comment flooding.
  705. *
  706. * @since 2.3.0
  707. *
  708. * @param string $comment_author_IP Comment author's IP address.
  709. * @param string $comment_author_email Comment author's email.
  710. * @param string $comment_date_gmt GMT date the comment was posted.
  711. */
  712. do_action( 'check_comment_flood', $comment_author_IP, $comment_author_email, $comment_date_gmt );
  713. if ( ! empty( $user_id ) ) {
  714. $user = get_userdata( $user_id );
  715. $post_author = $wpdb->get_var($wpdb->prepare("SELECT post_author FROM $wpdb->posts WHERE ID = %d LIMIT 1", $comment_post_ID));
  716. }
  717. if ( isset( $user ) && ( $user_id == $post_author || $user->has_cap( 'moderate_comments' ) ) ) {
  718. // The author and the admins get respect.
  719. $approved = 1;
  720. } else {
  721. // Everyone else's comments will be checked.
  722. if ( check_comment($comment_author, $comment_author_email, $comment_author_url, $comment_content, $comment_author_IP, $comment_agent, $comment_type) )
  723. $approved = 1;
  724. else
  725. $approved = 0;
  726. if ( wp_blacklist_check($comment_author, $comment_author_email, $comment_author_url, $comment_content, $comment_author_IP, $comment_agent) )
  727. $approved = 'spam';
  728. }
  729. /**
  730. * Filter a comment's approval status before it is set.
  731. *
  732. * @since 2.1.0
  733. *
  734. * @param bool|string $approved The approval status. Accepts 1, 0, or 'spam'.
  735. * @param array $commentdata Comment data.
  736. */
  737. $approved = apply_filters( 'pre_comment_approved', $approved, $commentdata );
  738. return $approved;
  739. }
  740. /**
  741. * Check whether comment flooding is occurring.
  742. *
  743. * Won't run, if current user can manage options, so to not block
  744. * administrators.
  745. *
  746. * @since 2.3.0
  747. * @uses $wpdb
  748. *
  749. * @param string $ip Comment IP.
  750. * @param string $email Comment author email address.
  751. * @param string $date MySQL time string.
  752. */
  753. function check_comment_flood_db( $ip, $email, $date ) {
  754. global $wpdb;
  755. if ( current_user_can( 'manage_options' ) )
  756. return; // don't throttle admins
  757. $hour_ago = gmdate( 'Y-m-d H:i:s', time() - HOUR_IN_SECONDS );
  758. 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 ) ) ) {
  759. $time_lastcomment = mysql2date('U', $lasttime, false);
  760. $time_newcomment = mysql2date('U', $date, false);
  761. /**
  762. * Filter the comment flood status.
  763. *
  764. * @since 2.1.0
  765. *
  766. * @param bool $bool Whether a comment flood is occurring. Default false.
  767. * @param int $time_lastcomment Timestamp of when the last comment was posted.
  768. * @param int $time_newcomment Timestamp of when the new comment was posted.
  769. */
  770. $flood_die = apply_filters( 'comment_flood_filter', false, $time_lastcomment, $time_newcomment );
  771. if ( $flood_die ) {
  772. /**
  773. * Fires before the comment flood message is triggered.
  774. *
  775. * @since 1.5.0
  776. *
  777. * @param int $time_lastcomment Timestamp of when the last comment was posted.
  778. * @param int $time_newcomment Timestamp of when the new comment was posted.
  779. */
  780. do_action( 'comment_flood_trigger', $time_lastcomment, $time_newcomment );
  781. if ( defined('DOING_AJAX') )
  782. die( __('You are posting comments too quickly. Slow down.') );
  783. wp_die( __('You are posting comments too quickly. Slow down.'), '', array('response' => 403) );
  784. }
  785. }
  786. }
  787. /**
  788. * Separates an array of comments into an array keyed by comment_type.
  789. *
  790. * @since 2.7.0
  791. *
  792. * @param array $comments Array of comments
  793. * @return array Array of comments keyed by comment_type.
  794. */
  795. function separate_comments(&$comments) {
  796. $comments_by_type = array('comment' => array(), 'trackback' => array(), 'pingback' => array(), 'pings' => array());
  797. $count = count($comments);
  798. for ( $i = 0; $i < $count; $i++ ) {
  799. $type = $comments[$i]->comment_type;
  800. if ( empty($type) )
  801. $type = 'comment';
  802. $comments_by_type[$type][] = &$comments[$i];
  803. if ( 'trackback' == $type || 'pingback' == $type )
  804. $comments_by_type['pings'][] = &$comments[$i];
  805. }
  806. return $comments_by_type;
  807. }
  808. /**
  809. * Calculate the total number of comment pages.
  810. *
  811. * @since 2.7.0
  812. *
  813. * @uses Walker_Comment
  814. *
  815. * @param array $comments Optional array of comment objects. Defaults to $wp_query->comments
  816. * @param int $per_page Optional comments per page.
  817. * @param boolean $threaded Optional control over flat or threaded comments.
  818. * @return int Number of comment pages.
  819. */
  820. function get_comment_pages_count( $comments = null, $per_page = null, $threaded = null ) {
  821. global $wp_query;
  822. if ( null === $comments && null === $per_page && null === $threaded && !empty($wp_query->max_num_comment_pages) )
  823. return $wp_query->max_num_comment_pages;
  824. if ( ( ! $comments || ! is_array( $comments ) ) && ! empty( $wp_query->comments ) )
  825. $comments = $wp_query->comments;
  826. if ( empty($comments) )
  827. return 0;
  828. if ( ! get_option( 'page_comments' ) )
  829. return 1;
  830. if ( !isset($per_page) )
  831. $per_page = (int) get_query_var('comments_per_page');
  832. if ( 0 === $per_page )
  833. $per_page = (int) get_option('comments_per_page');
  834. if ( 0 === $per_page )
  835. return 1;
  836. if ( !isset($threaded) )
  837. $threaded = get_option('thread_comments');
  838. if ( $threaded ) {
  839. $walker = new Walker_Comment;
  840. $count = ceil( $walker->get_number_of_root_elements( $comments ) / $per_page );
  841. } else {
  842. $count = ceil( count( $comments ) / $per_page );
  843. }
  844. return $count;
  845. }
  846. /**
  847. * Calculate what page number a comment will appear on for comment paging.
  848. *
  849. * @since 2.7.0
  850. * @uses get_comment() Gets the full comment of the $comment_ID parameter.
  851. * @uses get_option() Get various settings to control function and defaults.
  852. * @uses get_page_of_comment() Used to loop up to top level comment.
  853. *
  854. * @param int $comment_ID Comment ID.
  855. * @param array $args Optional args.
  856. * @return int|null Comment page number or null on error.
  857. */
  858. function get_page_of_comment( $comment_ID, $args = array() ) {
  859. global $wpdb;
  860. if ( !$comment = get_comment( $comment_ID ) )
  861. return;
  862. $defaults = array( 'type' => 'all', 'page' => '', 'per_page' => '', 'max_depth' => '' );
  863. $args = wp_parse_args( $args, $defaults );
  864. if ( '' === $args['per_page'] && get_option('page_comments') )
  865. $args['per_page'] = get_query_var('comments_per_page');
  866. if ( empty($args['per_page']) ) {
  867. $args['per_page'] = 0;
  868. $args['page'] = 0;
  869. }
  870. if ( $args['per_page'] < 1 )
  871. return 1;
  872. if ( '' === $args['max_depth'] ) {
  873. if ( get_option('thread_comments') )
  874. $args['max_depth'] = get_option('thread_comments_depth');
  875. else
  876. $args['max_depth'] = -1;
  877. }
  878. // Find this comment's top level parent if threading is enabled
  879. if ( $args['max_depth'] > 1 && 0 != $comment->comment_parent )
  880. return get_page_of_comment( $comment->comment_parent, $args );
  881. $allowedtypes = array(
  882. 'comment' => '',
  883. 'pingback' => 'pingback',
  884. 'trackback' => 'trackback',
  885. );
  886. $comtypewhere = ( 'all' != $args['type'] && isset($allowedtypes[$args['type']]) ) ? " AND comment_type = '" . $allowedtypes[$args['type']] . "'" : '';
  887. // Count comments older than this one
  888. $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 ) );
  889. // No older comments? Then it's page #1.
  890. if ( 0 == $oldercoms )
  891. return 1;
  892. // Divide comments older than this one by comments per page to get this comment's page number
  893. return ceil( ( $oldercoms + 1 ) / $args['per_page'] );
  894. }
  895. /**
  896. * Does comment contain blacklisted characters or words.
  897. *
  898. * @since 1.5.0
  899. *
  900. * @param string $author The author of the comment
  901. * @param string $email The email of the comment
  902. * @param string $url The url used in the comment
  903. * @param string $comment The comment content
  904. * @param string $user_ip The comment author IP address
  905. * @param string $user_agent The author's browser user agent
  906. * @return bool True if comment contains blacklisted content, false if comment does not
  907. */
  908. function wp_blacklist_check($author, $email, $url, $comment, $user_ip, $user_agent) {
  909. /**
  910. * Fires before the comment is tested for blacklisted characters or words.
  911. *
  912. * @since 1.5.0
  913. *
  914. * @param string $author Comment author.
  915. * @param string $email Comment author's email.
  916. * @param string $url Comment author's URL.
  917. * @param string $comment Comment content.
  918. * @param string $user_ip Comment author's IP address.
  919. * @param string $user_agent Comment author's browser user agent.
  920. */
  921. do_action( 'wp_blacklist_check', $author, $email, $url, $comment, $user_ip, $user_agent );
  922. $mod_keys = trim( get_option('blacklist_keys') );
  923. if ( '' == $mod_keys )
  924. return false; // If moderation keys are empty
  925. $words = explode("\n", $mod_keys );
  926. foreach ( (array) $words as $word ) {
  927. $word = trim($word);
  928. // Skip empty lines
  929. if ( empty($word) ) { continue; }
  930. // Do some escaping magic so that '#' chars in the
  931. // spam words don't break things:
  932. $word = preg_quote($word, '#');
  933. $pattern = "#$word#i";
  934. if (
  935. preg_match($pattern, $author)
  936. || preg_match($pattern, $email)
  937. || preg_match($pattern, $url)
  938. || preg_match($pattern, $comment)
  939. || preg_match($pattern, $user_ip)
  940. || preg_match($pattern, $user_agent)
  941. )
  942. return true;
  943. }
  944. return false;
  945. }
  946. /**
  947. * Retrieve total comments for blog or single post.
  948. *
  949. * The properties of the returned object contain the 'moderated', 'approved',
  950. * and spam comments for either the entire blog or single post. Those properties
  951. * contain the amount of comments that match the status. The 'total_comments'
  952. * property contains the integer of total comments.
  953. *
  954. * The comment stats are cached and then retrieved, if they already exist in the
  955. * cache.
  956. *
  957. * @since 2.5.0
  958. *
  959. * @param int $post_id Optional. Post ID.
  960. * @return object Comment stats.
  961. */
  962. function wp_count_comments( $post_id = 0 ) {
  963. global $wpdb;
  964. $post_id = (int) $post_id;
  965. /**
  966. * Filter the comments count for a given post.
  967. *
  968. * @since 2.7.0
  969. *
  970. * @param array $count An empty array.
  971. * @param int $post_id The post ID.
  972. */
  973. $stats = apply_filters( 'wp_count_comments', array(), $post_id );
  974. if ( !empty($stats) )
  975. return $stats;
  976. $count = wp_cache_get("comments-{$post_id}", 'counts');
  977. if ( false !== $count )
  978. return $count;
  979. $where = '';
  980. if ( $post_id > 0 )
  981. $where = $wpdb->prepare( "WHERE comment_post_ID = %d", $post_id );
  982. $count = $wpdb->get_results( "SELECT comment_approved, COUNT( * ) AS num_comments FROM {$wpdb->comments} {$where} GROUP BY comment_approved", ARRAY_A );
  983. $total = 0;
  984. $approved = array('0' => 'moderated', '1' => 'approved', 'spam' => 'spam', 'trash' => 'trash', 'post-trashed' => 'post-trashed');
  985. foreach ( (array) $count as $row ) {
  986. // Don't count post-trashed toward totals
  987. if ( 'post-trashed' != $row['comment_approved'] && 'trash' != $row['comment_approved'] )
  988. $total += $row['num_comments'];
  989. if ( isset( $approved[$row['comment_approved']] ) )
  990. $stats[$approved[$row['comment_approved']]] = $row['num_comments'];
  991. }
  992. $stats['total_comments'] = $total;
  993. foreach ( $approved as $key ) {
  994. if ( empty($stats[$key]) )
  995. $stats[$key] = 0;
  996. }
  997. $stats = (object) $stats;
  998. wp_cache_set("comments-{$post_id}", $stats, 'counts');
  999. return $stats;
  1000. }
  1001. /**
  1002. * Trashes or deletes a comment.
  1003. *
  1004. * The comment is moved to trash instead of permanently deleted unless trash is
  1005. * disabled, item is already in the trash, or $force_delete is true.
  1006. *
  1007. * The post comment count will be updated if the comment was approved and has a
  1008. * post ID available.
  1009. *
  1010. * @since 2.0.0
  1011. * @uses $wpdb
  1012. * @uses wp_transition_comment_status() Passes new and old comment status along with $comment object
  1013. *
  1014. * @param int $comment_id Comment ID
  1015. * @param bool $force_delete Whether to bypass trash and force deletion. Default is false.
  1016. * @return bool True on success, false on failure.
  1017. */
  1018. function wp_delete_comment($comment_id, $force_delete = false) {
  1019. global $wpdb;
  1020. if (!$comment = get_comment($comment_id))
  1021. return false;
  1022. if ( !$force_delete && EMPTY_TRASH_DAYS && !in_array( wp_get_comment_status($comment_id), array( 'trash', 'spam' ) ) )
  1023. return wp_trash_comment($comment_id);
  1024. /**
  1025. * Fires immediately before a comment is deleted from the database.
  1026. *
  1027. * @since 1.2.0
  1028. *
  1029. * @param int $comment_id The comment ID.
  1030. */
  1031. do_action( 'delete_comment', $comment_id );
  1032. // Move children up a level.
  1033. $children = $wpdb->get_col( $wpdb->prepare("SELECT comment_ID FROM $wpdb->comments WHERE comment_parent = %d", $comment_id) );
  1034. if ( !empty($children) ) {
  1035. $wpdb->update($wpdb->comments, array('comment_parent' => $comment->comment_parent), array('comment_parent' => $comment_id));
  1036. clean_comment_cache($children);
  1037. }
  1038. // Delete metadata
  1039. $meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->commentmeta WHERE comment_id = %d", $comment_id ) );
  1040. foreach ( $meta_ids as $mid )
  1041. delete_metadata_by_mid( 'comment', $mid );
  1042. if ( ! $wpdb->delete( $wpdb->comments, array( 'comment_ID' => $comment_id ) ) )
  1043. return false;
  1044. /**
  1045. * Fires immediately after a comment is deleted from the database.
  1046. *
  1047. * @since 2.9.0
  1048. *
  1049. * @param int $comment_id The comment ID.
  1050. */
  1051. do_action( 'deleted_comment', $comment_id );
  1052. $post_id = $comment->comment_post_ID;
  1053. if ( $post_id && $comment->comment_approved == 1 )
  1054. wp_update_comment_count($post_id);
  1055. clean_comment_cache($comment_id);
  1056. /**
  1057. * Fires immediately before changing the comment's status to 'delete'.
  1058. *
  1059. * @since 1.5.0
  1060. *
  1061. * @param int $comment_id The comment ID.
  1062. * @param string $status The new 'delete' comment status.
  1063. */
  1064. do_action( 'wp_set_comment_status', $comment_id, 'delete' );
  1065. wp_transition_comment_status('delete', $comment->comment_approved, $comment);
  1066. return true;
  1067. }
  1068. /**
  1069. * Moves a comment to the Trash
  1070. *
  1071. * If trash is disabled, comment is permanently deleted.
  1072. *
  1073. * @since 2.9.0
  1074. *
  1075. * @uses wp_delete_comment() if trash is disabled
  1076. *
  1077. * @param int $comment_id Comment ID.
  1078. * @return bool True on success, false on failure.
  1079. */
  1080. function wp_trash_comment($comment_id) {
  1081. if ( !EMPTY_TRASH_DAYS )
  1082. return wp_delete_comment($comment_id, true);
  1083. if ( !$comment = get_comment($comment_id) )
  1084. return false;
  1085. /**
  1086. * Fires immediately before a comment is sent to the Trash.
  1087. *
  1088. * @since 2.9.0
  1089. *
  1090. * @param int $comment_id The comment ID.
  1091. */
  1092. do_action( 'trash_comment', $comment_id );
  1093. if ( wp_set_comment_status($comment_id, 'trash') ) {
  1094. add_comment_meta($comment_id, '_wp_trash_meta_status', $comment->comment_approved);
  1095. add_comment_meta($comment_id, '_wp_trash_meta_time', time() );
  1096. /**
  1097. * Fires immediately after a comment is sent to Trash.
  1098. *
  1099. * @since 2.9.0
  1100. *
  1101. * @param int $comment_id The comment ID.
  1102. */
  1103. do_action( 'trashed_comment', $comment_id );
  1104. return true;
  1105. }
  1106. return false;
  1107. }
  1108. /**
  1109. * Removes a comment from the Trash
  1110. *
  1111. * @since 2.9.0
  1112. *
  1113. * @param int $comment_id Comment ID.
  1114. * @return bool True on success, false on failure.
  1115. */
  1116. function wp_untrash_comment($comment_id) {
  1117. if ( ! (int)$comment_id )
  1118. return false;
  1119. /**
  1120. * Fires immediately before a comment is restored from the Trash.
  1121. *
  1122. * @since 2.9.0
  1123. *
  1124. * @param int $comment_id The comment ID.
  1125. */
  1126. do_action( 'untrash_comment', $comment_id );
  1127. $status = (string) get_comment_meta($comment_id, '_wp_trash_meta_status', true);
  1128. if ( empty($status) )
  1129. $status = '0';
  1130. if ( wp_set_comment_status($comment_id, $status) ) {
  1131. delete_comment_meta($comment_id, '_wp_trash_meta_time');
  1132. delete_comment_meta($comment_id, '_wp_trash_meta_status');
  1133. /**
  1134. * Fires immediately after a comment is restored from the Trash.
  1135. *
  1136. * @since 2.9.0
  1137. *
  1138. * @param int $comment_id The comment ID.
  1139. */
  1140. do_action( 'untrashed_comment', $comment_id );
  1141. return true;
  1142. }
  1143. return false;
  1144. }
  1145. /**
  1146. * Marks a comment as Spam
  1147. *
  1148. * @since 2.9.0
  1149. *
  1150. * @param int $comment_id Comment ID.
  1151. * @return bool True on success, false on failure.
  1152. */
  1153. function wp_spam_comment($comment_id) {
  1154. if ( !$comment = get_comment($comment_id) )
  1155. return false;
  1156. /**
  1157. * Fires immediately before a comment is marked as Spam.
  1158. *
  1159. * @since 2.9.0
  1160. *
  1161. * @param int $comment_id The comment ID.
  1162. */
  1163. do_action( 'spam_comment', $comment_id );
  1164. if ( wp_set_comment_status($comment_id, 'spam') ) {
  1165. add_comment_meta($comment_id, '_wp_trash_meta_status', $comment->comment_approved);
  1166. /**
  1167. * Fires immediately after a comment is marked as Spam.
  1168. *
  1169. * @since 2.9.0
  1170. *
  1171. * @param int $comment_id The comment ID.
  1172. */
  1173. do_action( 'spammed_comment', $comment_id );
  1174. return true;
  1175. }
  1176. return false;
  1177. }
  1178. /**
  1179. * Removes a comment from the Spam
  1180. *
  1181. * @since 2.9.0
  1182. *
  1183. * @param int $comment_id Comment ID.
  1184. * @return bool True on success, false on failure.
  1185. */
  1186. function wp_unspam_comment($comment_id) {
  1187. if ( ! (int)$comment_id )
  1188. return false;
  1189. /**
  1190. * Fires immediately before a comment is unmarked as Spam.
  1191. *
  1192. * @since 2.9.0
  1193. *
  1194. * @param int $comment_id The comment ID.
  1195. */
  1196. do_action( 'unspam_comment', $comment_id );
  1197. $status = (string) get_comment_meta($comment_id, '_wp_trash_meta_status', true);
  1198. if ( empty($status) )
  1199. $status = '0';
  1200. if ( wp_set_comment_status($comment_id, $status) ) {
  1201. delete_comment_meta($comment_id, '_wp_trash_meta_status');
  1202. /**
  1203. * Fires immediately after a comment is unmarked as Spam.
  1204. *
  1205. * @since 2.9.0
  1206. *
  1207. * @param int $comment_id The comment ID.
  1208. */
  1209. do_action( 'unspammed_comment', $comment_id );
  1210. return true;
  1211. }
  1212. return false;
  1213. }
  1214. /**
  1215. * The status of a comment by ID.
  1216. *
  1217. * @since 1.0.0
  1218. *
  1219. * @param int $comment_id Comment ID
  1220. * @return string|bool Status might be 'trash', 'approved', 'unapproved', 'spam'. False on failure.
  1221. */
  1222. function wp_get_comment_status($comment_id) {
  1223. $comment = get_comment($comment_id);
  1224. if ( !$comment )
  1225. return false;
  1226. $approved = $comment->comment_approved;
  1227. if ( $approved == null )
  1228. return false;
  1229. elseif ( $approved == '1' )
  1230. return 'approved';
  1231. elseif ( $approved == '0' )
  1232. return 'unapproved';
  1233. elseif ( $approved == 'spam' )
  1234. return 'spam';
  1235. elseif ( $approved == 'trash' )
  1236. return 'trash';
  1237. else
  1238. return false;
  1239. }
  1240. /**
  1241. * Call hooks for when a comment status transition occurs.
  1242. *
  1243. * Calls hooks for comment status transitions. If the new comment status is not the same
  1244. * as the previous comment status, then two hooks will be ran, the first is
  1245. * 'transition_comment_status' with new status, old status, and comment data. The
  1246. * next action called is 'comment_OLDSTATUS_to_NEWSTATUS' the NEWSTATUS is the
  1247. * $new_status parameter and the OLDSTATUS is $old_status parameter; it has the
  1248. * comment data.
  1249. *
  1250. * The final action will run whether or not the comment statuses are the same. The
  1251. * action is named 'comment_NEWSTATUS_COMMENTTYPE', NEWSTATUS is from the $new_status
  1252. * parameter and COMMENTTYPE is comment_type comment data.
  1253. *
  1254. * @since 2.7.0
  1255. *
  1256. * @param string $new_status New comment status.
  1257. * @param string $old_status Previous comment status.
  1258. * @param object $comment Comment data.
  1259. */
  1260. function wp_transition_comment_status($new_status, $old_status, $comment) {
  1261. /*
  1262. * Translate raw statuses to human readable formats for the hooks.
  1263. * This is not a complete list of comment status, it's only the ones
  1264. * that need to be renamed
  1265. */
  1266. $comment_statuses = array(
  1267. 0 => 'unapproved',
  1268. 'hold' => 'unapproved', // wp_set_comment_status() uses "hold"
  1269. 1 => 'approved',
  1270. 'approve' => 'approved', // wp_set_comment_status() uses "approve"
  1271. );
  1272. if ( isset($comment_statuses[$new_status]) ) $new_status = $comment_statuses[$new_status];
  1273. if ( isset($comment_statuses[$old_status]) ) $old_status = $comment_statuses[$old_status];
  1274. // Call the hooks
  1275. if ( $new_status != $old_status ) {
  1276. /**
  1277. * Fires when the comment status is in transition.
  1278. *
  1279. * @since 2.7.0
  1280. *
  1281. * @param int|string $new_status The new comment status.
  1282. * @param int|string $old_status The old comment status.
  1283. * @param object $comment The comment data.
  1284. */
  1285. do_action( 'transition_comment_status', $new_status, $old_status, $comment );
  1286. /**
  1287. * Fires when the comment status is in transition from one specific status to another.
  1288. *
  1289. * The dynamic portions of the hook name, $old_status, and $new_status,
  1290. * refer to the old and new comment statuses, respectively.
  1291. *
  1292. * @since 2.7.0
  1293. *
  1294. * @param object $comment Comment object.
  1295. */
  1296. do_action( "comment_{$old_status}_to_{$new_status}", $comment );
  1297. }
  1298. /**
  1299. * Fires when the status of a specific comment type is in transition.
  1300. *
  1301. * The dynamic portions of the hook name, $new_status, and $comment->comment_type,
  1302. * refer to the new comment status, and the type of comment, respectively.
  1303. *
  1304. * Typical comment types include an empty string (standard comment), 'pingback',
  1305. * or 'trackback'.
  1306. *
  1307. * @since 2.7.0
  1308. *
  1309. * @param int $comment_ID The comment ID.
  1310. * @param obj $comment Comment object.
  1311. */
  1312. do_action( "comment_{$new_status}_{$comment->comment_type}", $comment->comment_ID, $comment );
  1313. }
  1314. /**
  1315. * Get current commenter's name, email, and URL.
  1316. *
  1317. * Expects cookies content to already be sanitized. User of this function might
  1318. * wish to recheck the returned array for validity.
  1319. *
  1320. * @see sanitize_comment_cookies() Use to sanitize cookies
  1321. *
  1322. * @since 2.0.4
  1323. *
  1324. * @return array Comment author, email, url respectively.
  1325. */
  1326. function wp_get_current_commenter() {
  1327. // Cookies should already be sanitized.
  1328. $comment_author = '';
  1329. if ( isset($_COOKIE['comment_author_'.COOKIEHASH]) )
  1330. $comment_author = $_COOKIE['comment_author_'.COOKIEHASH];
  1331. $comment_author_email = '';
  1332. if ( isset($_COOKIE['comment_author_email_'.COOKIEHASH]) )
  1333. $comment_author_email = $_COOKIE['comment_author_email_'.COOKIEHASH];
  1334. $comment_author_url = '';
  1335. if ( isset($_COOKIE['comment_author_url_'.COOKIEHASH]) )
  1336. $comment_author_url = $_COOKIE['comment_author_url_'.COOKIEHASH];
  1337. /**
  1338. * Filter the current commenter's name, email, and URL.
  1339. *
  1340. * @since 3.1.0
  1341. *
  1342. * @param string $comment_author Comment author's name.
  1343. * @param string $comment_author_email Comment author's email.
  1344. * @param string $comment_author_url Comment author's URL.
  1345. */
  1346. return apply_filters( 'wp_get_current_commenter', compact('comment_author', 'comment_author_email', 'comment_author_url') );
  1347. }
  1348. /**
  1349. * Inserts a comment to the database.
  1350. *
  1351. * The available comment data key names are 'comment_author_IP', 'comment_date',
  1352. * 'comment_date_gmt', 'comment_parent', 'comment_approved', and 'user_id'.
  1353. *
  1354. * @since 2.0.0
  1355. * @uses $wpdb
  1356. *
  1357. * @param array $commentdata Contains information on the comment.
  1358. * @return int The new comment's ID.
  1359. */
  1360. function wp_insert_comment($commentdata) {
  1361. global $wpdb;
  1362. extract(wp_unslash($commentdata), EXTR_SKIP);
  1363. if ( ! isset($comment_author_IP) )
  1364. $comment_author_IP = '';
  1365. if ( ! isset($comment_date) )
  1366. $comment_date = current_time('mysql');
  1367. if ( ! isset($comment_date_gmt) )
  1368. $comment_date_gmt = get_gmt_from_date($comment_date);
  1369. if ( ! isset($comment_parent) )
  1370. $comment_parent = 0;
  1371. if ( ! isset($comment_approved) )
  1372. $comment_approved = 1;
  1373. if ( ! isset($comment_karma) )
  1374. $comment_karma = 0;
  1375. if ( ! isset($user_id) )
  1376. $user_id = 0;
  1377. if ( ! isset($comment_type) )
  1378. $comment_type = '';
  1379. $data = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_date', 'comment_date_gmt', 'comment_content', 'comment_karma', 'comment_approved', 'comment_agent', 'comment_type', 'comment_parent', 'user_id');
  1380. $wpdb->insert($wpdb->comments, $data);
  1381. $id = (int) $wpdb->insert_id;
  1382. if ( $comment_approved == 1 )
  1383. wp_update_comment_count($comment_post_ID);
  1384. $comment = get_comment($id);
  1385. /**
  1386. * Fires immediately after a comment is inserted into the database.
  1387. *
  1388. * @since 2.8.0
  1389. *
  1390. * @param int $id The comment ID.
  1391. * @param obj $comment Comment object.
  1392. */
  1393. do_action( 'wp_insert_comment', $id, $comment );
  1394. wp_cache_set( 'last_changed', microtime(), 'comment' );
  1395. return $id;
  1396. }
  1397. /**
  1398. * Filters and sanitizes comment data.
  1399. *
  1400. * Sets the comment data 'filtered' field to true when finished. This can be
  1401. * checked as to whether the comment should be filtered and to keep from
  1402. * filtering the same comment more than once.
  1403. *
  1404. * @since 2.0.0
  1405. *
  1406. * @param array $commentdata Contains information on the comment.
  1407. * @return array Parsed comment information.
  1408. */
  1409. function wp_filter_comment($commentdata) {
  1410. if ( isset( $commentdata['user_ID'] ) ) {
  1411. /**
  1412. * Filter the comment author's user id before it is set.
  1413. *
  1414. * The first time this filter is evaluated, 'user_ID' is checked
  1415. * (for back-compat), followed by the standard 'user_id' value.
  1416. *
  1417. * @since 1.5.0
  1418. *
  1419. * @param int $user_ID The comment author's user ID.
  1420. */
  1421. $commentdata['user_id'] = apply_filters( 'pre_user_id', $commentdata['user_ID'] );
  1422. } elseif ( isset( $commentdata['user_id'] ) ) {
  1423. /** This filter is documented in wp-includes/comment.php */
  1424. $commentdata['user_id'] = apply_filters( 'pre_user_id', $commentdata['user_id'] );
  1425. }
  1426. /**
  1427. * Filter the comment author's browser user agent before it is set.
  1428. *
  1429. * @since 1.5.0
  1430. *
  1431. * @param int $comment_agent The comment author's browser user agent.
  1432. */
  1433. $commentdata['comment_agent'] = apply_filters( 'pre_comment_user_agent', ( isset( $commentdata['comment_agent'] ) ? $commentdata['comment_agent'] : '' ) );
  1434. /** This filter is documented in wp-includes/comment.php */
  1435. $commentdata['comment_author'] = apply_filters( 'pre_comment_author_name', $commentdata['comment_author'] );
  1436. /**
  1437. * Filter the comment content before it is set.
  1438. *
  1439. * @since 1.5.0
  1440. *
  1441. * @param int $comment_content The comment content.
  1442. */
  1443. $commentdata['comment_content'] = apply_filters( 'pre_comment_content', $commentdata['comment_content'] );
  1444. /**
  1445. * Filter the comment author's IP before it is set.
  1446. *
  1447. * @since 1.5.0
  1448. *
  1449. * @param int $comment_author_ip The comment author's IP.
  1450. */
  1451. $commentdata['comment_author_IP'] = apply_filters( 'pre_comment_user_ip', $commentdata['comment_author_IP'] );
  1452. /** This filter is documented in wp-includes/comment.php */
  1453. $commentdata['comment_author_url'] = apply_filters( 'pre_comment_author_url', $commentdata['comment_author_url'] );
  1454. /** This filter is documented in wp-includes/comment.php */
  1455. $commentdata['comment_author_email'] = apply_filters( 'pre_comment_author_email', $commentdata['comment_author_email'] );
  1456. $commentdata['filtered'] = true;
  1457. return $commentdata;
  1458. }
  1459. /**
  1460. * Whether a comment should be blocked because of comment flood.
  1461. *
  1462. * @since 2.1.0
  1463. *
  1464. * @param bool $block Whether plugin has already blocked comment.
  1465. * @param int $time_lastcomment Timestamp for last comment.
  1466. * @param int $time_newcomment Timestamp for new comment.
  1467. * @return bool Whether comment should be blocked.
  1468. */
  1469. function wp_throttle_comment_flood($block, $time_lastcomment, $time_newcomment) {
  1470. if ( $block ) // a plugin has already blocked... we'll let that decision stand
  1471. return $block;
  1472. if ( ($time_newcomment - $time_lastcomment) < 15 )
  1473. return true;
  1474. return false;
  1475. }
  1476. /**
  1477. * Adds a new comment to the database.
  1478. *
  1479. * Filters new comment to ensure that the fields are sanitized and valid before
  1480. * inserting comment into database. Calls 'comment_post' action with comment ID
  1481. * and whether comment is approved by WordPress. Also has 'preprocess_comment'
  1482. * filter for processing the comment data before the function handles it.
  1483. *
  1484. * We use REMOTE_ADDR here directly. If you are behind a proxy, you should ensure
  1485. * that it is properly set, such as in wp-config.php, for your environment.
  1486. * See {@link http://core.trac.wordpress.org/ticket/9235}
  1487. *
  1488. * @since 1.5.0
  1489. * @param array $commentdata Contains information on the comment.
  1490. * @return int The ID of the comment after adding.
  1491. */
  1492. function wp_new_comment( $commentdata ) {
  1493. /**
  1494. * Filter a comment's data before it is sanitized and inserted into the database.
  1495. *
  1496. * @since 1.5.0
  1497. *
  1498. * @param array $commentdata Comment data.
  1499. */
  1500. $commentdata = apply_filters( 'preprocess_comment', $commentdata );
  1501. $commentdata['comment_post_ID'] = (int) $commentdata['comment_post_ID'];
  1502. if ( isset($commentdata['user_ID']) )
  1503. $commentdata['user_id'] = $commentdata['user_ID'] = (int) $commentdata['user_ID'];
  1504. elseif ( isset($commentdata['user_id']) )
  1505. $commentdata['user_id'] = (int) $commentdata['user_id'];
  1506. $commentdata['comment_parent'] = isset($commentdata['comment_parent']) ? absint($commentdata['comment_parent']) : 0;
  1507. $parent_status = ( 0 < $commentdata['comment_parent'] ) ? wp_get_comment_status($commentdata['comment_parent']) : '';
  1508. $commentdata['comment_parent'] = ( 'approved' == $parent_status || 'unapproved' == $parent_status ) ? $commentdata['comment_parent'] : 0;
  1509. $commentdata['comment_author_IP'] = preg_replace( '/[^0-9a-fA-F:., ]/', '',$_SERVER['REMOTE_ADDR'] );
  1510. $commentdata['comment_agent'] = isset( $_SERVER['HTTP_USER_AGENT'] ) ? substr( $_SERVER['HTTP_USER_AGENT'], 0, 254 ) : '';
  1511. $commentdata['comment_date'] = current_time('mysql');
  1512. $commentdata['comment_date_gmt'] = current_time('mysql', 1);
  1513. $commentdata = wp_filter_comment($commentdata);
  1514. $commentdata['comment_approved'] = wp_allow_comment($commentdata);
  1515. $comment_ID = wp_insert_comment($commentdata);
  1516. /**
  1517. * Fires immediately after a comment is inserted into the database.
  1518. *
  1519. * @since 1.2.0
  1520. *
  1521. * @param int $comment_ID The comment ID.
  1522. * @param int $comment_approved 1 (true) if the comment is approved, 0 (false) if not.
  1523. */
  1524. do_action( 'comment_post', $comment_ID, $commentdata['comment_approved'] );
  1525. if ( 'spam' !== $commentdata['comment_approved'] ) { // If it's spam save it silently for later crunching
  1526. if ( '0' == $commentdata['comment_approved'] ) {
  1527. wp_notify_moderator( $comment_ID );
  1528. }
  1529. // wp_notify_postauthor() checks if notifying the author of their own comment.
  1530. // By default, it won't, but filters can override this.
  1531. if ( get_option( 'comments_notify' ) && $commentdata['comment_approved'] ) {
  1532. wp_notify_postauthor( $comment_ID );
  1533. }
  1534. }
  1535. return $comment_ID;
  1536. }
  1537. /**
  1538. * Sets the status of a comment.
  1539. *
  1540. * The 'wp_set_comment_status' action is called after the comment is handled.
  1541. * If the comment status is not in the list, then false is returned.
  1542. *
  1543. * @since 1.0.0
  1544. * @uses wp_transition_comment_status() Passes new and old comment status along with $comment object
  1545. *
  1546. * @param int $comment_id Comment ID.
  1547. * @param string $comment_status New comment status, either 'hold', 'approve', 'spam', or 'trash'.
  1548. * @param bool $wp_error Whether to return a WP_Error object if there is a failure. Default is false.
  1549. * @return bool|WP_Error True on success, false or WP_Error on failure.
  1550. */
  1551. function wp_set_comment_status($comment_id, $comment_status, $wp_error = false) {
  1552. global $wpdb;
  1553. $status = '0';
  1554. switch ( $comment_status ) {
  1555. case 'hold':
  1556. case '0':
  1557. $status = '0';
  1558. break;
  1559. case 'approve':
  1560. case '1':
  1561. $status = '1';
  1562. if ( get_option('comments_notify') ) {
  1563. wp_notify_postauthor( $comment_id );
  1564. }
  1565. break;
  1566. case 'spam':
  1567. $status = 'spam';
  1568. break;
  1569. case 'trash':
  1570. $status = 'trash';
  1571. break;
  1572. default:
  1573. return false;
  1574. }
  1575. $comment_old = clone get_comment($comment_id);
  1576. if ( !$wpdb->update( $wpdb->comments, array('comment_approved' => $status), array('comment_ID' => $comment_id) ) ) {
  1577. if ( $wp_error )
  1578. return new WP_Error('db_update_error', __('Could not update comment status'), $wpdb->last_error);
  1579. else
  1580. return false;
  1581. }
  1582. clean_comment_cache($comment_id);
  1583. $comment = get_comment($comment_id);
  1584. /**
  1585. * Fires after a comment status has been updated in the database.
  1586. *
  1587. * The hook also fires immediately before comment status transition hooks are fired.
  1588. *
  1589. * @since 1.5.0
  1590. *
  1591. * @param int $comment_id The comment ID.
  1592. * @param string|bool $comment_status The comment status. Possible values include 'hold',
  1593. * 'approve', 'spam', 'trash', or false.
  1594. */
  1595. do_action( 'wp_set_comment_status', $comment_id, $comment_status );
  1596. wp_transition_comment_status($comment_status, $comment_old->comment_approved, $comment);
  1597. wp_update_comment_count($comment->comment_post_ID);
  1598. return true;
  1599. }
  1600. /**
  1601. * Updates an existing comment in the database.
  1602. *
  1603. * Filters the comment and makes sure certain fields are valid before updating.
  1604. *
  1605. * @since 2.0.0
  1606. * @uses $wpdb
  1607. * @uses wp_transition_comment_status() Passes new and old comment status along with $comment object
  1608. *
  1609. * @param array $commentarr Contains information on the comment.
  1610. * @return int Comment was updated if value is 1, or was not updated if value is 0.
  1611. */
  1612. function wp_update_comment($commentarr) {
  1613. global $wpdb;
  1614. // First, get all of the original fields
  1615. $comment = get_comment($commentarr['comment_ID'], ARRAY_A);
  1616. if ( empty( $comment ) )
  1617. return 0;
  1618. // Escape data pulled from DB.
  1619. $comment = wp_slash($comment);
  1620. $old_status = $comment['comment_approved'];
  1621. // Merge old and new fields with new fields overwriting old ones.
  1622. $commentarr = array_merge($comment, $commentarr);
  1623. $commentarr = wp_filter_comment( $commentarr );
  1624. // Now extract the merged array.
  1625. extract(wp_unslash($commentarr), EXTR_SKIP);
  1626. /**
  1627. * Filter the comment content before it is updated in the database.
  1628. *
  1629. * @since 1.5.0
  1630. *
  1631. * @param string $comment_content The comment data.
  1632. */
  1633. $comment_content = apply_filters( 'comment_save_pre', $comment_content );
  1634. $comment_date_gmt = get_gmt_from_date($comment_date);
  1635. if ( !isset($comment_approved) )
  1636. $comment_approved = 1;
  1637. else if ( 'hold' == $comment_approved )
  1638. $comment_approved = 0;
  1639. else if ( 'approve' == $comment_approved )
  1640. $comment_approved = 1;
  1641. $data = compact( 'comment_content', 'comment_author', 'comment_author_email', 'comment_approved', 'comment_karma', 'comment_author_url', 'comment_date', 'comment_date_gmt', 'comment_parent' );
  1642. $rval = $wpdb->update( $wpdb->comments, $data, compact( 'comment_ID' ) );
  1643. clean_comment_cache($comment_ID);
  1644. wp_update_comment_count($comment_post_ID);
  1645. /**
  1646. * Fires immediately after a comment is updated in the database.
  1647. *
  1648. * The hook also fires immediately before comment status transition hooks are fired.
  1649. *
  1650. * @since 1.2.0
  1651. *
  1652. * @param int $comment_ID The comment ID.
  1653. */
  1654. do_action( 'edit_comment', $comment_ID );
  1655. $comment = get_comment($comment_ID);
  1656. wp_transition_comment_status($comment->comment_approved, $old_status, $comment);
  1657. return $rval;
  1658. }
  1659. /**
  1660. * Whether to defer comment counting.
  1661. *
  1662. * When setting $defer to true, all post comment counts will not be updated
  1663. * until $defer is set to false. When $defer is set to false, then all
  1664. * previously deferred updated post comment counts will then be automatically
  1665. * updated without having to call wp_update_comment_count() after.
  1666. *
  1667. * @since 2.5.0
  1668. * @staticvar bool $_defer
  1669. *
  1670. * @param bool $defer
  1671. * @return unknown
  1672. */
  1673. function wp_defer_comment_counting($defer=null) {
  1674. static $_defer = false;
  1675. if ( is_bool($defer) ) {
  1676. $_defer = $defer;
  1677. // flush any deferred counts
  1678. if ( !$defer )
  1679. wp_update_comment_count( null, true );
  1680. }
  1681. return $_defer;
  1682. }
  1683. /**
  1684. * Updates the comment count for post(s).
  1685. *
  1686. * When $do_deferred is false (is by default) and the comments have been set to
  1687. * be deferred, the post_id will be added to a queue, which will be updated at a
  1688. * later date and only updated once per post ID.
  1689. *
  1690. * If the comments have not be set up to be deferred, then the post will be
  1691. * updated. When $do_deferred is set to true, then all previous deferred post
  1692. * IDs will be updated along with the current $post_id.
  1693. *
  1694. * @since 2.1.0
  1695. * @see wp_update_comment_count_now() For what could cause a false return value
  1696. *
  1697. * @param int $post_id Post ID
  1698. * @param bool $do_deferred Whether to process previously deferred post comment counts
  1699. * @return bool True on success, false on failure
  1700. */
  1701. function wp_update_comment_count($post_id, $do_deferred=false) {
  1702. static $_deferred = array();
  1703. if ( $do_deferred ) {
  1704. $_deferred = array_unique($_deferred);
  1705. foreach ( $_deferred as $i => $_post_id ) {
  1706. wp_update_comment_count_now($_post_id);
  1707. unset( $_deferred[$i] ); /** @todo Move this outside of the foreach and reset $_deferred to an array instead */
  1708. }
  1709. }
  1710. if ( wp_defer_comment_counting() ) {
  1711. $_deferred[] = $post_id;
  1712. return true;
  1713. }
  1714. elseif ( $post_id ) {
  1715. return wp_update_comment_count_now($post_id);
  1716. }
  1717. }
  1718. /**
  1719. * Updates the comment count for the post.
  1720. *
  1721. * @since 2.5.0
  1722. * @uses $wpdb
  1723. *
  1724. * @param int $post_id Post ID
  1725. * @return bool True on success, false on '0' $post_id or if post with ID does not exist.
  1726. */
  1727. function wp_update_comment_count_now($post_id) {
  1728. global $wpdb;
  1729. $post_id = (int) $post_id;
  1730. if ( !$post_id )
  1731. return false;
  1732. if ( !$post = get_post($post_id) )
  1733. return false;
  1734. $old = (int) $post->comment_count;
  1735. $new = (int) $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved = '1'", $post_id) );
  1736. $wpdb->update( $wpdb->posts, array('comment_count' => $new), array('ID' => $post_id) );
  1737. clean_post_cache( $post );
  1738. /**
  1739. * Fires immediately after a post's comment count is updated in the database.
  1740. *
  1741. * @since 2.3.0
  1742. *
  1743. * @param int $post_id Post ID.
  1744. * @param int $new The new comment count.
  1745. * @param int $old The old comment count.
  1746. */
  1747. do_action( 'wp_update_comment_count', $post_id, $new, $old );
  1748. /** This action is documented in wp-includes/post.php */
  1749. do_action( 'edit_post', $post_id, $post );
  1750. return true;
  1751. }
  1752. //
  1753. // Ping and trackback functions.
  1754. //
  1755. /**
  1756. * Finds a pingback server URI based on the given URL.
  1757. *
  1758. * Checks the HTML for the rel="pingback" link and x-pingback headers. It does
  1759. * a check for the x-pingback headers first and returns that, if available. The
  1760. * check for the rel="pingback" has more overhead than just the header.
  1761. *
  1762. * @since 1.5.0
  1763. *
  1764. * @param string $url URL to ping.
  1765. * @param int $deprecated Not Used.
  1766. * @return bool|string False on failure, string containing URI on success.
  1767. */
  1768. function discover_pingback_server_uri( $url, $deprecated = '' ) {
  1769. if ( !empty( $deprecated ) )
  1770. _deprecated_argument( __FUNCTION__, '2.7' );
  1771. $pingback_str_dquote = 'rel="pingback"';
  1772. $pingback_str_squote = 'rel=\'pingback\'';
  1773. /** @todo Should use Filter Extension or custom preg_match instead. */
  1774. $parsed_url = parse_url($url);
  1775. if ( ! isset( $parsed_url['host'] ) ) // Not an URL. This should never happen.
  1776. return false;
  1777. //Do not search for a pingback server on our own uploads
  1778. $uploads_dir = wp_upload_dir();
  1779. if ( 0 === strpos($url, $uploads_dir['baseurl']) )
  1780. return false;
  1781. $response = wp_safe_remote_head( $url, array( 'timeout' => 2, 'httpversion' => '1.0' ) );
  1782. if ( is_wp_error( $response ) )
  1783. return false;
  1784. if ( wp_remote_retrieve_header( $response, 'x-pingback' ) )
  1785. return wp_remote_retrieve_header( $response, 'x-pingback' );
  1786. // Not an (x)html, sgml, or xml page, no use going further.
  1787. if ( preg_match('#(image|audio|video|model)/#is', wp_remote_retrieve_header( $response, 'content-type' )) )
  1788. return false;
  1789. // Now do a GET since we're going to look in the html headers (and we're sure it's not a binary file)
  1790. $response = wp_safe_remote_get( $url, array( 'timeout' => 2, 'httpversion' => '1.0' ) );
  1791. if ( is_wp_error( $response ) )
  1792. return false;
  1793. $contents = wp_remote_retrieve_body( $response );
  1794. $pingback_link_offset_dquote = strpos($contents, $pingback_str_dquote);
  1795. $pingback_link_offset_squote = strpos($contents, $pingback_str_squote);
  1796. if ( $pingback_link_offset_dquote || $pingback_link_offset_squote ) {
  1797. $quote = ($pingback_link_offset_dquote) ? '"' : '\'';
  1798. $pingback_link_offset = ($quote=='"') ? $pingback_link_offset_dquote : $pingback_link_offset_squote;
  1799. $pingback_href_pos = @strpos($contents, 'href=', $pingback_link_offset);
  1800. $pingback_href_start = $pingback_href_pos+6;
  1801. $pingback_href_end = @strpos($contents, $quote, $pingback_href_start);
  1802. $pingback_server_url_len = $pingback_href_end - $pingback_href_start;
  1803. $pingback_server_url = substr($contents, $pingback_href_start, $pingback_server_url_len);
  1804. // We may find rel="pingback" but an incomplete pingback URL
  1805. if ( $pingback_server_url_len > 0 ) { // We got it!
  1806. return $pingback_server_url;
  1807. }
  1808. }
  1809. return false;
  1810. }
  1811. /**
  1812. * Perform all pingbacks, enclosures, trackbacks, and send to pingback services.
  1813. *
  1814. * @since 2.1.0
  1815. * @uses $wpdb
  1816. */
  1817. function do_all_pings() {
  1818. global $wpdb;
  1819. // Do pingbacks
  1820. while ($ping = $wpdb->get_row("SELECT ID, post_content, meta_id FROM {$wpdb->posts}, {$wpdb->postmeta} WHERE {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id AND {$wpdb->postmeta}.meta_key = '_pingme' LIMIT 1")) {
  1821. delete_metadata_by_mid( 'post', $ping->meta_id );
  1822. pingback( $ping->post_content, $ping->ID );
  1823. }
  1824. // Do Enclosures
  1825. while ($enclosure = $wpdb->get_row("SELECT ID, post_content, meta_id FROM {$wpdb->posts}, {$wpdb->postmeta} WHERE {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id AND {$wpdb->postmeta}.meta_key = '_encloseme' LIMIT 1")) {
  1826. delete_metadata_by_mid( 'post', $enclosure->meta_id );
  1827. do_enclose( $enclosure->post_content, $enclosure->ID );
  1828. }
  1829. // Do Trackbacks
  1830. $trackbacks = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE to_ping <> '' AND post_status = 'publish'");
  1831. if ( is_array($trackbacks) )
  1832. foreach ( $trackbacks as $trackback )
  1833. do_trackbacks($trackback);
  1834. //Do Update Services/Generic Pings
  1835. generic_ping();
  1836. }
  1837. /**
  1838. * Perform trackbacks.
  1839. *
  1840. * @since 1.5.0
  1841. * @uses $wpdb
  1842. *
  1843. * @param int $post_id Post ID to do trackbacks on.
  1844. */
  1845. function do_trackbacks($post_id) {
  1846. global $wpdb;
  1847. $post = get_post( $post_id );
  1848. $to_ping = get_to_ping($post_id);
  1849. $pinged = get_pung($post_id);
  1850. if ( empty($to_ping) ) {
  1851. $wpdb->update($wpdb->posts, array('to_ping' => ''), array('ID' => $post_id) );
  1852. return;
  1853. }
  1854. if ( empty($post->post_excerpt) ) {
  1855. /** This filter is documented in wp-admin/post-template.php */
  1856. $excerpt = apply_filters( 'the_content', $post->post_content, $post->ID );
  1857. } else {
  1858. /** This filter is documented in wp-admin/post-template.php */
  1859. $excerpt = apply_filters( 'the_excerpt', $post->post_excerpt );
  1860. }
  1861. $excerpt = str_replace(']]>', ']]&gt;', $excerpt);
  1862. $excerpt = wp_html_excerpt($excerpt, 252, '&#8230;');
  1863. /** This filter is documented in wp-includes/post-template.php */
  1864. $post_title = apply_filters( 'the_title', $post->post_title, $post->ID );
  1865. $post_title = strip_tags($post_title);
  1866. if ( $to_ping ) {
  1867. foreach ( (array) $to_ping as $tb_ping ) {
  1868. $tb_ping = trim($tb_ping);
  1869. if ( !in_array($tb_ping, $pinged) ) {
  1870. trackback($tb_ping, $post_title, $excerpt, $post_id);
  1871. $pinged[] = $tb_ping;
  1872. } else {
  1873. $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s, '')) WHERE ID = %d", $tb_ping, $post_id) );
  1874. }
  1875. }
  1876. }
  1877. }
  1878. /**
  1879. * Sends pings to all of the ping site services.
  1880. *
  1881. * @since 1.2.0
  1882. *
  1883. * @param int $post_id Post ID. Not actually used.
  1884. * @return int Same as Post ID from parameter
  1885. */
  1886. function generic_ping($post_id = 0) {
  1887. $services = get_option('ping_sites');
  1888. $services = explode("\n", $services);
  1889. foreach ( (array) $services as $service ) {
  1890. $service = trim($service);
  1891. if ( '' != $service )
  1892. weblog_ping($service);
  1893. }
  1894. return $post_id;
  1895. }
  1896. /**
  1897. * Pings back the links found in a post.
  1898. *
  1899. * @since 0.71
  1900. * @uses $wp_version
  1901. * @uses IXR_Client
  1902. *
  1903. * @param string $content Post content to check for links.
  1904. * @param int $post_ID Post ID.
  1905. */
  1906. function pingback($content, $post_ID) {
  1907. global $wp_version;
  1908. include_once(ABSPATH . WPINC . '/class-IXR.php');
  1909. include_once(ABSPATH . WPINC . '/class-wp-http-ixr-client.php');
  1910. // original code by Mort (http://mort.mine.nu:8080)
  1911. $post_links = array();
  1912. $pung = get_pung($post_ID);
  1913. // Step 1
  1914. // Parsing the post, external links (if any) are stored in the $post_links array
  1915. $post_links_temp = wp_extract_urls( $content );
  1916. // Step 2.
  1917. // Walking thru the links array
  1918. // first we get rid of links pointing to sites, not to specific files
  1919. // Example:
  1920. // http://dummy-weblog.org
  1921. // http://dummy-weblog.org/
  1922. // http://dummy-weblog.org/post.php
  1923. // We don't wanna ping first and second types, even if they have a valid <link/>
  1924. foreach ( (array) $post_links_temp as $link_test ) :
  1925. if ( !in_array($link_test, $pung) && (url_to_postid($link_test) != $post_ID) // If we haven't pung it already and it isn't a link to itself
  1926. && !is_local_attachment($link_test) ) : // Also, let's never ping local attachments.
  1927. if ( $test = @parse_url($link_test) ) {
  1928. if ( isset($test['query']) )
  1929. $post_links[] = $link_test;
  1930. elseif ( isset( $test['path'] ) && ( $test['path'] != '/' ) && ( $test['path'] != '' ) )
  1931. $post_links[] = $link_test;
  1932. }
  1933. endif;
  1934. endforeach;
  1935. $post_links = array_unique( $post_links );
  1936. /**
  1937. * Fires just before pinging back links found in a post.
  1938. *
  1939. * @since 2.0.0
  1940. *
  1941. * @param array &$post_links An array of post links to be checked, passed by reference.
  1942. * @param array &$pung Whether a link has already been pinged, passed by reference.
  1943. * @param int $post_ID The post ID.
  1944. */
  1945. do_action_ref_array( 'pre_ping', array( &$post_links, &$pung, $post_ID ) );
  1946. foreach ( (array) $post_links as $pagelinkedto ) {
  1947. $pingback_server_url = discover_pingback_server_uri( $pagelinkedto );
  1948. if ( $pingback_server_url ) {
  1949. @ set_time_limit( 60 );
  1950. // Now, the RPC call
  1951. $pagelinkedfrom = get_permalink($post_ID);
  1952. // using a timeout of 3 seconds should be enough to cover slow servers
  1953. $client = new WP_HTTP_IXR_Client($pingback_server_url);
  1954. $client->timeout = 3;
  1955. /**
  1956. * Filter the user agent sent when pinging-back a URL.
  1957. *
  1958. * @since 2.9.0
  1959. *
  1960. * @param string $concat_useragent The user agent concatenated with ' -- WordPress/'
  1961. * and the WordPress version.
  1962. * @param string $useragent The useragent.
  1963. * @param string $pingback_server_url The server URL being linked to.
  1964. * @param string $pagelinkedto URL of page linked to.
  1965. * @param string $pagelinkedfrom URL of page linked from.
  1966. */
  1967. $client->useragent = apply_filters( 'pingback_useragent', $client->useragent . ' -- WordPress/' . $wp_version, $client->useragent, $pingback_server_url, $pagelinkedto, $pagelinkedfrom );
  1968. // when set to true, this outputs debug messages by itself
  1969. $client->debug = false;
  1970. if ( $client->query('pingback.ping', $pagelinkedfrom, $pagelinkedto) || ( isset($client->error->code) && 48 == $client->error->code ) ) // Already registered
  1971. add_ping( $post_ID, $pagelinkedto );
  1972. }
  1973. }
  1974. }
  1975. /**
  1976. * Check whether blog is public before returning sites.
  1977. *
  1978. * @since 2.1.0
  1979. *
  1980. * @param mixed $sites Will return if blog is public, will not return if not public.
  1981. * @return mixed Empty string if blog is not public, returns $sites, if site is public.
  1982. */
  1983. function privacy_ping_filter($sites) {
  1984. if ( '0' != get_option('blog_public') )
  1985. return $sites;
  1986. else
  1987. return '';
  1988. }
  1989. /**
  1990. * Send a Trackback.
  1991. *
  1992. * Updates database when sending trackback to prevent duplicates.
  1993. *
  1994. * @since 0.71
  1995. * @uses $wpdb
  1996. *
  1997. * @param string $trackback_url URL to send trackbacks.
  1998. * @param string $title Title of post.
  1999. * @param string $excerpt Excerpt of post.
  2000. * @param int $ID Post ID.
  2001. * @return mixed Database query from update.
  2002. */
  2003. function trackback($trackback_url, $title, $excerpt, $ID) {
  2004. global $wpdb;
  2005. if ( empty($trackback_url) )
  2006. return;
  2007. $options = array();
  2008. $options['timeout'] = 4;
  2009. $options['body'] = array(
  2010. 'title' => $title,
  2011. 'url' => get_permalink($ID),
  2012. 'blog_name' => get_option('blogname'),
  2013. 'excerpt' => $excerpt
  2014. );
  2015. $response = wp_safe_remote_post( $trackback_url, $options );
  2016. if ( is_wp_error( $response ) )
  2017. return;
  2018. $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET pinged = CONCAT(pinged, '\n', %s) WHERE ID = %d", $trackback_url, $ID) );
  2019. return $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s, '')) WHERE ID = %d", $trackback_url, $ID) );
  2020. }
  2021. /**
  2022. * Send a pingback.
  2023. *
  2024. * @since 1.2.0
  2025. * @uses $wp_version
  2026. * @uses IXR_Client
  2027. *
  2028. * @param string $server Host of blog to connect to.
  2029. * @param string $path Path to send the ping.
  2030. */
  2031. function weblog_ping($server = '', $path = '') {
  2032. global $wp_version;
  2033. include_once(ABSPATH . WPINC . '/class-IXR.php');
  2034. include_once(ABSPATH . WPINC . '/class-wp-http-ixr-client.php');
  2035. // using a timeout of 3 seconds should be enough to cover slow servers
  2036. $client = new WP_HTTP_IXR_Client($server, ((!strlen(trim($path)) || ('/' == $path)) ? false : $path));
  2037. $client->timeout = 3;
  2038. $client->useragent .= ' -- WordPress/'.$wp_version;
  2039. // when set to true, this outputs debug messages by itself
  2040. $client->debug = false;
  2041. $home = trailingslashit( home_url() );
  2042. if ( !$client->query('weblogUpdates.extendedPing', get_option('blogname'), $home, get_bloginfo('rss2_url') ) ) // then try a normal ping
  2043. $client->query('weblogUpdates.ping', get_option('blogname'), $home);
  2044. }
  2045. /**
  2046. * Default filter attached to pingback_ping_source_uri to validate the pingback's Source URI
  2047. *
  2048. * @since 3.5.1
  2049. * @see wp_http_validate_url()
  2050. *
  2051. * @param string $source_uri
  2052. * @return string
  2053. */
  2054. function pingback_ping_source_uri( $source_uri ) {
  2055. return (string) wp_http_validate_url( $source_uri );
  2056. }
  2057. /**
  2058. * Default filter attached to xmlrpc_pingback_error.
  2059. *
  2060. * Returns a generic pingback error code unless the error code is 48,
  2061. * which reports that the pingback is already registered.
  2062. *
  2063. * @since 3.5.1
  2064. * @link http://www.hixie.ch/specs/pingback/pingback#TOC3
  2065. *
  2066. * @param IXR_Error $ixr_error
  2067. * @return IXR_Error
  2068. */
  2069. function xmlrpc_pingback_error( $ixr_error ) {
  2070. if ( $ixr_error->code === 48 )
  2071. return $ixr_error;
  2072. return new IXR_Error( 0, '' );
  2073. }
  2074. //
  2075. // Cache
  2076. //
  2077. /**
  2078. * Removes comment ID from the comment cache.
  2079. *
  2080. * @since 2.3.0
  2081. *
  2082. * @param int|array $ids Comment ID or array of comment IDs to remove from cache
  2083. */
  2084. function clean_comment_cache($ids) {
  2085. foreach ( (array) $ids as $id )
  2086. wp_cache_delete($id, 'comment');
  2087. wp_cache_set( 'last_changed', microtime(), 'comment' );
  2088. }
  2089. /**
  2090. * Updates the comment cache of given comments.
  2091. *
  2092. * Will add the comments in $comments to the cache. If comment ID already exists
  2093. * in the comment cache then it will not be updated. The comment is added to the
  2094. * cache using the comment group with the key using the ID of the comments.
  2095. *
  2096. * @since 2.3.0
  2097. *
  2098. * @param array $comments Array of comment row objects
  2099. */
  2100. function update_comment_cache($comments) {
  2101. foreach ( (array) $comments as $comment )
  2102. wp_cache_add($comment->comment_ID, $comment, 'comment');
  2103. }
  2104. //
  2105. // Internal
  2106. //
  2107. /**
  2108. * Close comments on old posts on the fly, without any extra DB queries. Hooked to the_posts.
  2109. *
  2110. * @access private
  2111. * @since 2.7.0
  2112. *
  2113. * @param object $posts Post data object.
  2114. * @param object $query Query object.
  2115. * @return object
  2116. */
  2117. function _close_comments_for_old_posts( $posts, $query ) {
  2118. if ( empty( $posts ) || ! $query->is_singular() || ! get_option( 'close_comments_for_old_posts' ) )
  2119. return $posts;
  2120. /**
  2121. * Filter the list of post types to automatically close comments for.
  2122. *
  2123. * @since 3.2.0
  2124. *
  2125. * @param array $post_types An array of registered post types. Default array with 'post'.
  2126. */
  2127. $post_types = apply_filters( 'close_comments_for_post_types', array( 'post' ) );
  2128. if ( ! in_array( $posts[0]->post_type, $post_types ) )
  2129. return $posts;
  2130. $days_old = (int) get_option( 'close_comments_days_old' );
  2131. if ( ! $days_old )
  2132. return $posts;
  2133. if ( time() - strtotime( $posts[0]->post_date_gmt ) > ( $days_old * DAY_IN_SECONDS ) ) {
  2134. $posts[0]->comment_status = 'closed';
  2135. $posts[0]->ping_status = 'closed';
  2136. }
  2137. return $posts;
  2138. }
  2139. /**
  2140. * Close comments on an old post. Hooked to comments_open and pings_open.
  2141. *
  2142. * @access private
  2143. * @since 2.7.0
  2144. *
  2145. * @param bool $open Comments open or closed
  2146. * @param int $post_id Post ID
  2147. * @return bool $open
  2148. */
  2149. function _close_comments_for_old_post( $open, $post_id ) {
  2150. if ( ! $open )
  2151. return $open;
  2152. if ( !get_option('close_comments_for_old_posts') )
  2153. return $open;
  2154. $days_old = (int) get_option('close_comments_days_old');
  2155. if ( !$days_old )
  2156. return $open;
  2157. $post = get_post($post_id);
  2158. /** This filter is documented in wp-includes/comment.php */
  2159. $post_types = apply_filters( 'close_comments_for_post_types', array( 'post' ) );
  2160. if ( ! in_array( $post->post_type, $post_types ) )
  2161. return $open;
  2162. if ( time() - strtotime( $post->post_date_gmt ) > ( $days_old * DAY_IN_SECONDS ) )
  2163. return false;
  2164. return $open;
  2165. }