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

/wp-includes/comment.php

https://bitbucket.org/MaheshDhaduk/androidmobiles
PHP | 1923 lines | 964 code | 261 blank | 698 comment | 263 complexity | c57fc5b9601dc2a5ad149482bfc51f4c MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, AGPL-1.0

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

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