PageRenderTime 66ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/comment.php

https://bitbucket.org/space87/wordpressstart
PHP | 2018 lines | 1011 code | 275 blank | 732 comment | 268 complexity | dc79e8aa0082d090b4af313375c0a42a MD5 | raw file

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 Optional. The meta key to retrieve. By default, returns data for all keys.
  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. * Sets the cookies used to store an unauthenticated commentator's identity. Typically used
  512. * to recall previous comments by this commentator that are still held in moderation.
  513. *
  514. * @param object $comment Comment object.
  515. * @param object $user Comment author's object.
  516. *
  517. * @since 3.4.0
  518. */
  519. function wp_set_comment_cookies($comment, $user) {
  520. if ( $user->exists() )
  521. return;
  522. $comment_cookie_lifetime = apply_filters('comment_cookie_lifetime', 30000000);
  523. setcookie('comment_author_' . COOKIEHASH, $comment->comment_author, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN);
  524. setcookie('comment_author_email_' . COOKIEHASH, $comment->comment_author_email, time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN);
  525. setcookie('comment_author_url_' . COOKIEHASH, esc_url($comment->comment_author_url), time() + $comment_cookie_lifetime, COOKIEPATH, COOKIE_DOMAIN);
  526. }
  527. /**
  528. * Sanitizes the cookies sent to the user already.
  529. *
  530. * Will only do anything if the cookies have already been created for the user.
  531. * Mostly used after cookies had been sent to use elsewhere.
  532. *
  533. * @since 2.0.4
  534. */
  535. function sanitize_comment_cookies() {
  536. if ( isset($_COOKIE['comment_author_'.COOKIEHASH]) ) {
  537. $comment_author = apply_filters('pre_comment_author_name', $_COOKIE['comment_author_'.COOKIEHASH]);
  538. $comment_author = stripslashes($comment_author);
  539. $comment_author = esc_attr($comment_author);
  540. $_COOKIE['comment_author_'.COOKIEHASH] = $comment_author;
  541. }
  542. if ( isset($_COOKIE['comment_author_email_'.COOKIEHASH]) ) {
  543. $comment_author_email = apply_filters('pre_comment_author_email', $_COOKIE['comment_author_email_'.COOKIEHASH]);
  544. $comment_author_email = stripslashes($comment_author_email);
  545. $comment_author_email = esc_attr($comment_author_email);
  546. $_COOKIE['comment_author_email_'.COOKIEHASH] = $comment_author_email;
  547. }
  548. if ( isset($_COOKIE['comment_author_url_'.COOKIEHASH]) ) {
  549. $comment_author_url = apply_filters('pre_comment_author_url', $_COOKIE['comment_author_url_'.COOKIEHASH]);
  550. $comment_author_url = stripslashes($comment_author_url);
  551. $_COOKIE['comment_author_url_'.COOKIEHASH] = $comment_author_url;
  552. }
  553. }
  554. /**
  555. * Validates whether this comment is allowed to be made.
  556. *
  557. * @since 2.0.0
  558. * @uses $wpdb
  559. * @uses apply_filters() Calls 'pre_comment_approved' hook on the type of comment
  560. * @uses apply_filters() Calls 'comment_duplicate_trigger' hook on commentdata.
  561. * @uses do_action() Calls 'check_comment_flood' hook on $comment_author_IP, $comment_author_email, and $comment_date_gmt
  562. *
  563. * @param array $commentdata Contains information on the comment
  564. * @return mixed Signifies the approval status (0|1|'spam')
  565. */
  566. function wp_allow_comment($commentdata) {
  567. global $wpdb;
  568. extract($commentdata, EXTR_SKIP);
  569. // Simple duplicate check
  570. // expected_slashed ($comment_post_ID, $comment_author, $comment_author_email, $comment_content)
  571. $dupe = "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = '$comment_post_ID' AND comment_approved != 'trash' AND ( comment_author = '$comment_author' ";
  572. if ( $comment_author_email )
  573. $dupe .= "OR comment_author_email = '$comment_author_email' ";
  574. $dupe .= ") AND comment_content = '$comment_content' LIMIT 1";
  575. if ( $wpdb->get_var($dupe) ) {
  576. do_action( 'comment_duplicate_trigger', $commentdata );
  577. if ( defined('DOING_AJAX') )
  578. die( __('Duplicate comment detected; it looks as though you&#8217;ve already said that!') );
  579. wp_die( __('Duplicate comment detected; it looks as though you&#8217;ve already said that!') );
  580. }
  581. do_action( 'check_comment_flood', $comment_author_IP, $comment_author_email, $comment_date_gmt );
  582. if ( isset($user_id) && $user_id) {
  583. $userdata = get_userdata($user_id);
  584. $user = new WP_User($user_id);
  585. $post_author = $wpdb->get_var($wpdb->prepare("SELECT post_author FROM $wpdb->posts WHERE ID = %d LIMIT 1", $comment_post_ID));
  586. }
  587. if ( isset($userdata) && ( $user_id == $post_author || $user->has_cap('moderate_comments') ) ) {
  588. // The author and the admins get respect.
  589. $approved = 1;
  590. } else {
  591. // Everyone else's comments will be checked.
  592. if ( check_comment($comment_author, $comment_author_email, $comment_author_url, $comment_content, $comment_author_IP, $comment_agent, $comment_type) )
  593. $approved = 1;
  594. else
  595. $approved = 0;
  596. if ( wp_blacklist_check($comment_author, $comment_author_email, $comment_author_url, $comment_content, $comment_author_IP, $comment_agent) )
  597. $approved = 'spam';
  598. }
  599. $approved = apply_filters( 'pre_comment_approved', $approved, $commentdata );
  600. return $approved;
  601. }
  602. /**
  603. * Check whether comment flooding is occurring.
  604. *
  605. * Won't run, if current user can manage options, so to not block
  606. * administrators.
  607. *
  608. * @since 2.3.0
  609. * @uses $wpdb
  610. * @uses apply_filters() Calls 'comment_flood_filter' filter with first
  611. * parameter false, last comment timestamp, new comment timestamp.
  612. * @uses do_action() Calls 'comment_flood_trigger' action with parameters with
  613. * last comment timestamp and new comment timestamp.
  614. *
  615. * @param string $ip Comment IP.
  616. * @param string $email Comment author email address.
  617. * @param string $date MySQL time string.
  618. */
  619. function check_comment_flood_db( $ip, $email, $date ) {
  620. global $wpdb;
  621. if ( current_user_can( 'manage_options' ) )
  622. return; // don't throttle admins
  623. $hour_ago = gmdate( 'Y-m-d H:i:s', time() - 3600 );
  624. 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 ) ) ) {
  625. $time_lastcomment = mysql2date('U', $lasttime, false);
  626. $time_newcomment = mysql2date('U', $date, false);
  627. $flood_die = apply_filters('comment_flood_filter', false, $time_lastcomment, $time_newcomment);
  628. if ( $flood_die ) {
  629. do_action('comment_flood_trigger', $time_lastcomment, $time_newcomment);
  630. if ( defined('DOING_AJAX') )
  631. die( __('You are posting comments too quickly. Slow down.') );
  632. wp_die( __('You are posting comments too quickly. Slow down.'), '', array('response' => 403) );
  633. }
  634. }
  635. }
  636. /**
  637. * Separates an array of comments into an array keyed by comment_type.
  638. *
  639. * @since 2.7.0
  640. *
  641. * @param array $comments Array of comments
  642. * @return array Array of comments keyed by comment_type.
  643. */
  644. function &separate_comments(&$comments) {
  645. $comments_by_type = array('comment' => array(), 'trackback' => array(), 'pingback' => array(), 'pings' => array());
  646. $count = count($comments);
  647. for ( $i = 0; $i < $count; $i++ ) {
  648. $type = $comments[$i]->comment_type;
  649. if ( empty($type) )
  650. $type = 'comment';
  651. $comments_by_type[$type][] = &$comments[$i];
  652. if ( 'trackback' == $type || 'pingback' == $type )
  653. $comments_by_type['pings'][] = &$comments[$i];
  654. }
  655. return $comments_by_type;
  656. }
  657. /**
  658. * Calculate the total number of comment pages.
  659. *
  660. * @since 2.7.0
  661. * @uses get_query_var() Used to fill in the default for $per_page parameter.
  662. * @uses get_option() Used to fill in defaults for parameters.
  663. * @uses Walker_Comment
  664. *
  665. * @param array $comments Optional array of comment objects. Defaults to $wp_query->comments
  666. * @param int $per_page Optional comments per page.
  667. * @param boolean $threaded Optional control over flat or threaded comments.
  668. * @return int Number of comment pages.
  669. */
  670. function get_comment_pages_count( $comments = null, $per_page = null, $threaded = null ) {
  671. global $wp_query;
  672. if ( null === $comments && null === $per_page && null === $threaded && !empty($wp_query->max_num_comment_pages) )
  673. return $wp_query->max_num_comment_pages;
  674. if ( !$comments || !is_array($comments) )
  675. $comments = $wp_query->comments;
  676. if ( empty($comments) )
  677. return 0;
  678. if ( !isset($per_page) )
  679. $per_page = (int) get_query_var('comments_per_page');
  680. if ( 0 === $per_page )
  681. $per_page = (int) get_option('comments_per_page');
  682. if ( 0 === $per_page )
  683. return 1;
  684. if ( !isset($threaded) )
  685. $threaded = get_option('thread_comments');
  686. if ( $threaded ) {
  687. $walker = new Walker_Comment;
  688. $count = ceil( $walker->get_number_of_root_elements( $comments ) / $per_page );
  689. } else {
  690. $count = ceil( count( $comments ) / $per_page );
  691. }
  692. return $count;
  693. }
  694. /**
  695. * Calculate what page number a comment will appear on for comment paging.
  696. *
  697. * @since 2.7.0
  698. * @uses get_comment() Gets the full comment of the $comment_ID parameter.
  699. * @uses get_option() Get various settings to control function and defaults.
  700. * @uses get_page_of_comment() Used to loop up to top level comment.
  701. *
  702. * @param int $comment_ID Comment ID.
  703. * @param array $args Optional args.
  704. * @return int|null Comment page number or null on error.
  705. */
  706. function get_page_of_comment( $comment_ID, $args = array() ) {
  707. global $wpdb;
  708. if ( !$comment = get_comment( $comment_ID ) )
  709. return;
  710. $defaults = array( 'type' => 'all', 'page' => '', 'per_page' => '', 'max_depth' => '' );
  711. $args = wp_parse_args( $args, $defaults );
  712. if ( '' === $args['per_page'] && get_option('page_comments') )
  713. $args['per_page'] = get_query_var('comments_per_page');
  714. if ( empty($args['per_page']) ) {
  715. $args['per_page'] = 0;
  716. $args['page'] = 0;
  717. }
  718. if ( $args['per_page'] < 1 )
  719. return 1;
  720. if ( '' === $args['max_depth'] ) {
  721. if ( get_option('thread_comments') )
  722. $args['max_depth'] = get_option('thread_comments_depth');
  723. else
  724. $args['max_depth'] = -1;
  725. }
  726. // Find this comment's top level parent if threading is enabled
  727. if ( $args['max_depth'] > 1 && 0 != $comment->comment_parent )
  728. return get_page_of_comment( $comment->comment_parent, $args );
  729. $allowedtypes = array(
  730. 'comment' => '',
  731. 'pingback' => 'pingback',
  732. 'trackback' => 'trackback',
  733. );
  734. $comtypewhere = ( 'all' != $args['type'] && isset($allowedtypes[$args['type']]) ) ? " AND comment_type = '" . $allowedtypes[$args['type']] . "'" : '';
  735. // Count comments older than this one
  736. $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 ) );
  737. // No older comments? Then it's page #1.
  738. if ( 0 == $oldercoms )
  739. return 1;
  740. // Divide comments older than this one by comments per page to get this comment's page number
  741. return ceil( ( $oldercoms + 1 ) / $args['per_page'] );
  742. }
  743. /**
  744. * Does comment contain blacklisted characters or words.
  745. *
  746. * @since 1.5.0
  747. * @uses do_action() Calls 'wp_blacklist_check' hook for all parameters.
  748. *
  749. * @param string $author The author of the comment
  750. * @param string $email The email of the comment
  751. * @param string $url The url used in the comment
  752. * @param string $comment The comment content
  753. * @param string $user_ip The comment author IP address
  754. * @param string $user_agent The author's browser user agent
  755. * @return bool True if comment contains blacklisted content, false if comment does not
  756. */
  757. function wp_blacklist_check($author, $email, $url, $comment, $user_ip, $user_agent) {
  758. do_action('wp_blacklist_check', $author, $email, $url, $comment, $user_ip, $user_agent);
  759. $mod_keys = trim( get_option('blacklist_keys') );
  760. if ( '' == $mod_keys )
  761. return false; // If moderation keys are empty
  762. $words = explode("\n", $mod_keys );
  763. foreach ( (array) $words as $word ) {
  764. $word = trim($word);
  765. // Skip empty lines
  766. if ( empty($word) ) { continue; }
  767. // Do some escaping magic so that '#' chars in the
  768. // spam words don't break things:
  769. $word = preg_quote($word, '#');
  770. $pattern = "#$word#i";
  771. if (
  772. preg_match($pattern, $author)
  773. || preg_match($pattern, $email)
  774. || preg_match($pattern, $url)
  775. || preg_match($pattern, $comment)
  776. || preg_match($pattern, $user_ip)
  777. || preg_match($pattern, $user_agent)
  778. )
  779. return true;
  780. }
  781. return false;
  782. }
  783. /**
  784. * Retrieve total comments for blog or single post.
  785. *
  786. * The properties of the returned object contain the 'moderated', 'approved',
  787. * and spam comments for either the entire blog or single post. Those properties
  788. * contain the amount of comments that match the status. The 'total_comments'
  789. * property contains the integer of total comments.
  790. *
  791. * The comment stats are cached and then retrieved, if they already exist in the
  792. * cache.
  793. *
  794. * @since 2.5.0
  795. *
  796. * @param int $post_id Optional. Post ID.
  797. * @return object Comment stats.
  798. */
  799. function wp_count_comments( $post_id = 0 ) {
  800. global $wpdb;
  801. $post_id = (int) $post_id;
  802. $stats = apply_filters('wp_count_comments', array(), $post_id);
  803. if ( !empty($stats) )
  804. return $stats;
  805. $count = wp_cache_get("comments-{$post_id}", 'counts');
  806. if ( false !== $count )
  807. return $count;
  808. $where = '';
  809. if ( $post_id > 0 )
  810. $where = $wpdb->prepare( "WHERE comment_post_ID = %d", $post_id );
  811. $count = $wpdb->get_results( "SELECT comment_approved, COUNT( * ) AS num_comments FROM {$wpdb->comments} {$where} GROUP BY comment_approved", ARRAY_A );
  812. $total = 0;
  813. $approved = array('0' => 'moderated', '1' => 'approved', 'spam' => 'spam', 'trash' => 'trash', 'post-trashed' => 'post-trashed');
  814. foreach ( (array) $count as $row ) {
  815. // Don't count post-trashed toward totals
  816. if ( 'post-trashed' != $row['comment_approved'] && 'trash' != $row['comment_approved'] )
  817. $total += $row['num_comments'];
  818. if ( isset( $approved[$row['comment_approved']] ) )
  819. $stats[$approved[$row['comment_approved']]] = $row['num_comments'];
  820. }
  821. $stats['total_comments'] = $total;
  822. foreach ( $approved as $key ) {
  823. if ( empty($stats[$key]) )
  824. $stats[$key] = 0;
  825. }
  826. $stats = (object) $stats;
  827. wp_cache_set("comments-{$post_id}", $stats, 'counts');
  828. return $stats;
  829. }
  830. /**
  831. * Trashes or deletes a comment.
  832. *
  833. * The comment is moved to trash instead of permanently deleted unless trash is
  834. * disabled, item is already in the trash, or $force_delete is true.
  835. *
  836. * The post comment count will be updated if the comment was approved and has a
  837. * post ID available.
  838. *
  839. * @since 2.0.0
  840. * @uses $wpdb
  841. * @uses do_action() Calls 'delete_comment' hook on comment ID
  842. * @uses do_action() Calls 'deleted_comment' hook on comment ID after deletion, on success
  843. * @uses do_action() Calls 'wp_set_comment_status' hook on comment ID with 'delete' set for the second parameter
  844. * @uses wp_transition_comment_status() Passes new and old comment status along with $comment object
  845. *
  846. * @param int $comment_id Comment ID
  847. * @param bool $force_delete Whether to bypass trash and force deletion. Default is false.
  848. * @return bool False if delete comment query failure, true on success.
  849. */
  850. function wp_delete_comment($comment_id, $force_delete = false) {
  851. global $wpdb;
  852. if (!$comment = get_comment($comment_id))
  853. return false;
  854. if ( !$force_delete && EMPTY_TRASH_DAYS && !in_array( wp_get_comment_status($comment_id), array( 'trash', 'spam' ) ) )
  855. return wp_trash_comment($comment_id);
  856. do_action('delete_comment', $comment_id);
  857. // Move children up a level.
  858. $children = $wpdb->get_col( $wpdb->prepare("SELECT comment_ID FROM $wpdb->comments WHERE comment_parent = %d", $comment_id) );
  859. if ( !empty($children) ) {
  860. $wpdb->update($wpdb->comments, array('comment_parent' => $comment->comment_parent), array('comment_parent' => $comment_id));
  861. clean_comment_cache($children);
  862. }
  863. // Delete metadata
  864. $meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->commentmeta WHERE comment_id = %d", $comment_id ) );
  865. foreach ( $meta_ids as $mid )
  866. delete_metadata_by_mid( 'comment', $mid );
  867. if ( ! $wpdb->delete( $wpdb->comments, array( 'comment_ID' => $comment_id ) ) )
  868. return false;
  869. do_action('deleted_comment', $comment_id);
  870. $post_id = $comment->comment_post_ID;
  871. if ( $post_id && $comment->comment_approved == 1 )
  872. wp_update_comment_count($post_id);
  873. clean_comment_cache($comment_id);
  874. do_action('wp_set_comment_status', $comment_id, 'delete');
  875. wp_transition_comment_status('delete', $comment->comment_approved, $comment);
  876. return true;
  877. }
  878. /**
  879. * Moves a comment to the Trash
  880. *
  881. * If trash is disabled, comment is permanently deleted.
  882. *
  883. * @since 2.9.0
  884. * @uses do_action() on 'trash_comment' before trashing
  885. * @uses do_action() on 'trashed_comment' after trashing
  886. * @uses wp_delete_comment() if trash is disabled
  887. *
  888. * @param int $comment_id Comment ID.
  889. * @return mixed False on failure
  890. */
  891. function wp_trash_comment($comment_id) {
  892. if ( !EMPTY_TRASH_DAYS )
  893. return wp_delete_comment($comment_id, true);
  894. if ( !$comment = get_comment($comment_id) )
  895. return false;
  896. do_action('trash_comment', $comment_id);
  897. if ( wp_set_comment_status($comment_id, 'trash') ) {
  898. add_comment_meta($comment_id, '_wp_trash_meta_status', $comment->comment_approved);
  899. add_comment_meta($comment_id, '_wp_trash_meta_time', time() );
  900. do_action('trashed_comment', $comment_id);
  901. return true;
  902. }
  903. return false;
  904. }
  905. /**
  906. * Removes a comment from the Trash
  907. *
  908. * @since 2.9.0
  909. * @uses do_action() on 'untrash_comment' before untrashing
  910. * @uses do_action() on 'untrashed_comment' after untrashing
  911. *
  912. * @param int $comment_id Comment ID.
  913. * @return mixed False on failure
  914. */
  915. function wp_untrash_comment($comment_id) {
  916. if ( ! (int)$comment_id )
  917. return false;
  918. do_action('untrash_comment', $comment_id);
  919. $status = (string) get_comment_meta($comment_id, '_wp_trash_meta_status', true);
  920. if ( empty($status) )
  921. $status = '0';
  922. if ( wp_set_comment_status($comment_id, $status) ) {
  923. delete_comment_meta($comment_id, '_wp_trash_meta_time');
  924. delete_comment_meta($comment_id, '_wp_trash_meta_status');
  925. do_action('untrashed_comment', $comment_id);
  926. return true;
  927. }
  928. return false;
  929. }
  930. /**
  931. * Marks a comment as Spam
  932. *
  933. * @since 2.9.0
  934. * @uses do_action() on 'spam_comment' before spamming
  935. * @uses do_action() on 'spammed_comment' after spamming
  936. *
  937. * @param int $comment_id Comment ID.
  938. * @return mixed False on failure
  939. */
  940. function wp_spam_comment($comment_id) {
  941. if ( !$comment = get_comment($comment_id) )
  942. return false;
  943. do_action('spam_comment', $comment_id);
  944. if ( wp_set_comment_status($comment_id, 'spam') ) {
  945. add_comment_meta($comment_id, '_wp_trash_meta_status', $comment->comment_approved);
  946. do_action('spammed_comment', $comment_id);
  947. return true;
  948. }
  949. return false;
  950. }
  951. /**
  952. * Removes a comment from the Spam
  953. *
  954. * @since 2.9.0
  955. * @uses do_action() on 'unspam_comment' before unspamming
  956. * @uses do_action() on 'unspammed_comment' after unspamming
  957. *
  958. * @param int $comment_id Comment ID.
  959. * @return mixed False on failure
  960. */
  961. function wp_unspam_comment($comment_id) {
  962. if ( ! (int)$comment_id )
  963. return false;
  964. do_action('unspam_comment', $comment_id);
  965. $status = (string) get_comment_meta($comment_id, '_wp_trash_meta_status', true);
  966. if ( empty($status) )
  967. $status = '0';
  968. if ( wp_set_comment_status($comment_id, $status) ) {
  969. delete_comment_meta($comment_id, '_wp_trash_meta_status');
  970. do_action('unspammed_comment', $comment_id);
  971. return true;
  972. }
  973. return false;
  974. }
  975. /**
  976. * The status of a comment by ID.
  977. *
  978. * @since 1.0.0
  979. *
  980. * @param int $comment_id Comment ID
  981. * @return string|bool Status might be 'trash', 'approved', 'unapproved', 'spam'. False on failure.
  982. */
  983. function wp_get_comment_status($comment_id) {
  984. $comment = get_comment($comment_id);
  985. if ( !$comment )
  986. return false;
  987. $approved = $comment->comment_approved;
  988. if ( $approved == null )
  989. return false;
  990. elseif ( $approved == '1' )
  991. return 'approved';
  992. elseif ( $approved == '0' )
  993. return 'unapproved';
  994. elseif ( $approved == 'spam' )
  995. return 'spam';
  996. elseif ( $approved == 'trash' )
  997. return 'trash';
  998. else
  999. return false;
  1000. }
  1001. /**
  1002. * Call hooks for when a comment status transition occurs.
  1003. *
  1004. * Calls hooks for comment status transitions. If the new comment status is not the same
  1005. * as the previous comment status, then two hooks will be ran, the first is
  1006. * 'transition_comment_status' with new status, old status, and comment data. The
  1007. * next action called is 'comment_OLDSTATUS_to_NEWSTATUS' the NEWSTATUS is the
  1008. * $new_status parameter and the OLDSTATUS is $old_status parameter; it has the
  1009. * comment data.
  1010. *
  1011. * The final action will run whether or not the comment statuses are the same. The
  1012. * action is named 'comment_NEWSTATUS_COMMENTTYPE', NEWSTATUS is from the $new_status
  1013. * parameter and COMMENTTYPE is comment_type comment data.
  1014. *
  1015. * @since 2.7.0
  1016. *
  1017. * @param string $new_status New comment status.
  1018. * @param string $old_status Previous comment status.
  1019. * @param object $comment Comment data.
  1020. */
  1021. function wp_transition_comment_status($new_status, $old_status, $comment) {
  1022. // Translate raw statuses to human readable formats for the hooks
  1023. // This is not a complete list of comment status, it's only the ones that need to be renamed
  1024. $comment_statuses = array(
  1025. 0 => 'unapproved',
  1026. 'hold' => 'unapproved', // wp_set_comment_status() uses "hold"
  1027. 1 => 'approved',
  1028. 'approve' => 'approved', // wp_set_comment_status() uses "approve"
  1029. );
  1030. if ( isset($comment_statuses[$new_status]) ) $new_status = $comment_statuses[$new_status];
  1031. if ( isset($comment_statuses[$old_status]) ) $old_status = $comment_statuses[$old_status];
  1032. // Call the hooks
  1033. if ( $new_status != $old_status ) {
  1034. do_action('transition_comment_status', $new_status, $old_status, $comment);
  1035. do_action("comment_{$old_status}_to_{$new_status}", $comment);
  1036. }
  1037. do_action("comment_{$new_status}_{$comment->comment_type}", $comment->comment_ID, $comment);
  1038. }
  1039. /**
  1040. * Get current commenter's name, email, and URL.
  1041. *
  1042. * Expects cookies content to already be sanitized. User of this function might
  1043. * wish to recheck the returned array for validity.
  1044. *
  1045. * @see sanitize_comment_cookies() Use to sanitize cookies
  1046. *
  1047. * @since 2.0.4
  1048. *
  1049. * @return array Comment author, email, url respectively.
  1050. */
  1051. function wp_get_current_commenter() {
  1052. // Cookies should already be sanitized.
  1053. $comment_author = '';
  1054. if ( isset($_COOKIE['comment_author_'.COOKIEHASH]) )
  1055. $comment_author = $_COOKIE['comment_author_'.COOKIEHASH];
  1056. $comment_author_email = '';
  1057. if ( isset($_COOKIE['comment_author_email_'.COOKIEHASH]) )
  1058. $comment_author_email = $_COOKIE['comment_author_email_'.COOKIEHASH];
  1059. $comment_author_url = '';
  1060. if ( isset($_COOKIE['comment_author_url_'.COOKIEHASH]) )
  1061. $comment_author_url = $_COOKIE['comment_author_url_'.COOKIEHASH];
  1062. return apply_filters('wp_get_current_commenter', compact('comment_author', 'comment_author_email', 'comment_author_url'));
  1063. }
  1064. /**
  1065. * Inserts a comment to the database.
  1066. *
  1067. * The available comment data key names are 'comment_author_IP', 'comment_date',
  1068. * 'comment_date_gmt', 'comment_parent', 'comment_approved', and 'user_id'.
  1069. *
  1070. * @since 2.0.0
  1071. * @uses $wpdb
  1072. *
  1073. * @param array $commentdata Contains information on the comment.
  1074. * @return int The new comment's ID.
  1075. */
  1076. function wp_insert_comment($commentdata) {
  1077. global $wpdb;
  1078. extract(stripslashes_deep($commentdata), EXTR_SKIP);
  1079. if ( ! isset($comment_author_IP) )
  1080. $comment_author_IP = '';
  1081. if ( ! isset($comment_date) )
  1082. $comment_date = current_time('mysql');
  1083. if ( ! isset($comment_date_gmt) )
  1084. $comment_date_gmt = get_gmt_from_date($comment_date);
  1085. if ( ! isset($comment_parent) )
  1086. $comment_parent = 0;
  1087. if ( ! isset($comment_approved) )
  1088. $comment_approved = 1;
  1089. if ( ! isset($comment_karma) )
  1090. $comment_karma = 0;
  1091. if ( ! isset($user_id) )
  1092. $user_id = 0;
  1093. if ( ! isset($comment_type) )
  1094. $comment_type = '';
  1095. $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');
  1096. $wpdb->insert($wpdb->comments, $data);
  1097. $id = (int) $wpdb->insert_id;
  1098. if ( $comment_approved == 1 )
  1099. wp_update_comment_count($comment_post_ID);
  1100. $comment = get_comment($id);
  1101. do_action('wp_insert_comment', $id, $comment);
  1102. return $id;
  1103. }
  1104. /**
  1105. * Filters and sanitizes comment data.
  1106. *
  1107. * Sets the comment data 'filtered' field to true when finished. This can be
  1108. * checked as to whether the comment should be filtered and to keep from
  1109. * filtering the same comment more than once.
  1110. *
  1111. * @since 2.0.0
  1112. * @uses apply_filters() Calls 'pre_user_id' hook on comment author's user ID
  1113. * @uses apply_filters() Calls 'pre_comment_user_agent' hook on comment author's user agent
  1114. * @uses apply_filters() Calls 'pre_comment_author_name' hook on comment author's name
  1115. * @uses apply_filters() Calls 'pre_comment_content' hook on the comment's content
  1116. * @uses apply_filters() Calls 'pre_comment_user_ip' hook on comment author's IP
  1117. * @uses apply_filters() Calls 'pre_comment_author_url' hook on comment author's URL
  1118. * @uses apply_filters() Calls 'pre_comment_author_email' hook on comment author's email address
  1119. *
  1120. * @param array $commentdata Contains information on the comment.
  1121. * @return array Parsed comment information.
  1122. */
  1123. function wp_filter_comment($commentdata) {
  1124. if ( isset($commentdata['user_ID']) )
  1125. $commentdata['user_id'] = apply_filters('pre_user_id', $commentdata['user_ID']);
  1126. elseif ( isset($commentdata['user_id']) )
  1127. $commentdata['user_id'] = apply_filters('pre_user_id', $commentdata['user_id']);
  1128. $commentdata['comment_agent'] = apply_filters('pre_comment_user_agent', ( isset( $commentdata['comment_agent'] ) ? $commentdata['comment_agent'] : '' ) );
  1129. $commentdata['comment_author'] = apply_filters('pre_comment_author_name', $commentdata['comment_author']);
  1130. $commentdata['comment_content'] = apply_filters('pre_comment_content', $commentdata['comment_content']);
  1131. $commentdata['comment_author_IP'] = apply_filters('pre_comment_user_ip', $commentdata['comment_author_IP']);
  1132. $commentdata['comment_author_url'] = apply_filters('pre_comment_author_url', $commentdata['comment_author_url']);
  1133. $commentdata['comment_author_email'] = apply_filters('pre_comment_author_email', $commentdata['comment_author_email']);
  1134. $commentdata['filtered'] = true;
  1135. return $commentdata;
  1136. }
  1137. /**
  1138. * Whether comment should be blocked because of comment flood.
  1139. *
  1140. * @since 2.1.0
  1141. *
  1142. * @param bool $block Whether plugin has already blocked comment.
  1143. * @param int $time_lastcomment Timestamp for last comment.
  1144. * @param int $time_newcomment Timestamp for new comment.
  1145. * @return bool Whether comment should be blocked.
  1146. */
  1147. function wp_throttle_comment_flood($block, $time_lastcomment, $time_newcomment) {
  1148. if ( $block ) // a plugin has already blocked... we'll let that decision stand
  1149. return $block;
  1150. if ( ($time_newcomment - $time_lastcomment) < 15 )
  1151. return true;
  1152. return false;
  1153. }
  1154. /**
  1155. * Adds a new comment to the database.
  1156. *
  1157. * Filters new comment to ensure that the fields are sanitized and valid before
  1158. * inserting comment into database. Calls 'comment_post' action with comment ID
  1159. * and whether comment is approved by WordPress. Also has 'preprocess_comment'
  1160. * filter for processing the comment data before the function handles it.
  1161. *
  1162. * We use REMOTE_ADDR here directly. If you are behind a proxy, you should ensure
  1163. * that it is properly set, such as in wp-config.php, for your environment.
  1164. * See {@link http://core.trac.wordpress.org/ticket/9235}
  1165. *
  1166. * @since 1.5.0
  1167. * @uses apply_filters() Calls 'preprocess_comment' hook on $commentdata parameter array before processing
  1168. * @uses do_action() Calls 'comment_post' hook on $comment_ID returned from adding the comment and if the comment was approved.
  1169. * @uses wp_filter_comment() Used to filter comment before adding comment.
  1170. * @uses wp_allow_comment() checks to see if comment is approved.
  1171. * @uses wp_insert_comment() Does the actual comment insertion to the database.
  1172. *
  1173. * @param array $commentdata Contains information on the comment.
  1174. * @return int The ID of the comment after adding.
  1175. */
  1176. function wp_new_comment( $commentdata ) {
  1177. $commentdata = apply_filters('preprocess_comment', $commentdata);
  1178. $commentdata['comment_post_ID'] = (int) $commentdata['comment_post_ID'];
  1179. if ( isset($commentdata['user_ID']) )
  1180. $commentdata['user_id'] = $commentdata['user_ID'] = (int) $commentdata['user_ID'];
  1181. elseif ( isset($commentdata['user_id']) )
  1182. $commentdata['user_id'] = (int) $commentdata['user_id'];
  1183. $commentdata['comment_parent'] = isset($commentdata['comment_parent']) ? absint($commentdata['comment_parent']) : 0;
  1184. $parent_status = ( 0 < $commentdata['comment_parent'] ) ? wp_get_comment_status($commentdata['comment_parent']) : '';
  1185. $commentdata['comment_parent'] = ( 'approved' == $parent_status || 'unapproved' == $parent_status ) ? $commentdata['comment_parent'] : 0;
  1186. $commentdata['comment_author_IP'] = preg_replace( '/[^0-9a-fA-F:., ]/', '',$_SERVER['REMOTE_ADDR'] );
  1187. $commentdata['comment_agent'] = substr($_SERVER['HTTP_USER_AGENT'], 0, 254);
  1188. $commentdata['comment_date'] = current_time('mysql');
  1189. $commentdata['comment_date_gmt'] = current_time('mysql', 1);
  1190. $commentdata = wp_filter_comment($commentdata);
  1191. $commentdata['comment_approved'] = wp_allow_comment($commentdata);
  1192. $comment_ID = wp_insert_comment($commentdata);
  1193. do_action('comment_post', $comment_ID, $commentdata['comment_approved']);
  1194. if ( 'spam' !== $commentdata['comment_approved'] ) { // If it's spam save it silently for later crunching
  1195. if ( '0' == $commentdata['comment_approved'] )
  1196. wp_notify_moderator($comment_ID);
  1197. $post = &get_post($commentdata['comment_post_ID']); // Don't notify if it's your own comment
  1198. if ( get_option('comments_notify') && $commentdata['comment_approved'] && ( ! isset( $commentdata['user_id'] ) || $post->post_author != $commentdata['user_id'] ) )
  1199. wp_notify_postauthor($comment_ID, isset( $commentdata['comment_type'] ) ? $commentdata['comment_type'] : '' );
  1200. }
  1201. return $comment_ID;
  1202. }
  1203. /**
  1204. * Sets the status of a comment.
  1205. *
  1206. * The 'wp_set_comment_status' action is called after the comment is handled.
  1207. * If the comment status is not in the list, then false is returned.
  1208. *
  1209. * @since 1.0.0
  1210. * @uses wp_transition_comment_status() Passes new and old comment status along with $comment object
  1211. *
  1212. * @param int $comment_id Comment ID.
  1213. * @param string $comment_status New comment status, either 'hold', 'approve', 'spam', or 'trash'.
  1214. * @param bool $wp_error Whether to return a WP_Error object if there is a failure. Default is false.
  1215. * @return bool False on failure or deletion and true on success.
  1216. */
  1217. function wp_set_comment_status($comment_id, $comment_status, $wp_error = false) {
  1218. global $wpdb;
  1219. $status = '0';
  1220. switch ( $comment_status ) {
  1221. case 'hold':
  1222. case '0':
  1223. $status = '0';
  1224. break;
  1225. case 'approve':
  1226. case '1':
  1227. $status = '1';
  1228. if ( get_option('comments_notify') ) {
  1229. $comment = get_comment($comment_id);
  1230. wp_notify_postauthor($comment_id, $comment->comment_type);
  1231. }
  1232. break;
  1233. case 'spam':
  1234. $status = 'spam';
  1235. break;
  1236. case 'trash':
  1237. $status = 'trash';
  1238. break;
  1239. default:
  1240. return false;
  1241. }
  1242. $comment_old = clone get_comment($comment_id);
  1243. if ( !$wpdb->update( $wpdb->comments, array('comment_approved' => $status), array('comment_ID' => $comment_id) ) ) {
  1244. if ( $wp_error )
  1245. return new WP_Error('db_update_error', __('Could not update comment status'), $wpdb->last_error);
  1246. else
  1247. return false;
  1248. }
  1249. clean_comment_cache($comment_id);
  1250. $comment = get_comment($comment_id);
  1251. do_action('wp_set_comment_status', $comment_id, $comment_status);
  1252. wp_transition_comment_status($comment_status, $comment_old->comment_approved, $comment);
  1253. wp_update_comment_count($comment->comment_post_ID);
  1254. return true;
  1255. }
  1256. /**
  1257. * Updates an existing comment in the database.
  1258. *
  1259. * Filters the comment and makes sure certain fields are valid before updating.
  1260. *
  1261. * @since 2.0.0
  1262. * @uses $wpdb
  1263. * @uses wp_transition_comment_status() Passes new and old comment status along with $comment object
  1264. *
  1265. * @param array $commentarr Contains information on the comment.
  1266. * @return int Comment was updated if value is 1, or was not updated if value is 0.
  1267. */
  1268. function wp_update_comment($commentarr) {
  1269. global $wpdb;
  1270. // First, get all of the original fields
  1271. $comment = get_comment($commentarr['comment_ID'], ARRAY_A);
  1272. // Escape data pulled from DB.
  1273. $comment = esc_sql($comment);
  1274. $old_status = $comment['comment_approved'];
  1275. // Merge old and new fields with new fields overwriting old ones.
  1276. $commentarr = array_merge($comment, $commentarr);
  1277. $commentarr = wp_filter_comment( $commentarr );
  1278. // Now extract the merged array.
  1279. extract(stripslashes_deep($commentarr), EXTR_SKIP);
  1280. $comment_content = apply_filters('comment_save_pre', $comment_content);
  1281. $comment_date_gmt = get_gmt_from_date($comment_date);
  1282. if ( !isset($comment_approved) )
  1283. $comment_approved = 1;
  1284. else if ( 'hold' == $comment_approved )
  1285. $comment_approved = 0;
  1286. else if ( 'approve' == $comment_approved )
  1287. $comment_approved = 1;
  1288. $data = compact('comment_content', 'comment_author', 'comment_author_email', 'comment_approved', 'comment_karma', 'comment_author_…

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