PageRenderTime 60ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/comment.php

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