PageRenderTime 32ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/comment.php

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