PageRenderTime 69ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/comment.php

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