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

/wp-includes/comment.php

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