PageRenderTime 72ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/comment.php

https://bitbucket.org/aqge/deptandashboard
PHP | 2012 lines | 1011 code | 275 blank | 726 comment | 270 complexity | 17ad1a88a12dbd7831d7ce86d83901ee MD5 | raw file
Possible License(s): AGPL-1.0, GPL-2.0, LGPL-2.1

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * Manages WordPress comments
  4. *
  5. * @package WordPress
  6. * @subpackage Comment
  7. */
  8. /**
  9. * Checks whether a comment passes internal checks to be allowed to add.
  10. *
  11. * If comment moderation is set in the administration, then all comments,
  12. * regardless of their type and whitelist will be set to false. If the number of
  13. * links exceeds the amount in the administration, then the check fails. If any
  14. * of the parameter contents match the blacklist of words, then the check fails.
  15. *
  16. * If the number of links exceeds the amount in the administration, then the
  17. * check fails. If any of the parameter contents match the blacklist of words,
  18. * then the check fails.
  19. *
  20. * If the comment author was approved before, then the comment is
  21. * automatically whitelisted.
  22. *
  23. * If none of the checks fail, then the failback is to set the check to pass
  24. * (return true).
  25. *
  26. * @since 1.2.0
  27. * @uses $wpdb
  28. *
  29. * @param string $author Comment Author's name
  30. * @param string $email Comment Author's email
  31. * @param string $url Comment Author's URL
  32. * @param string $comment Comment contents
  33. * @param string $user_ip Comment Author's IP address
  34. * @param string $user_agent Comment Author's User Agent
  35. * @param string $comment_type Comment type, either user submitted comment,
  36. * trackback, or pingback
  37. * @return bool Whether the checks passed (true) and the comments should be
  38. * displayed or set to moderated
  39. */
  40. function check_comment($author, $email, $url, $comment, $user_ip, $user_agent, $comment_type) {
  41. global $wpdb;
  42. if ( 1 == get_option('comment_moderation') )
  43. return false; // If moderation is set to manual
  44. $comment = apply_filters( 'comment_text', $comment );
  45. // Check # of external links
  46. if ( $max_links = get_option( 'comment_max_links' ) ) {
  47. $num_links = preg_match_all( '/<a [^>]*href/i', $comment, $out );
  48. $num_links = apply_filters( 'comment_max_links_url', $num_links, $url ); // provide for counting of $url as a link
  49. if ( $num_links >= $max_links )
  50. return false;
  51. }
  52. $mod_keys = trim(get_option('moderation_keys'));
  53. if ( !empty($mod_keys) ) {
  54. $words = explode("\n", $mod_keys );
  55. foreach ( (array) $words as $word) {
  56. $word = trim($word);
  57. // Skip empty lines
  58. if ( empty($word) )
  59. continue;
  60. // Do some escaping magic so that '#' chars in the
  61. // spam words don't break things:
  62. $word = preg_quote($word, '#');
  63. $pattern = "#$word#i";
  64. if ( preg_match($pattern, $author) ) return false;
  65. if ( preg_match($pattern, $email) ) return false;
  66. if ( preg_match($pattern, $url) ) return false;
  67. if ( preg_match($pattern, $comment) ) return false;
  68. if ( preg_match($pattern, $user_ip) ) return false;
  69. if ( preg_match($pattern, $user_agent) ) return false;
  70. }
  71. }
  72. // Comment whitelisting:
  73. if ( 1 == get_option('comment_whitelist')) {
  74. if ( 'trackback' != $comment_type && 'pingback' != $comment_type && $author != '' && $email != '' ) {
  75. // expected_slashed ($author, $email)
  76. $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");
  77. if ( ( 1 == $ok_to_comment ) &&
  78. ( empty($mod_keys) || false === strpos( $email, $mod_keys) ) )
  79. return true;
  80. else
  81. return false;
  82. } else {
  83. return false;
  84. }
  85. }
  86. return true;
  87. }
  88. /**
  89. * Retrieve the approved comments for post $post_id.
  90. *
  91. * @since 2.0.0
  92. * @uses $wpdb
  93. *
  94. * @param int $post_id The ID of the post
  95. * @return array $comments The approved comments
  96. */
  97. function get_approved_comments($post_id) {
  98. global $wpdb;
  99. return $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved = '1' ORDER BY comment_date", $post_id));
  100. }
  101. /**
  102. * Retrieves comment data given a comment ID or comment object.
  103. *
  104. * If an object is passed then the comment data will be cached and then returned
  105. * after being passed through a filter. If the comment is empty, then the global
  106. * comment variable will be used, if it is set.
  107. *
  108. * If the comment is empty, then the global comment variable will be used, if it
  109. * is set.
  110. *
  111. * @since 2.0.0
  112. * @uses $wpdb
  113. *
  114. * @param object|string|int $comment Comment to retrieve.
  115. * @param string $output Optional. OBJECT or ARRAY_A or ARRAY_N constants.
  116. * @return object|array|null Depends on $output value.
  117. */
  118. function &get_comment(&$comment, $output = OBJECT) {
  119. global $wpdb;
  120. $null = null;
  121. if ( empty($comment) ) {
  122. if ( isset($GLOBALS['comment']) )
  123. $_comment = & $GLOBALS['comment'];
  124. else
  125. $_comment = null;
  126. } elseif ( is_object($comment) ) {
  127. wp_cache_add($comment->comment_ID, $comment, 'comment');
  128. $_comment = $comment;
  129. } else {
  130. if ( isset($GLOBALS['comment']) && ($GLOBALS['comment']->comment_ID == $comment) ) {
  131. $_comment = & $GLOBALS['comment'];
  132. } elseif ( ! $_comment = wp_cache_get($comment, 'comment') ) {
  133. $_comment = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_ID = %d LIMIT 1", $comment));
  134. if ( ! $_comment )
  135. return $null;
  136. wp_cache_add($_comment->comment_ID, $_comment, 'comment');
  137. }
  138. }
  139. $_comment = apply_filters('get_comment', $_comment);
  140. if ( $output == OBJECT ) {
  141. return $_comment;
  142. } elseif ( $output == ARRAY_A ) {
  143. $__comment = get_object_vars($_comment);
  144. return $__comment;
  145. } elseif ( $output == ARRAY_N ) {
  146. $__comment = array_values(get_object_vars($_comment));
  147. return $__comment;
  148. } else {
  149. return $_comment;
  150. }
  151. }
  152. /**
  153. * Retrieve a list of comments.
  154. *
  155. * The comment list can be for the blog as a whole or for an individual post.
  156. *
  157. * The list of comment arguments are 'status', 'orderby', 'comment_date_gmt',
  158. * 'order', 'number', 'offset', and 'post_id'.
  159. *
  160. * @since 2.7.0
  161. * @uses $wpdb
  162. *
  163. * @param mixed $args Optional. Array or string of options to override defaults.
  164. * @return array List of comments.
  165. */
  166. function get_comments( $args = '' ) {
  167. $query = new WP_Comment_Query;
  168. return $query->query( $args );
  169. }
  170. /**
  171. * WordPress Comment Query class.
  172. *
  173. * @since 3.1.0
  174. */
  175. class WP_Comment_Query {
  176. /**
  177. * Execute the query
  178. *
  179. * @since 3.1.0
  180. *
  181. * @param string|array $query_vars
  182. * @return int|array
  183. */
  184. function query( $query_vars ) {
  185. global $wpdb;
  186. $defaults = array(
  187. 'author_email' => '',
  188. 'ID' => '',
  189. 'karma' => '',
  190. 'number' => '',
  191. 'offset' => '',
  192. 'orderby' => '',
  193. 'order' => 'DESC',
  194. 'parent' => '',
  195. 'post_ID' => '',
  196. 'post_id' => 0,
  197. 'post_author' => '',
  198. 'post_name' => '',
  199. 'post_parent' => '',
  200. 'post_status' => '',
  201. 'post_type' => '',
  202. 'status' => '',
  203. 'type' => '',
  204. 'user_id' => '',
  205. 'search' => '',
  206. 'count' => false
  207. );
  208. $this->query_vars = wp_parse_args( $query_vars, $defaults );
  209. do_action_ref_array( 'pre_get_comments', array( &$this ) );
  210. extract( $this->query_vars, EXTR_SKIP );
  211. // $args can be whatever, only use the args defined in defaults to compute the key
  212. $key = md5( serialize( compact(array_keys($defaults)) ) );
  213. $last_changed = wp_cache_get('last_changed', 'comment');
  214. if ( !$last_changed ) {
  215. $last_changed = time();
  216. wp_cache_set('last_changed', $last_changed, 'comment');
  217. }
  218. $cache_key = "get_comments:$key:$last_changed";
  219. if ( $cache = wp_cache_get( $cache_key, 'comment' ) ) {
  220. return $cache;
  221. }
  222. $post_id = absint($post_id);
  223. if ( 'hold' == $status )
  224. $approved = "comment_approved = '0'";
  225. elseif ( 'approve' == $status )
  226. $approved = "comment_approved = '1'";
  227. elseif ( 'spam' == $status )
  228. $approved = "comment_approved = 'spam'";
  229. elseif ( 'trash' == $status )
  230. $approved = "comment_approved = 'trash'";
  231. else
  232. $approved = "( comment_approved = '0' OR comment_approved = '1' )";
  233. $order = ( 'ASC' == strtoupper($order) ) ? 'ASC' : 'DESC';
  234. if ( ! empty( $orderby ) ) {
  235. $ordersby = is_array($orderby) ? $orderby : preg_split('/[,\s]/', $orderby);
  236. $ordersby = array_intersect(
  237. $ordersby,
  238. array(
  239. 'comment_agent',
  240. 'comment_approved',
  241. 'comment_author',
  242. 'comment_author_email',
  243. 'comment_author_IP',
  244. 'comment_author_url',
  245. 'comment_content',
  246. 'comment_date',
  247. 'comment_date_gmt',
  248. 'comment_ID',
  249. 'comment_karma',
  250. 'comment_parent',
  251. 'comment_post_ID',
  252. 'comment_type',
  253. 'user_id',
  254. )
  255. );
  256. $orderby = empty( $ordersby ) ? 'comment_date_gmt' : implode(', ', $ordersby);
  257. } else {
  258. $orderby = 'comment_date_gmt';
  259. }
  260. $number = absint($number);
  261. $offset = absint($offset);
  262. if ( !empty($number) ) {
  263. if ( $offset )
  264. $limits = 'LIMIT ' . $offset . ',' . $number;
  265. else
  266. $limits = 'LIMIT ' . $number;
  267. } else {
  268. $limits = '';
  269. }
  270. if ( $count )
  271. $fields = 'COUNT(*)';
  272. else
  273. $fields = '*';
  274. $join = '';
  275. $where = $approved;
  276. if ( ! empty($post_id) )
  277. $where .= $wpdb->prepare( ' AND comment_post_ID = %d', $post_id );
  278. if ( '' !== $author_email )
  279. $where .= $wpdb->prepare( ' AND comment_author_email = %s', $author_email );
  280. if ( '' !== $karma )
  281. $where .= $wpdb->prepare( ' AND comment_karma = %d', $karma );
  282. if ( 'comment' == $type ) {
  283. $where .= " AND comment_type = ''";
  284. } elseif( 'pings' == $type ) {
  285. $where .= ' AND comment_type IN ("pingback", "trackback")';
  286. } elseif ( ! empty( $type ) ) {
  287. $where .= $wpdb->prepare( ' AND comment_type = %s', $type );
  288. }
  289. if ( '' !== $parent )
  290. $where .= $wpdb->prepare( ' AND comment_parent = %d', $parent );
  291. if ( '' !== $user_id )
  292. $where .= $wpdb->prepare( ' AND user_id = %d', $user_id );
  293. if ( '' !== $search )
  294. $where .= $this->get_search_sql( $search, array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_content' ) );
  295. $post_fields = array_filter( compact( array( 'post_author', 'post_name', 'post_parent', 'post_status', 'post_type', ) ) );
  296. if ( ! empty( $post_fields ) ) {
  297. $join = "JOIN $wpdb->posts ON $wpdb->posts.ID = $wpdb->comments.comment_post_ID";
  298. foreach( $post_fields as $field_name => $field_value )
  299. $where .= $wpdb->prepare( " AND {$wpdb->posts}.{$field_name} = %s", $field_value );
  300. }
  301. $pieces = array( 'fields', 'join', 'where', 'orderby', 'order', 'limits' );
  302. $clauses = apply_filters_ref_array( 'comments_clauses', array( compact( $pieces ), &$this ) );
  303. foreach ( $pieces as $piece )
  304. $$piece = isset( $clauses[ $piece ] ) ? $clauses[ $piece ] : '';
  305. $query = "SELECT $fields FROM $wpdb->comments $join WHERE $where ORDER BY $orderby $order $limits";
  306. if ( $count )
  307. return $wpdb->get_var( $query );
  308. $comments = $wpdb->get_results( $query );
  309. $comments = apply_filters_ref_array( 'the_comments', array( $comments, &$this ) );
  310. wp_cache_add( $cache_key, $comments, 'comment' );
  311. return $comments;
  312. }
  313. /*
  314. * Used internally to generate an SQL string for searching across multiple columns
  315. *
  316. * @access protected
  317. * @since 3.1.0
  318. *
  319. * @param string $string
  320. * @param array $cols
  321. * @return string
  322. */
  323. function get_search_sql( $string, $cols ) {
  324. $string = esc_sql( like_escape( $string ) );
  325. $searches = array();
  326. foreach ( $cols as $col )
  327. $searches[] = "$col LIKE '%$string%'";
  328. return ' AND (' . implode(' OR ', $searches) . ')';
  329. }
  330. }
  331. /**
  332. * Retrieve all of the WordPress supported comment statuses.
  333. *
  334. * Comments have a limited set of valid status values, this provides the comment
  335. * status values and descriptions.
  336. *
  337. * @package WordPress
  338. * @subpackage Post
  339. * @since 2.7.0
  340. *
  341. * @return array List of comment statuses.
  342. */
  343. function get_comment_statuses( ) {
  344. $status = array(
  345. 'hold' => __('Unapproved'),
  346. /* translators: comment status */
  347. 'approve' => _x('Approved', 'adjective'),
  348. /* translators: comment status */
  349. 'spam' => _x('Spam', 'adjective'),
  350. );
  351. return $status;
  352. }
  353. /**
  354. * The date the last comment was modified.
  355. *
  356. * @since 1.5.0
  357. * @uses $wpdb
  358. * @global array $cache_lastcommentmodified
  359. *
  360. * @param string $timezone Which timezone to use in reference to 'gmt', 'blog',
  361. * or 'server' locations.
  362. * @return string Last comment modified date.
  363. */
  364. function get_lastcommentmodified($timezone = 'server') {
  365. global $cache_lastcommentmodified, $wpdb;
  366. if ( isset($cache_lastcommentmodified[$timezone]) )
  367. return $cache_lastcommentmodified[$timezone];
  368. $add_seconds_server = date('Z');
  369. switch ( strtolower($timezone)) {
  370. case 'gmt':
  371. $lastcommentmodified = $wpdb->get_var("SELECT comment_date_gmt FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
  372. break;
  373. case 'blog':
  374. $lastcommentmodified = $wpdb->get_var("SELECT comment_date FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
  375. break;
  376. case 'server':
  377. $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));
  378. break;
  379. }
  380. $cache_lastcommentmodified[$timezone] = $lastcommentmodified;
  381. return $lastcommentmodified;
  382. }
  383. /**
  384. * The amount of comments in a post or total comments.
  385. *
  386. * A lot like {@link wp_count_comments()}, in that they both return comment
  387. * stats (albeit with different types). The {@link wp_count_comments()} actual
  388. * caches, but this function does not.
  389. *
  390. * @since 2.0.0
  391. * @uses $wpdb
  392. *
  393. * @param int $post_id Optional. Comment amount in post if > 0, else total comments blog wide.
  394. * @return array The amount of spam, approved, awaiting moderation, and total comments.
  395. */
  396. function get_comment_count( $post_id = 0 ) {
  397. global $wpdb;
  398. $post_id = (int) $post_id;
  399. $where = '';
  400. if ( $post_id > 0 ) {
  401. $where = $wpdb->prepare("WHERE comment_post_ID = %d", $post_id);
  402. }
  403. $totals = (array) $wpdb->get_results("
  404. SELECT comment_approved, COUNT( * ) AS total
  405. FROM {$wpdb->comments}
  406. {$where}
  407. GROUP BY comment_approved
  408. ", ARRAY_A);
  409. $comment_count = array(
  410. "approved" => 0,
  411. "awaiting_moderation" => 0,
  412. "spam" => 0,
  413. "total_comments" => 0
  414. );
  415. foreach ( $totals as $row ) {
  416. switch ( $row['comment_approved'] ) {
  417. case 'spam':
  418. $comment_count['spam'] = $row['total'];
  419. $comment_count["total_comments"] += $row['total'];
  420. break;
  421. case 1:
  422. $comment_count['approved'] = $row['total'];
  423. $comment_count['total_comments'] += $row['total'];
  424. break;
  425. case 0:
  426. $comment_count['awaiting_moderation'] = $row['total'];
  427. $comment_count['total_comments'] += $row['total'];
  428. break;
  429. default:
  430. break;
  431. }
  432. }
  433. return $comment_count;
  434. }
  435. //
  436. // Comment meta functions
  437. //
  438. /**
  439. * Add meta data field to a comment.
  440. *
  441. * @since 2.9.0
  442. * @uses add_metadata
  443. * @link http://codex.wordpress.org/Function_Reference/add_comment_meta
  444. *
  445. * @param int $comment_id Comment ID.
  446. * @param string $meta_key Metadata name.
  447. * @param mixed $meta_value Metadata value.
  448. * @param bool $unique Optional, default is false. Whether the same key should not be added.
  449. * @return bool False for failure. True for success.
  450. */
  451. function add_comment_meta($comment_id, $meta_key, $meta_value, $unique = false) {
  452. return add_metadata('comment', $comment_id, $meta_key, $meta_value, $unique);
  453. }
  454. /**
  455. * Remove metadata matching criteria from a comment.
  456. *
  457. * You can match based on the key, or key and value. Removing based on key and
  458. * value, will keep from removing duplicate metadata with the same key. It also
  459. * allows removing all metadata matching key, if needed.
  460. *
  461. * @since 2.9.0
  462. * @uses delete_metadata
  463. * @link http://codex.wordpress.org/Function_Reference/delete_comment_meta
  464. *
  465. * @param int $comment_id comment ID
  466. * @param string $meta_key Metadata name.
  467. * @param mixed $meta_value Optional. Metadata value.
  468. * @return bool False for failure. True for success.
  469. */
  470. function delete_comment_meta($comment_id, $meta_key, $meta_value = '') {
  471. return delete_metadata('comment', $comment_id, $meta_key, $meta_value);
  472. }
  473. /**
  474. * Retrieve comment meta field for a comment.
  475. *
  476. * @since 2.9.0
  477. * @uses get_metadata
  478. * @link http://codex.wordpress.org/Function_Reference/get_comment_meta
  479. *
  480. * @param int $comment_id Comment ID.
  481. * @param string $key The meta key to retrieve.
  482. * @param bool $single Whether to return a single value.
  483. * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
  484. * is true.
  485. */
  486. function get_comment_meta($comment_id, $key, $single = false) {
  487. return get_metadata('comment', $comment_id, $key, $single);
  488. }
  489. /**
  490. * Update comment meta field based on comment ID.
  491. *
  492. * Use the $prev_value parameter to differentiate between meta fields with the
  493. * same key and comment ID.
  494. *
  495. * If the meta field for the comment does not exist, it will be added.
  496. *
  497. * @since 2.9.0
  498. * @uses update_metadata
  499. * @link http://codex.wordpress.org/Function_Reference/update_comment_meta
  500. *
  501. * @param int $comment_id Comment ID.
  502. * @param string $meta_key Metadata key.
  503. * @param mixed $meta_value Metadata value.
  504. * @param mixed $prev_value Optional. Previous value to check before removing.
  505. * @return bool False on failure, true if success.
  506. */
  507. function update_comment_meta($comment_id, $meta_key, $meta_value, $prev_value = '') {
  508. return update_metadata('comment', $comment_id, $meta_key, $meta_value, $prev_value);
  509. }
  510. /**
  511. * Sanitizes the cookies sent to the user already.
  512. *
  513. * Will only do anything if the cookies have already been created for the user.
  514. * Mostly used after cookies had been sent to use elsewhere.
  515. *
  516. * @since 2.0.4
  517. */
  518. function sanitize_comment_cookies() {
  519. if ( isset($_COOKIE['comment_author_'.COOKIEHASH]) ) {
  520. $comment_author = apply_filters('pre_comment_author_name', $_COOKIE['comment_author_'.COOKIEHASH]);
  521. $comment_author = stripslashes($comment_author);
  522. $comment_author = esc_attr($comment_author);
  523. $_COOKIE['comment_author_'.COOKIEHASH] = $comment_author;
  524. }
  525. if ( isset($_COOKIE['comment_author_email_'.COOKIEHASH]) ) {
  526. $comment_author_email = apply_filters('pre_comment_author_email', $_COOKIE['comment_author_email_'.COOKIEHASH]);
  527. $comment_author_email = stripslashes($comment_author_email);
  528. $comment_author_email = esc_attr($comment_author_email);
  529. $_COOKIE['comment_author_email_'.COOKIEHASH] = $comment_author_email;
  530. }
  531. if ( isset($_COOKIE['comment_author_url_'.COOKIEHASH]) ) {
  532. $comment_author_url = apply_filters('pre_comment_author_url', $_COOKIE['comment_author_url_'.COOKIEHASH]);
  533. $comment_author_url = stripslashes($comment_author_url);
  534. $_COOKIE['comment_author_url_'.COOKIEHASH] = $comment_author_url;
  535. }
  536. }
  537. /**
  538. * Validates whether this comment is allowed to be made.
  539. *
  540. * @since 2.0.0
  541. * @uses $wpdb
  542. * @uses apply_filters() Calls 'pre_comment_approved' hook on the type of comment
  543. * @uses apply_filters() Calls 'comment_duplicate_trigger' hook on commentdata.
  544. * @uses do_action() Calls 'check_comment_flood' hook on $comment_author_IP, $comment_author_email, and $comment_date_gmt
  545. *
  546. * @param array $commentdata Contains information on the comment
  547. * @return mixed Signifies the approval status (0|1|'spam')
  548. */
  549. function wp_allow_comment($commentdata) {
  550. global $wpdb;
  551. extract($commentdata, EXTR_SKIP);
  552. // Simple duplicate check
  553. // expected_slashed ($comment_post_ID, $comment_author, $comment_author_email, $comment_content)
  554. $dupe = "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = '$comment_post_ID' AND comment_approved != 'trash' AND ( comment_author = '$comment_author' ";
  555. if ( $comment_author_email )
  556. $dupe .= "OR comment_author_email = '$comment_author_email' ";
  557. $dupe .= ") AND comment_content = '$comment_content' LIMIT 1";
  558. if ( $wpdb->get_var($dupe) ) {
  559. do_action( 'comment_duplicate_trigger', $commentdata );
  560. if ( defined('DOING_AJAX') )
  561. die( __('Duplicate comment detected; it looks as though you&#8217;ve already said that!') );
  562. wp_die( __('Duplicate comment detected; it looks as though you&#8217;ve already said that!') );
  563. }
  564. do_action( 'check_comment_flood', $comment_author_IP, $comment_author_email, $comment_date_gmt );
  565. if ( isset($user_id) && $user_id) {
  566. $userdata = get_userdata($user_id);
  567. $user = new WP_User($user_id);
  568. $post_author = $wpdb->get_var($wpdb->prepare("SELECT post_author FROM $wpdb->posts WHERE ID = %d LIMIT 1", $comment_post_ID));
  569. }
  570. if ( isset($userdata) && ( $user_id == $post_author || $user->has_cap('moderate_comments') ) ) {
  571. // The author and the admins get respect.
  572. $approved = 1;
  573. } else {
  574. // Everyone else's comments will be checked.
  575. if ( check_comment($comment_author, $comment_author_email, $comment_author_url, $comment_content, $comment_author_IP, $comment_agent, $comment_type) )
  576. $approved = 1;
  577. else
  578. $approved = 0;
  579. if ( wp_blacklist_check($comment_author, $comment_author_email, $comment_author_url, $comment_content, $comment_author_IP, $comment_agent) )
  580. $approved = 'spam';
  581. }
  582. $approved = apply_filters( 'pre_comment_approved', $approved, $commentdata );
  583. return $approved;
  584. }
  585. /**
  586. * Check whether comment flooding is occurring.
  587. *
  588. * Won't run, if current user can manage options, so to not block
  589. * administrators.
  590. *
  591. * @since 2.3.0
  592. * @uses $wpdb
  593. * @uses apply_filters() Calls 'comment_flood_filter' filter with first
  594. * parameter false, last comment timestamp, new comment timestamp.
  595. * @uses do_action() Calls 'comment_flood_trigger' action with parameters with
  596. * last comment timestamp and new comment timestamp.
  597. *
  598. * @param string $ip Comment IP.
  599. * @param string $email Comment author email address.
  600. * @param string $date MySQL time string.
  601. */
  602. function check_comment_flood_db( $ip, $email, $date ) {
  603. global $wpdb;
  604. if ( current_user_can( 'manage_options' ) )
  605. return; // don't throttle admins
  606. $hour_ago = gmdate( 'Y-m-d H:i:s', time() - 3600 );
  607. 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 ) ) ) {
  608. $time_lastcomment = mysql2date('U', $lasttime, false);
  609. $time_newcomment = mysql2date('U', $date, false);
  610. $flood_die = apply_filters('comment_flood_filter', false, $time_lastcomment, $time_newcomment);
  611. if ( $flood_die ) {
  612. do_action('comment_flood_trigger', $time_lastcomment, $time_newcomment);
  613. if ( defined('DOING_AJAX') )
  614. die( __('You are posting comments too quickly. Slow down.') );
  615. wp_die( __('You are posting comments too quickly. Slow down.'), '', array('response' => 403) );
  616. }
  617. }
  618. }
  619. /**
  620. * Separates an array of comments into an array keyed by comment_type.
  621. *
  622. * @since 2.7.0
  623. *
  624. * @param array $comments Array of comments
  625. * @return array Array of comments keyed by comment_type.
  626. */
  627. function &separate_comments(&$comments) {
  628. $comments_by_type = array('comment' => array(), 'trackback' => array(), 'pingback' => array(), 'pings' => array());
  629. $count = count($comments);
  630. for ( $i = 0; $i < $count; $i++ ) {
  631. $type = $comments[$i]->comment_type;
  632. if ( empty($type) )
  633. $type = 'comment';
  634. $comments_by_type[$type][] = &$comments[$i];
  635. if ( 'trackback' == $type || 'pingback' == $type )
  636. $comments_by_type['pings'][] = &$comments[$i];
  637. }
  638. return $comments_by_type;
  639. }
  640. /**
  641. * Calculate the total number of comment pages.
  642. *
  643. * @since 2.7.0
  644. * @uses get_query_var() Used to fill in the default for $per_page parameter.
  645. * @uses get_option() Used to fill in defaults for parameters.
  646. * @uses Walker_Comment
  647. *
  648. * @param array $comments Optional array of comment objects. Defaults to $wp_query->comments
  649. * @param int $per_page Optional comments per page.
  650. * @param boolean $threaded Optional control over flat or threaded comments.
  651. * @return int Number of comment pages.
  652. */
  653. function get_comment_pages_count( $comments = null, $per_page = null, $threaded = null ) {
  654. global $wp_query;
  655. if ( null === $comments && null === $per_page && null === $threaded && !empty($wp_query->max_num_comment_pages) )
  656. return $wp_query->max_num_comment_pages;
  657. if ( !$comments || !is_array($comments) )
  658. $comments = $wp_query->comments;
  659. if ( empty($comments) )
  660. return 0;
  661. if ( !isset($per_page) )
  662. $per_page = (int) get_query_var('comments_per_page');
  663. if ( 0 === $per_page )
  664. $per_page = (int) get_option('comments_per_page');
  665. if ( 0 === $per_page )
  666. return 1;
  667. if ( !isset($threaded) )
  668. $threaded = get_option('thread_comments');
  669. if ( $threaded ) {
  670. $walker = new Walker_Comment;
  671. $count = ceil( $walker->get_number_of_root_elements( $comments ) / $per_page );
  672. } else {
  673. $count = ceil( count( $comments ) / $per_page );
  674. }
  675. return $count;
  676. }
  677. /**
  678. * Calculate what page number a comment will appear on for comment paging.
  679. *
  680. * @since 2.7.0
  681. * @uses get_comment() Gets the full comment of the $comment_ID parameter.
  682. * @uses get_option() Get various settings to control function and defaults.
  683. * @uses get_page_of_comment() Used to loop up to top level comment.
  684. *
  685. * @param int $comment_ID Comment ID.
  686. * @param array $args Optional args.
  687. * @return int|null Comment page number or null on error.
  688. */
  689. function get_page_of_comment( $comment_ID, $args = array() ) {
  690. global $wpdb;
  691. if ( !$comment = get_comment( $comment_ID ) )
  692. return;
  693. $defaults = array( 'type' => 'all', 'page' => '', 'per_page' => '', 'max_depth' => '' );
  694. $args = wp_parse_args( $args, $defaults );
  695. if ( '' === $args['per_page'] && get_option('page_comments') )
  696. $args['per_page'] = get_query_var('comments_per_page');
  697. if ( empty($args['per_page']) ) {
  698. $args['per_page'] = 0;
  699. $args['page'] = 0;
  700. }
  701. if ( $args['per_page'] < 1 )
  702. return 1;
  703. if ( '' === $args['max_depth'] ) {
  704. if ( get_option('thread_comments') )
  705. $args['max_depth'] = get_option('thread_comments_depth');
  706. else
  707. $args['max_depth'] = -1;
  708. }
  709. // Find this comment's top level parent if threading is enabled
  710. if ( $args['max_depth'] > 1 && 0 != $comment->comment_parent )
  711. return get_page_of_comment( $comment->comment_parent, $args );
  712. $allowedtypes = array(
  713. 'comment' => '',
  714. 'pingback' => 'pingback',
  715. 'trackback' => 'trackback',
  716. );
  717. $comtypewhere = ( 'all' != $args['type'] && isset($allowedtypes[$args['type']]) ) ? " AND comment_type = '" . $allowedtypes[$args['type']] . "'" : '';
  718. // Count comments older than this one
  719. $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 ) );
  720. // No older comments? Then it's page #1.
  721. if ( 0 == $oldercoms )
  722. return 1;
  723. // Divide comments older than this one by comments per page to get this comment's page number
  724. return ceil( ( $oldercoms + 1 ) / $args['per_page'] );
  725. }
  726. /**
  727. * Does comment contain blacklisted characters or words.
  728. *
  729. * @since 1.5.0
  730. * @uses do_action() Calls 'wp_blacklist_check' hook for all parameters.
  731. *
  732. * @param string $author The author of the comment
  733. * @param string $email The email of the comment
  734. * @param string $url The url used in the comment
  735. * @param string $comment The comment content
  736. * @param string $user_ip The comment author IP address
  737. * @param string $user_agent The author's browser user agent
  738. * @return bool True if comment contains blacklisted content, false if comment does not
  739. */
  740. function wp_blacklist_check($author, $email, $url, $comment, $user_ip, $user_agent) {
  741. do_action('wp_blacklist_check', $author, $email, $url, $comment, $user_ip, $user_agent);
  742. $mod_keys = trim( get_option('blacklist_keys') );
  743. if ( '' == $mod_keys )
  744. return false; // If moderation keys are empty
  745. $words = explode("\n", $mod_keys );
  746. foreach ( (array) $words as $word ) {
  747. $word = trim($word);
  748. // Skip empty lines
  749. if ( empty($word) ) { continue; }
  750. // Do some escaping magic so that '#' chars in the
  751. // spam words don't break things:
  752. $word = preg_quote($word, '#');
  753. $pattern = "#$word#i";
  754. if (
  755. preg_match($pattern, $author)
  756. || preg_match($pattern, $email)
  757. || preg_match($pattern, $url)
  758. || preg_match($pattern, $comment)
  759. || preg_match($pattern, $user_ip)
  760. || preg_match($pattern, $user_agent)
  761. )
  762. return true;
  763. }
  764. return false;
  765. }
  766. /**
  767. * Retrieve total comments for blog or single post.
  768. *
  769. * The properties of the returned object contain the 'moderated', 'approved',
  770. * and spam comments for either the entire blog or single post. Those properties
  771. * contain the amount of comments that match the status. The 'total_comments'
  772. * property contains the integer of total comments.
  773. *
  774. * The comment stats are cached and then retrieved, if they already exist in the
  775. * cache.
  776. *
  777. * @since 2.5.0
  778. *
  779. * @param int $post_id Optional. Post ID.
  780. * @return object Comment stats.
  781. */
  782. function wp_count_comments( $post_id = 0 ) {
  783. global $wpdb;
  784. $post_id = (int) $post_id;
  785. $stats = apply_filters('wp_count_comments', array(), $post_id);
  786. if ( !empty($stats) )
  787. return $stats;
  788. $count = wp_cache_get("comments-{$post_id}", 'counts');
  789. if ( false !== $count )
  790. return $count;
  791. $where = '';
  792. if ( $post_id > 0 )
  793. $where = $wpdb->prepare( "WHERE comment_post_ID = %d", $post_id );
  794. $count = $wpdb->get_results( "SELECT comment_approved, COUNT( * ) AS num_comments FROM {$wpdb->comments} {$where} GROUP BY comment_approved", ARRAY_A );
  795. $total = 0;
  796. $approved = array('0' => 'moderated', '1' => 'approved', 'spam' => 'spam', 'trash' => 'trash', 'post-trashed' => 'post-trashed');
  797. foreach ( (array) $count as $row ) {
  798. // Don't count post-trashed toward totals
  799. if ( 'post-trashed' != $row['comment_approved'] && 'trash' != $row['comment_approved'] )
  800. $total += $row['num_comments'];
  801. if ( isset( $approved[$row['comment_approved']] ) )
  802. $stats[$approved[$row['comment_approved']]] = $row['num_comments'];
  803. }
  804. $stats['total_comments'] = $total;
  805. foreach ( $approved as $key ) {
  806. if ( empty($stats[$key]) )
  807. $stats[$key] = 0;
  808. }
  809. $stats = (object) $stats;
  810. wp_cache_set("comments-{$post_id}", $stats, 'counts');
  811. return $stats;
  812. }
  813. /**
  814. * Trashes or deletes a comment.
  815. *
  816. * The comment is moved to trash instead of permanently deleted unless trash is
  817. * disabled, item is already in the trash, or $force_delete is true.
  818. *
  819. * The post comment count will be updated if the comment was approved and has a
  820. * post ID available.
  821. *
  822. * @since 2.0.0
  823. * @uses $wpdb
  824. * @uses do_action() Calls 'delete_comment' hook on comment ID
  825. * @uses do_action() Calls 'deleted_comment' hook on comment ID after deletion, on success
  826. * @uses do_action() Calls 'wp_set_comment_status' hook on comment ID with 'delete' set for the second parameter
  827. * @uses wp_transition_comment_status() Passes new and old comment status along with $comment object
  828. *
  829. * @param int $comment_id Comment ID
  830. * @param bool $force_delete Whether to bypass trash and force deletion. Default is false.
  831. * @return bool False if delete comment query failure, true on success.
  832. */
  833. function wp_delete_comment($comment_id, $force_delete = false) {
  834. global $wpdb;
  835. if (!$comment = get_comment($comment_id))
  836. return false;
  837. if ( !$force_delete && EMPTY_TRASH_DAYS && !in_array( wp_get_comment_status($comment_id), array( 'trash', 'spam' ) ) )
  838. return wp_trash_comment($comment_id);
  839. do_action('delete_comment', $comment_id);
  840. // Move children up a level.
  841. $children = $wpdb->get_col( $wpdb->prepare("SELECT comment_ID FROM $wpdb->comments WHERE comment_parent = %d", $comment_id) );
  842. if ( !empty($children) ) {
  843. $wpdb->update($wpdb->comments, array('comment_parent' => $comment->comment_parent), array('comment_parent' => $comment_id));
  844. clean_comment_cache($children);
  845. }
  846. // Delete metadata
  847. $meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->commentmeta WHERE comment_id = %d ", $comment_id ) );
  848. if ( !empty($meta_ids) ) {
  849. do_action( 'delete_commentmeta', $meta_ids );
  850. $in_meta_ids = "'" . implode("', '", $meta_ids) . "'";
  851. $wpdb->query( "DELETE FROM $wpdb->commentmeta WHERE meta_id IN ($in_meta_ids)" );
  852. do_action( 'deleted_commentmeta', $meta_ids );
  853. }
  854. if ( ! $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->comments WHERE comment_ID = %d LIMIT 1", $comment_id) ) )
  855. return false;
  856. do_action('deleted_comment', $comment_id);
  857. $post_id = $comment->comment_post_ID;
  858. if ( $post_id && $comment->comment_approved == 1 )
  859. wp_update_comment_count($post_id);
  860. clean_comment_cache($comment_id);
  861. do_action('wp_set_comment_status', $comment_id, 'delete');
  862. wp_transition_comment_status('delete', $comment->comment_approved, $comment);
  863. return true;
  864. }
  865. /**
  866. * Moves a comment to the Trash
  867. *
  868. * If trash is disabled, comment is permanently deleted.
  869. *
  870. * @since 2.9.0
  871. * @uses do_action() on 'trash_comment' before trashing
  872. * @uses do_action() on 'trashed_comment' after trashing
  873. * @uses wp_delete_comment() if trash is disabled
  874. *
  875. * @param int $comment_id Comment ID.
  876. * @return mixed False on failure
  877. */
  878. function wp_trash_comment($comment_id) {
  879. if ( !EMPTY_TRASH_DAYS )
  880. return wp_delete_comment($comment_id, true);
  881. if ( !$comment = get_comment($comment_id) )
  882. return false;
  883. do_action('trash_comment', $comment_id);
  884. if ( wp_set_comment_status($comment_id, 'trash') ) {
  885. add_comment_meta($comment_id, '_wp_trash_meta_status', $comment->comment_approved);
  886. add_comment_meta($comment_id, '_wp_trash_meta_time', time() );
  887. do_action('trashed_comment', $comment_id);
  888. return true;
  889. }
  890. return false;
  891. }
  892. /**
  893. * Removes a comment from the Trash
  894. *
  895. * @since 2.9.0
  896. * @uses do_action() on 'untrash_comment' before untrashing
  897. * @uses do_action() on 'untrashed_comment' after untrashing
  898. *
  899. * @param int $comment_id Comment ID.
  900. * @return mixed False on failure
  901. */
  902. function wp_untrash_comment($comment_id) {
  903. if ( ! (int)$comment_id )
  904. return false;
  905. do_action('untrash_comment', $comment_id);
  906. $status = (string) get_comment_meta($comment_id, '_wp_trash_meta_status', true);
  907. if ( empty($status) )
  908. $status = '0';
  909. if ( wp_set_comment_status($comment_id, $status) ) {
  910. delete_comment_meta($comment_id, '_wp_trash_meta_time');
  911. delete_comment_meta($comment_id, '_wp_trash_meta_status');
  912. do_action('untrashed_comment', $comment_id);
  913. return true;
  914. }
  915. return false;
  916. }
  917. /**
  918. * Marks a comment as Spam
  919. *
  920. * @since 2.9.0
  921. * @uses do_action() on 'spam_comment' before spamming
  922. * @uses do_action() on 'spammed_comment' after spamming
  923. *
  924. * @param int $comment_id Comment ID.
  925. * @return mixed False on failure
  926. */
  927. function wp_spam_comment($comment_id) {
  928. if ( !$comment = get_comment($comment_id) )
  929. return false;
  930. do_action('spam_comment', $comment_id);
  931. if ( wp_set_comment_status($comment_id, 'spam') ) {
  932. add_comment_meta($comment_id, '_wp_trash_meta_status', $comment->comment_approved);
  933. do_action('spammed_comment', $comment_id);
  934. return true;
  935. }
  936. return false;
  937. }
  938. /**
  939. * Removes a comment from the Spam
  940. *
  941. * @since 2.9.0
  942. * @uses do_action() on 'unspam_comment' before unspamming
  943. * @uses do_action() on 'unspammed_comment' after unspamming
  944. *
  945. * @param int $comment_id Comment ID.
  946. * @return mixed False on failure
  947. */
  948. function wp_unspam_comment($comment_id) {
  949. if ( ! (int)$comment_id )
  950. return false;
  951. do_action('unspam_comment', $comment_id);
  952. $status = (string) get_comment_meta($comment_id, '_wp_trash_meta_status', true);
  953. if ( empty($status) )
  954. $status = '0';
  955. if ( wp_set_comment_status($comment_id, $status) ) {
  956. delete_comment_meta($comment_id, '_wp_trash_meta_status');
  957. do_action('unspammed_comment', $comment_id);
  958. return true;
  959. }
  960. return false;
  961. }
  962. /**
  963. * The status of a comment by ID.
  964. *
  965. * @since 1.0.0
  966. *
  967. * @param int $comment_id Comment ID
  968. * @return string|bool Status might be 'trash', 'approved', 'unapproved', 'spam'. False on failure.
  969. */
  970. function wp_get_comment_status($comment_id) {
  971. $comment = get_comment($comment_id);
  972. if ( !$comment )
  973. return false;
  974. $approved = $comment->comment_approved;
  975. if ( $approved == NULL )
  976. return false;
  977. elseif ( $approved == '1' )
  978. return 'approved';
  979. elseif ( $approved == '0' )
  980. return 'unapproved';
  981. elseif ( $approved == 'spam' )
  982. return 'spam';
  983. elseif ( $approved == 'trash' )
  984. return 'trash';
  985. else
  986. return false;
  987. }
  988. /**
  989. * Call hooks for when a comment status transition occurs.
  990. *
  991. * Calls hooks for comment status transitions. If the new comment status is not the same
  992. * as the previous comment status, then two hooks will be ran, the first is
  993. * 'transition_comment_status' with new status, old status, and comment data. The
  994. * next action called is 'comment_OLDSTATUS_to_NEWSTATUS' the NEWSTATUS is the
  995. * $new_status parameter and the OLDSTATUS is $old_status parameter; it has the
  996. * comment data.
  997. *
  998. * The final action will run whether or not the comment statuses are the same. The
  999. * action is named 'comment_NEWSTATUS_COMMENTTYPE', NEWSTATUS is from the $new_status
  1000. * parameter and COMMENTTYPE is comment_type comment data.
  1001. *
  1002. * @since 2.7.0
  1003. *
  1004. * @param string $new_status New comment status.
  1005. * @param string $old_status Previous comment status.
  1006. * @param object $comment Comment data.
  1007. */
  1008. function wp_transition_comment_status($new_status, $old_status, $comment) {
  1009. // Translate raw statuses to human readable formats for the hooks
  1010. // This is not a complete list of comment status, it's only the ones that need to be renamed
  1011. $comment_statuses = array(
  1012. 0 => 'unapproved',
  1013. 'hold' => 'unapproved', // wp_set_comment_status() uses "hold"
  1014. 1 => 'approved',
  1015. 'approve' => 'approved', // wp_set_comment_status() uses "approve"
  1016. );
  1017. if ( isset($comment_statuses[$new_status]) ) $new_status = $comment_statuses[$new_status];
  1018. if ( isset($comment_statuses[$old_status]) ) $old_status = $comment_statuses[$old_status];
  1019. // Call the hooks
  1020. if ( $new_status != $old_status ) {
  1021. do_action('transition_comment_status', $new_status, $old_status, $comment);
  1022. do_action("comment_{$old_status}_to_{$new_status}", $comment);
  1023. }
  1024. do_action("comment_{$new_status}_{$comment->comment_type}", $comment->comment_ID, $comment);
  1025. }
  1026. /**
  1027. * Get current commenter's name, email, and URL.
  1028. *
  1029. * Expects cookies content to already be sanitized. User of this function might
  1030. * wish to recheck the returned array for validity.
  1031. *
  1032. * @see sanitize_comment_cookies() Use to sanitize cookies
  1033. *
  1034. * @since 2.0.4
  1035. *
  1036. * @return array Comment author, email, url respectively.
  1037. */
  1038. function wp_get_current_commenter() {
  1039. // Cookies should already be sanitized.
  1040. $comment_author = '';
  1041. if ( isset($_COOKIE['comment_author_'.COOKIEHASH]) )
  1042. $comment_author = $_COOKIE['comment_author_'.COOKIEHASH];
  1043. $comment_author_email = '';
  1044. if ( isset($_COOKIE['comment_author_email_'.COOKIEHASH]) )
  1045. $comment_author_email = $_COOKIE['comment_author_email_'.COOKIEHASH];
  1046. $comment_author_url = '';
  1047. if ( isset($_COOKIE['comment_author_url_'.COOKIEHASH]) )
  1048. $comment_author_url = $_COOKIE['comment_author_url_'.COOKIEHASH];
  1049. return apply_filters('wp_get_current_commenter', compact('comment_author', 'comment_author_email', 'comment_author_url'));
  1050. }
  1051. /**
  1052. * Inserts a comment to the database.
  1053. *
  1054. * The available comment data key names are 'comment_author_IP', 'comment_date',
  1055. * 'comment_date_gmt', 'comment_parent', 'comment_approved', and 'user_id'.
  1056. *
  1057. * @since 2.0.0
  1058. * @uses $wpdb
  1059. *
  1060. * @param array $commentdata Contains information on the comment.
  1061. * @return int The new comment's ID.
  1062. */
  1063. function wp_insert_comment($commentdata) {
  1064. global $wpdb;
  1065. extract(stripslashes_deep($commentdata), EXTR_SKIP);
  1066. if ( ! isset($comment_author_IP) )
  1067. $comment_author_IP = '';
  1068. if ( ! isset($comment_date) )
  1069. $comment_date = current_time('mysql');
  1070. if ( ! isset($comment_date_gmt) )
  1071. $comment_date_gmt = get_gmt_from_date($comment_date);
  1072. if ( ! isset($comment_parent) )
  1073. $comment_parent = 0;
  1074. if ( ! isset($comment_approved) )
  1075. $comment_approved = 1;
  1076. if ( ! isset($comment_karma) )
  1077. $comment_karma = 0;
  1078. if ( ! isset($user_id) )
  1079. $user_id = 0;
  1080. if ( ! isset($comment_type) )
  1081. $comment_type = '';
  1082. $data = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_date', 'comment_date_gmt', 'comment_content', 'comment_karma', 'comment_approved', 'comment_agent', 'comment_type', 'comment_parent', 'user_id');
  1083. $wpdb->insert($wpdb->comments, $data);
  1084. $id = (int) $wpdb->insert_id;
  1085. if ( $comment_approved == 1 )
  1086. wp_update_comment_count($comment_post_ID);
  1087. $comment = get_comment($id);
  1088. do_action('wp_insert_comment', $id, $comment);
  1089. return $id;
  1090. }
  1091. /**
  1092. * Filters and sanitizes comment data.
  1093. *
  1094. * Sets the comment data 'filtered' field to true when finished. This can be
  1095. * checked as to whether the comment should be filtered and to keep from
  1096. * filtering the same comment more than once.
  1097. *
  1098. * @since 2.0.0
  1099. * @uses apply_filters() Calls 'pre_user_id' hook on comment author's user ID
  1100. * @uses apply_filters() Calls 'pre_comment_user_agent' hook on comment author's user agent
  1101. * @uses apply_filters() Calls 'pre_comment_author_name' hook on comment author's name
  1102. * @uses apply_filters() Calls 'pre_comment_content' hook on the comment's content
  1103. * @uses apply_filters() Calls 'pre_comment_user_ip' hook on comment author's IP
  1104. * @uses apply_filters() Calls 'pre_comment_author_url' hook on comment author's URL
  1105. * @uses apply_filters() Calls 'pre_comment_author_email' hook on comment author's email address
  1106. *
  1107. * @param array $commentdata Contains information on the comment.
  1108. * @return array Parsed comment information.
  1109. */
  1110. function wp_filter_comment($commentdata) {
  1111. if ( isset($commentdata['user_ID']) )
  1112. $commentdata['user_id'] = apply_filters('pre_user_id', $commentdata['user_ID']);
  1113. elseif ( isset($commentdata['user_id']) )
  1114. $commentdata['user_id'] = apply_filters('pre_user_id', $commentdata['user_id']);
  1115. $commentdata['comment_agent'] = apply_filters('pre_comment_user_agent', ( isset( $commentdata['comment_agent'] ) ? $commentdata['comment_agent'] : '' ) );
  1116. $commentdata['comment_author'] = apply_filters('pre_comment_author_name', $commentdata['comment_author']);
  1117. $commentdata['comment_content'] = apply_filters('pre_comment_content', $commentdata['comment_content']);
  1118. $commentdata['comment_author_IP'] = apply_filters('pre_comment_user_ip', $commentdata['comment_author_IP']);
  1119. $commentdata['comment_author_url'] = apply_filters('pre_comment_author_url', $commentdata['comment_author_url']);
  1120. $commentdata['comment_author_email'] = apply_filters('pre_comment_author_email', $commentdata['comment_author_email']);
  1121. $commentdata['filtered'] = true;
  1122. return $commentdata;
  1123. }
  1124. /**
  1125. * Whether comment should be blocked because of comment flood.
  1126. *
  1127. * @since 2.1.0
  1128. *
  1129. * @param bool $block Whether plugin has already blocked comment.
  1130. * @param int $time_lastcomment Timestamp for last comment.
  1131. * @param int $time_newcomment Timestamp for new comment.
  1132. * @return bool Whether comment should be blocked.
  1133. */
  1134. function wp_throttle_comment_flood($block, $time_lastcomment, $time_newcomment) {
  1135. if ( $block ) // a plugin has already blocked... we'll let that decision stand
  1136. return $block;
  1137. if ( ($time_newcomment - $time_lastcomment) < 15 )
  1138. return true;
  1139. return false;
  1140. }
  1141. /**
  1142. * Adds a new comment to the database.
  1143. *
  1144. * Filters new comment to ensure that the fields are sanitized and valid before
  1145. * inserting comment into database. Calls 'comment_post' action with comment ID
  1146. * and whether comment is approved by WordPress. Also has 'preprocess_comment'
  1147. * filter for processing the comment data before the function handles it.
  1148. *
  1149. * We use REMOTE_ADDR here directly. If you are behind a proxy, you should ensure
  1150. * that it is properly set, such as in wp-config.php, for your environment.
  1151. * See {@link http://core.trac.wordpress.org/ticket/9235}
  1152. *
  1153. * @since 1.5.0
  1154. * @uses apply_filters() Calls 'preprocess_comment' hook on $commentdata parameter array before processing
  1155. * @uses do_action() Calls 'comment_post' hook on $comment_ID returned from adding the comment and if the comment was approved.
  1156. * @uses wp_filter_comment() Used to filter comment before adding comment.
  1157. * @uses wp_allow_comment() checks to see if comment is approved.
  1158. * @uses wp_insert_comment() Does the actual comment insertion to the database.
  1159. *
  1160. * @param array $commentdata Contains information on the comment.
  1161. * @return int The ID of the comment after adding.
  1162. */
  1163. function wp_new_comment( $commentdata ) {
  1164. $commentdata = apply_filters('preprocess_comment', $commentdata);
  1165. $commentdata['comment_post_ID'] = (int) $commentdata['comment_post_ID'];
  1166. if ( isset($commentdata['user_ID']) )
  1167. $commentdata['user_id'] = $commentdata['user_ID'] = (int) $commentdata['user_ID'];
  1168. elseif ( isset($commentdata['user_id']) )
  1169. $commentdata['user_id'] = (int) $commentdata['user_id'];
  1170. $commentdata['comment_parent'] = isset($commentdata['comment_parent']) ? absint($commentdata['comment_parent']) : 0;
  1171. $parent_status = ( 0 < $commentdata['comment_parent'] ) ? wp_get_comment_status($commentdata['comment_parent']) : '';
  1172. $commentdata['comment_parent'] = ( 'approved' == $parent_status || 'unapproved' == $parent_status ) ? $commentdata['comment_parent'] : 0;
  1173. $commentdata['comment_author_IP'] = preg_replace( '/[^0-9a-fA-F:., ]/', '',$_SERVER['REMOTE_ADDR'] );
  1174. $commentdata['comment_agent'] = substr($_SERVER['HTTP_USER_AGENT'], 0, 254);
  1175. $commentdata['comment_date'] = current_time('mysql');
  1176. $commentdata['comment_date_gmt'] = current_time('mysql', 1);
  1177. $commentdata = wp_filter_comment($commentdata);
  1178. $commentdata['comment_approved'] = wp_allow_comment($commentdata);
  1179. $comment_ID = wp_insert_comment($commentdata);
  1180. do_action('comment_post', $comment_ID, $commentdata['comment_approved']);
  1181. if ( 'spam' !== $commentdata['comment_approved'] ) { // If it's spam save it silently for later crunching
  1182. if ( '0' == $commentdata['comment_approved'] )
  1183. wp_notify_moderator($comment_ID);
  1184. $post = &get_post($commentdata['comment_post_ID']); // Don't notify if it's your own comment
  1185. if ( get_option('comments_notify') && $commentdata['comment_approved'] && ( ! isset( $commentdata['user_id'] ) || $post->post_author != $commentdata['user_id'] ) )
  1186. wp_notify_postauthor($comment_ID, isset( $commentdata['comment_type'] ) ? $commentdata['comment_type'] : '' );
  1187. }
  1188. return $comment_ID;
  1189. }
  1190. /**
  1191. * Sets the status of a comment.
  1192. *
  1193. * The 'wp_set_comment_status' action is called after the comment is handled and
  1194. * will only be called, if the comment status is either 'hold', 'approve', or
  1195. * 'spam'. If the comment status is not in the list, then false is returned and
  1196. * if the status is 'delete', then the comment is deleted without calling the
  1197. * action.
  1198. *
  1199. * @since 1.0.0
  1200. * @uses wp_transition_comment_status() Passes new and old comment status along with $comment object
  1201. *
  1202. * @param int $comment_id Comment ID.
  1203. * @param string $comment_status New comment status, either 'hold', 'approve', 'spam', or 'delete'.
  1204. * @param bool $wp_error Whether to return a WP_Error object if there is a failure. Default is false.
  1205. * @return bool False on failure or deletion and true on success.
  1206. */
  1207. function wp_set_comment_status($comment_id, $comment_status, $wp_error = false) {
  1208. global $wpdb;
  1209. $status = '0';
  1210. switch ( $comment_status ) {
  1211. case 'hold':
  1212. case '0':
  1213. $status = '0';
  1214. break;
  1215. case 'approve':
  1216. case '1':
  1217. $status = '1';
  1218. if ( get_option('comments_notify') ) {
  1219. $comment = get_comment($comment_id);
  1220. wp_notify_postauthor($comment_id, $comment->comment_type);
  1221. }
  1222. break;
  1223. case 'spam':
  1224. $status = 'spam';
  1225. break;
  1226. case 'trash':
  1227. $status = 'trash';
  1228. break;
  1229. default:
  1230. return false;
  1231. }
  1232. $comment_old = clone get_comment($comment_id);
  1233. if ( !$wpdb->update( $wpdb->comments, array('comment_approved' => $status), array('comment_ID' => $comment_id) ) ) {
  1234. if ( $wp_error )
  1235. return new WP_Error('db_update_error', __('Could not update comment status'), $wpdb->last_error);
  1236. else
  1237. return false;
  1238. }
  1239. clean_comment_cache($comment_id);
  1240. $comment = get_comment($comment_id);
  1241. do_action('wp_set_comment_status', $comment_id, $comment_status);
  1242. wp_transition_comment_status($comment_status, $comment_old->comment_approved, $comment);
  1243. wp_update_comment_count($comment->comment_post_ID);
  1244. return true;
  1245. }
  1246. /**
  1247. * Updates an existing comment in the database.
  1248. *
  1249. * Filters the comment and makes sure certain fields are valid before updating.
  1250. *
  1251. * @since 2.0.0
  1252. * @uses $wpdb
  1253. * @uses wp_transition_comment_status() Passes new and old comment status along with $comment object
  1254. *
  1255. * @param array $commentarr Contains information on the comment.
  1256. * @return int Comment was updated if value is 1, or was not updated if value is 0.
  1257. */
  1258. function wp_update_comment($commentarr) {
  1259. global $wpdb;
  1260. // First, get all of the original fields
  1261. $comment = get_comment($commentarr['comment_ID'], ARRAY_A);
  1262. // Escape data pulled from DB.
  1263. $comment = esc_sql($comment);
  1264. $old_status = $comment['comment_approved'];
  1265. // Merge old and new fields with new fields overwriting old ones.
  1266. $commentarr = array_merge($comment, $commentarr);
  1267. $commentarr = wp_filter_comment( $commentarr );
  1268. // Now extract the merged array.
  1269. extract(stripslashes_deep($commentarr), EXTR_SKIP);
  1270. $comment_content = apply_filters('comment_save_pre', $comment_content);
  1271. $comment_date_gmt = get_gmt_from_date($comment_date);
  1272. if ( !isset($comment_approved) )
  1273. $comment_approved = 1;
  1274. else if ( 'hold' == $comment_approved )
  1275. $comment_approved = 0;
  1276. else if ( 'approve' == $comment_approved )
  1277. $comment_approved = 1;
  1278. $data = compact('comment_content', 'comment_author', 'comment_author_email', 'comment_approved', 'comment_karma', 'comment_author_url', 'comment_date', 'comment_date_gmt');
  1279. $rval = $wpdb->update( $wpdb->comments, $data, compact( 'comment_ID' ) );
  1280. clean_comment_cache($comment_ID);
  1281. wp_update_comment_count($comment_post_ID);
  1282. do_action('edit_comment', $comment_ID);
  1283. $comment = get_comment($comment_ID);
  1284. wp_transition_comment_status($comment->comment_approved, $old_status, $comment);
  1285. return $rval;
  1286. }
  1287. /**
  1288. * Whether to defer comment counting.
  1289. *
  1290. * When setting $defer to true, all post comment counts will not be updated
  1291. * until $defer is set to false. W…

Large files files are truncated, but you can click here to view the full file