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

/wp-includes/comment.php

https://bitbucket.org/aqge/deptandashboard
PHP | 2012 lines | 1011 code | 275 blank | 726 comment | 270 complexity | 17ad1a88a12dbd7831d7ce86d83901ee MD5 | raw file
Possible License(s): AGPL-1.0, GPL-2.0, LGPL-2.1
  1. <?php
  2. /**
  3. * Manages WordPress comments
  4. *
  5. * @package WordPress
  6. * @subpackage Comment
  7. */
  8. /**
  9. * Checks whether a comment passes internal checks to be allowed to add.
  10. *
  11. * If comment moderation is set in the administration, then all comments,
  12. * regardless of their type and whitelist will be set to false. If the number of
  13. * links exceeds the amount in the administration, then the check fails. If any
  14. * of the parameter contents match the blacklist of words, then the check fails.
  15. *
  16. * If the number of links exceeds the amount in the administration, then the
  17. * check fails. If any of the parameter contents match the blacklist of words,
  18. * then the check fails.
  19. *
  20. * If the comment author was approved before, then the comment is
  21. * automatically whitelisted.
  22. *
  23. * If none of the checks fail, then the failback is to set the check to pass
  24. * (return true).
  25. *
  26. * @since 1.2.0
  27. * @uses $wpdb
  28. *
  29. * @param string $author Comment Author's name
  30. * @param string $email Comment Author's email
  31. * @param string $url Comment Author's URL
  32. * @param string $comment Comment contents
  33. * @param string $user_ip Comment Author's IP address
  34. * @param string $user_agent Comment Author's User Agent
  35. * @param string $comment_type Comment type, either user submitted comment,
  36. * trackback, or pingback
  37. * @return bool Whether the checks passed (true) and the comments should be
  38. * displayed or set to moderated
  39. */
  40. function check_comment($author, $email, $url, $comment, $user_ip, $user_agent, $comment_type) {
  41. global $wpdb;
  42. if ( 1 == get_option('comment_moderation') )
  43. return false; // If moderation is set to manual
  44. $comment = apply_filters( 'comment_text', $comment );
  45. // Check # of external links
  46. if ( $max_links = get_option( 'comment_max_links' ) ) {
  47. $num_links = preg_match_all( '/<a [^>]*href/i', $comment, $out );
  48. $num_links = apply_filters( 'comment_max_links_url', $num_links, $url ); // provide for counting of $url as a link
  49. if ( $num_links >= $max_links )
  50. return false;
  51. }
  52. $mod_keys = trim(get_option('moderation_keys'));
  53. if ( !empty($mod_keys) ) {
  54. $words = explode("\n", $mod_keys );
  55. foreach ( (array) $words as $word) {
  56. $word = trim($word);
  57. // Skip empty lines
  58. if ( empty($word) )
  59. continue;
  60. // Do some escaping magic so that '#' chars in the
  61. // spam words don't break things:
  62. $word = preg_quote($word, '#');
  63. $pattern = "#$word#i";
  64. if ( preg_match($pattern, $author) ) return false;
  65. if ( preg_match($pattern, $email) ) return false;
  66. if ( preg_match($pattern, $url) ) return false;
  67. if ( preg_match($pattern, $comment) ) return false;
  68. if ( preg_match($pattern, $user_ip) ) return false;
  69. if ( preg_match($pattern, $user_agent) ) return false;
  70. }
  71. }
  72. // Comment whitelisting:
  73. if ( 1 == get_option('comment_whitelist')) {
  74. if ( 'trackback' != $comment_type && 'pingback' != $comment_type && $author != '' && $email != '' ) {
  75. // expected_slashed ($author, $email)
  76. $ok_to_comment = $wpdb->get_var("SELECT comment_approved FROM $wpdb->comments WHERE comment_author = '$author' AND comment_author_email = '$email' and comment_approved = '1' LIMIT 1");
  77. if ( ( 1 == $ok_to_comment ) &&
  78. ( empty($mod_keys) || false === strpos( $email, $mod_keys) ) )
  79. return true;
  80. else
  81. return false;
  82. } else {
  83. return false;
  84. }
  85. }
  86. return true;
  87. }
  88. /**
  89. * Retrieve the approved comments for post $post_id.
  90. *
  91. * @since 2.0.0
  92. * @uses $wpdb
  93. *
  94. * @param int $post_id The ID of the post
  95. * @return array $comments The approved comments
  96. */
  97. function get_approved_comments($post_id) {
  98. global $wpdb;
  99. return $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved = '1' ORDER BY comment_date", $post_id));
  100. }
  101. /**
  102. * Retrieves comment data given a comment ID or comment object.
  103. *
  104. * If an object is passed then the comment data will be cached and then returned
  105. * after being passed through a filter. If the comment is empty, then the global
  106. * comment variable will be used, if it is set.
  107. *
  108. * If the comment is empty, then the global comment variable will be used, if it
  109. * is set.
  110. *
  111. * @since 2.0.0
  112. * @uses $wpdb
  113. *
  114. * @param object|string|int $comment Comment to retrieve.
  115. * @param string $output Optional. OBJECT or ARRAY_A or ARRAY_N constants.
  116. * @return object|array|null Depends on $output value.
  117. */
  118. function &get_comment(&$comment, $output = OBJECT) {
  119. global $wpdb;
  120. $null = null;
  121. if ( empty($comment) ) {
  122. if ( isset($GLOBALS['comment']) )
  123. $_comment = & $GLOBALS['comment'];
  124. else
  125. $_comment = null;
  126. } elseif ( is_object($comment) ) {
  127. wp_cache_add($comment->comment_ID, $comment, 'comment');
  128. $_comment = $comment;
  129. } else {
  130. if ( isset($GLOBALS['comment']) && ($GLOBALS['comment']->comment_ID == $comment) ) {
  131. $_comment = & $GLOBALS['comment'];
  132. } elseif ( ! $_comment = wp_cache_get($comment, 'comment') ) {
  133. $_comment = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_ID = %d LIMIT 1", $comment));
  134. if ( ! $_comment )
  135. return $null;
  136. wp_cache_add($_comment->comment_ID, $_comment, 'comment');
  137. }
  138. }
  139. $_comment = apply_filters('get_comment', $_comment);
  140. if ( $output == OBJECT ) {
  141. return $_comment;
  142. } elseif ( $output == ARRAY_A ) {
  143. $__comment = get_object_vars($_comment);
  144. return $__comment;
  145. } elseif ( $output == ARRAY_N ) {
  146. $__comment = array_values(get_object_vars($_comment));
  147. return $__comment;
  148. } else {
  149. return $_comment;
  150. }
  151. }
  152. /**
  153. * Retrieve a list of comments.
  154. *
  155. * The comment list can be for the blog as a whole or for an individual post.
  156. *
  157. * The list of comment arguments are 'status', 'orderby', 'comment_date_gmt',
  158. * 'order', 'number', 'offset', and 'post_id'.
  159. *
  160. * @since 2.7.0
  161. * @uses $wpdb
  162. *
  163. * @param mixed $args Optional. Array or string of options to override defaults.
  164. * @return array List of comments.
  165. */
  166. function get_comments( $args = '' ) {
  167. $query = new WP_Comment_Query;
  168. return $query->query( $args );
  169. }
  170. /**
  171. * WordPress Comment Query class.
  172. *
  173. * @since 3.1.0
  174. */
  175. class WP_Comment_Query {
  176. /**
  177. * Execute the query
  178. *
  179. * @since 3.1.0
  180. *
  181. * @param string|array $query_vars
  182. * @return int|array
  183. */
  184. function query( $query_vars ) {
  185. global $wpdb;
  186. $defaults = array(
  187. 'author_email' => '',
  188. 'ID' => '',
  189. 'karma' => '',
  190. 'number' => '',
  191. 'offset' => '',
  192. 'orderby' => '',
  193. 'order' => 'DESC',
  194. 'parent' => '',
  195. 'post_ID' => '',
  196. 'post_id' => 0,
  197. 'post_author' => '',
  198. 'post_name' => '',
  199. 'post_parent' => '',
  200. 'post_status' => '',
  201. 'post_type' => '',
  202. 'status' => '',
  203. 'type' => '',
  204. 'user_id' => '',
  205. 'search' => '',
  206. 'count' => false
  207. );
  208. $this->query_vars = wp_parse_args( $query_vars, $defaults );
  209. do_action_ref_array( 'pre_get_comments', array( &$this ) );
  210. extract( $this->query_vars, EXTR_SKIP );
  211. // $args can be whatever, only use the args defined in defaults to compute the key
  212. $key = md5( serialize( compact(array_keys($defaults)) ) );
  213. $last_changed = wp_cache_get('last_changed', 'comment');
  214. if ( !$last_changed ) {
  215. $last_changed = time();
  216. wp_cache_set('last_changed', $last_changed, 'comment');
  217. }
  218. $cache_key = "get_comments:$key:$last_changed";
  219. if ( $cache = wp_cache_get( $cache_key, 'comment' ) ) {
  220. return $cache;
  221. }
  222. $post_id = absint($post_id);
  223. if ( 'hold' == $status )
  224. $approved = "comment_approved = '0'";
  225. elseif ( 'approve' == $status )
  226. $approved = "comment_approved = '1'";
  227. elseif ( 'spam' == $status )
  228. $approved = "comment_approved = 'spam'";
  229. elseif ( 'trash' == $status )
  230. $approved = "comment_approved = 'trash'";
  231. else
  232. $approved = "( comment_approved = '0' OR comment_approved = '1' )";
  233. $order = ( 'ASC' == strtoupper($order) ) ? 'ASC' : 'DESC';
  234. if ( ! empty( $orderby ) ) {
  235. $ordersby = is_array($orderby) ? $orderby : preg_split('/[,\s]/', $orderby);
  236. $ordersby = array_intersect(
  237. $ordersby,
  238. array(
  239. 'comment_agent',
  240. 'comment_approved',
  241. 'comment_author',
  242. 'comment_author_email',
  243. 'comment_author_IP',
  244. 'comment_author_url',
  245. 'comment_content',
  246. 'comment_date',
  247. 'comment_date_gmt',
  248. 'comment_ID',
  249. 'comment_karma',
  250. 'comment_parent',
  251. 'comment_post_ID',
  252. 'comment_type',
  253. 'user_id',
  254. )
  255. );
  256. $orderby = empty( $ordersby ) ? 'comment_date_gmt' : implode(', ', $ordersby);
  257. } else {
  258. $orderby = 'comment_date_gmt';
  259. }
  260. $number = absint($number);
  261. $offset = absint($offset);
  262. if ( !empty($number) ) {
  263. if ( $offset )
  264. $limits = 'LIMIT ' . $offset . ',' . $number;
  265. else
  266. $limits = 'LIMIT ' . $number;
  267. } else {
  268. $limits = '';
  269. }
  270. if ( $count )
  271. $fields = 'COUNT(*)';
  272. else
  273. $fields = '*';
  274. $join = '';
  275. $where = $approved;
  276. if ( ! empty($post_id) )
  277. $where .= $wpdb->prepare( ' AND comment_post_ID = %d', $post_id );
  278. if ( '' !== $author_email )
  279. $where .= $wpdb->prepare( ' AND comment_author_email = %s', $author_email );
  280. if ( '' !== $karma )
  281. $where .= $wpdb->prepare( ' AND comment_karma = %d', $karma );
  282. if ( 'comment' == $type ) {
  283. $where .= " AND comment_type = ''";
  284. } elseif( 'pings' == $type ) {
  285. $where .= ' AND comment_type IN ("pingback", "trackback")';
  286. } elseif ( ! empty( $type ) ) {
  287. $where .= $wpdb->prepare( ' AND comment_type = %s', $type );
  288. }
  289. if ( '' !== $parent )
  290. $where .= $wpdb->prepare( ' AND comment_parent = %d', $parent );
  291. if ( '' !== $user_id )
  292. $where .= $wpdb->prepare( ' AND user_id = %d', $user_id );
  293. if ( '' !== $search )
  294. $where .= $this->get_search_sql( $search, array( 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_content' ) );
  295. $post_fields = array_filter( compact( array( 'post_author', 'post_name', 'post_parent', 'post_status', 'post_type', ) ) );
  296. if ( ! empty( $post_fields ) ) {
  297. $join = "JOIN $wpdb->posts ON $wpdb->posts.ID = $wpdb->comments.comment_post_ID";
  298. foreach( $post_fields as $field_name => $field_value )
  299. $where .= $wpdb->prepare( " AND {$wpdb->posts}.{$field_name} = %s", $field_value );
  300. }
  301. $pieces = array( 'fields', 'join', 'where', 'orderby', 'order', 'limits' );
  302. $clauses = apply_filters_ref_array( 'comments_clauses', array( compact( $pieces ), &$this ) );
  303. foreach ( $pieces as $piece )
  304. $$piece = isset( $clauses[ $piece ] ) ? $clauses[ $piece ] : '';
  305. $query = "SELECT $fields FROM $wpdb->comments $join WHERE $where ORDER BY $orderby $order $limits";
  306. if ( $count )
  307. return $wpdb->get_var( $query );
  308. $comments = $wpdb->get_results( $query );
  309. $comments = apply_filters_ref_array( 'the_comments', array( $comments, &$this ) );
  310. wp_cache_add( $cache_key, $comments, 'comment' );
  311. return $comments;
  312. }
  313. /*
  314. * Used internally to generate an SQL string for searching across multiple columns
  315. *
  316. * @access protected
  317. * @since 3.1.0
  318. *
  319. * @param string $string
  320. * @param array $cols
  321. * @return string
  322. */
  323. function get_search_sql( $string, $cols ) {
  324. $string = esc_sql( like_escape( $string ) );
  325. $searches = array();
  326. foreach ( $cols as $col )
  327. $searches[] = "$col LIKE '%$string%'";
  328. return ' AND (' . implode(' OR ', $searches) . ')';
  329. }
  330. }
  331. /**
  332. * Retrieve all of the WordPress supported comment statuses.
  333. *
  334. * Comments have a limited set of valid status values, this provides the comment
  335. * status values and descriptions.
  336. *
  337. * @package WordPress
  338. * @subpackage Post
  339. * @since 2.7.0
  340. *
  341. * @return array List of comment statuses.
  342. */
  343. function get_comment_statuses( ) {
  344. $status = array(
  345. 'hold' => __('Unapproved'),
  346. /* translators: comment status */
  347. 'approve' => _x('Approved', 'adjective'),
  348. /* translators: comment status */
  349. 'spam' => _x('Spam', 'adjective'),
  350. );
  351. return $status;
  352. }
  353. /**
  354. * The date the last comment was modified.
  355. *
  356. * @since 1.5.0
  357. * @uses $wpdb
  358. * @global array $cache_lastcommentmodified
  359. *
  360. * @param string $timezone Which timezone to use in reference to 'gmt', 'blog',
  361. * or 'server' locations.
  362. * @return string Last comment modified date.
  363. */
  364. function get_lastcommentmodified($timezone = 'server') {
  365. global $cache_lastcommentmodified, $wpdb;
  366. if ( isset($cache_lastcommentmodified[$timezone]) )
  367. return $cache_lastcommentmodified[$timezone];
  368. $add_seconds_server = date('Z');
  369. switch ( strtolower($timezone)) {
  370. case 'gmt':
  371. $lastcommentmodified = $wpdb->get_var("SELECT comment_date_gmt FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
  372. break;
  373. case 'blog':
  374. $lastcommentmodified = $wpdb->get_var("SELECT comment_date FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
  375. break;
  376. case 'server':
  377. $lastcommentmodified = $wpdb->get_var($wpdb->prepare("SELECT DATE_ADD(comment_date_gmt, INTERVAL %s SECOND) FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1", $add_seconds_server));
  378. break;
  379. }
  380. $cache_lastcommentmodified[$timezone] = $lastcommentmodified;
  381. return $lastcommentmodified;
  382. }
  383. /**
  384. * The amount of comments in a post or total comments.
  385. *
  386. * A lot like {@link wp_count_comments()}, in that they both return comment
  387. * stats (albeit with different types). The {@link wp_count_comments()} actual
  388. * caches, but this function does not.
  389. *
  390. * @since 2.0.0
  391. * @uses $wpdb
  392. *
  393. * @param int $post_id Optional. Comment amount in post if > 0, else total comments blog wide.
  394. * @return array The amount of spam, approved, awaiting moderation, and total comments.
  395. */
  396. function get_comment_count( $post_id = 0 ) {
  397. global $wpdb;
  398. $post_id = (int) $post_id;
  399. $where = '';
  400. if ( $post_id > 0 ) {
  401. $where = $wpdb->prepare("WHERE comment_post_ID = %d", $post_id);
  402. }
  403. $totals = (array) $wpdb->get_results("
  404. SELECT comment_approved, COUNT( * ) AS total
  405. FROM {$wpdb->comments}
  406. {$where}
  407. GROUP BY comment_approved
  408. ", ARRAY_A);
  409. $comment_count = array(
  410. "approved" => 0,
  411. "awaiting_moderation" => 0,
  412. "spam" => 0,
  413. "total_comments" => 0
  414. );
  415. foreach ( $totals as $row ) {
  416. switch ( $row['comment_approved'] ) {
  417. case 'spam':
  418. $comment_count['spam'] = $row['total'];
  419. $comment_count["total_comments"] += $row['total'];
  420. break;
  421. case 1:
  422. $comment_count['approved'] = $row['total'];
  423. $comment_count['total_comments'] += $row['total'];
  424. break;
  425. case 0:
  426. $comment_count['awaiting_moderation'] = $row['total'];
  427. $comment_count['total_comments'] += $row['total'];
  428. break;
  429. default:
  430. break;
  431. }
  432. }
  433. return $comment_count;
  434. }
  435. //
  436. // Comment meta functions
  437. //
  438. /**
  439. * Add meta data field to a comment.
  440. *
  441. * @since 2.9.0
  442. * @uses add_metadata
  443. * @link http://codex.wordpress.org/Function_Reference/add_comment_meta
  444. *
  445. * @param int $comment_id Comment ID.
  446. * @param string $meta_key Metadata name.
  447. * @param mixed $meta_value Metadata value.
  448. * @param bool $unique Optional, default is false. Whether the same key should not be added.
  449. * @return bool False for failure. True for success.
  450. */
  451. function add_comment_meta($comment_id, $meta_key, $meta_value, $unique = false) {
  452. return add_metadata('comment', $comment_id, $meta_key, $meta_value, $unique);
  453. }
  454. /**
  455. * Remove metadata matching criteria from a comment.
  456. *
  457. * You can match based on the key, or key and value. Removing based on key and
  458. * value, will keep from removing duplicate metadata with the same key. It also
  459. * allows removing all metadata matching key, if needed.
  460. *
  461. * @since 2.9.0
  462. * @uses delete_metadata
  463. * @link http://codex.wordpress.org/Function_Reference/delete_comment_meta
  464. *
  465. * @param int $comment_id comment ID
  466. * @param string $meta_key Metadata name.
  467. * @param mixed $meta_value Optional. Metadata value.
  468. * @return bool False for failure. True for success.
  469. */
  470. function delete_comment_meta($comment_id, $meta_key, $meta_value = '') {
  471. return delete_metadata('comment', $comment_id, $meta_key, $meta_value);
  472. }
  473. /**
  474. * Retrieve comment meta field for a comment.
  475. *
  476. * @since 2.9.0
  477. * @uses get_metadata
  478. * @link http://codex.wordpress.org/Function_Reference/get_comment_meta
  479. *
  480. * @param int $comment_id Comment ID.
  481. * @param string $key The meta key to retrieve.
  482. * @param bool $single Whether to return a single value.
  483. * @return mixed Will be an array if $single is false. Will be value of meta data field if $single
  484. * is true.
  485. */
  486. function get_comment_meta($comment_id, $key, $single = false) {
  487. return get_metadata('comment', $comment_id, $key, $single);
  488. }
  489. /**
  490. * Update comment meta field based on comment ID.
  491. *
  492. * Use the $prev_value parameter to differentiate between meta fields with the
  493. * same key and comment ID.
  494. *
  495. * If the meta field for the comment does not exist, it will be added.
  496. *
  497. * @since 2.9.0
  498. * @uses update_metadata
  499. * @link http://codex.wordpress.org/Function_Reference/update_comment_meta
  500. *
  501. * @param int $comment_id Comment ID.
  502. * @param string $meta_key Metadata key.
  503. * @param mixed $meta_value Metadata value.
  504. * @param mixed $prev_value Optional. Previous value to check before removing.
  505. * @return bool False on failure, true if success.
  506. */
  507. function update_comment_meta($comment_id, $meta_key, $meta_value, $prev_value = '') {
  508. return update_metadata('comment', $comment_id, $meta_key, $meta_value, $prev_value);
  509. }
  510. /**
  511. * Sanitizes the cookies sent to the user already.
  512. *
  513. * Will only do anything if the cookies have already been created for the user.
  514. * Mostly used after cookies had been sent to use elsewhere.
  515. *
  516. * @since 2.0.4
  517. */
  518. function sanitize_comment_cookies() {
  519. if ( isset($_COOKIE['comment_author_'.COOKIEHASH]) ) {
  520. $comment_author = apply_filters('pre_comment_author_name', $_COOKIE['comment_author_'.COOKIEHASH]);
  521. $comment_author = stripslashes($comment_author);
  522. $comment_author = esc_attr($comment_author);
  523. $_COOKIE['comment_author_'.COOKIEHASH] = $comment_author;
  524. }
  525. if ( isset($_COOKIE['comment_author_email_'.COOKIEHASH]) ) {
  526. $comment_author_email = apply_filters('pre_comment_author_email', $_COOKIE['comment_author_email_'.COOKIEHASH]);
  527. $comment_author_email = stripslashes($comment_author_email);
  528. $comment_author_email = esc_attr($comment_author_email);
  529. $_COOKIE['comment_author_email_'.COOKIEHASH] = $comment_author_email;
  530. }
  531. if ( isset($_COOKIE['comment_author_url_'.COOKIEHASH]) ) {
  532. $comment_author_url = apply_filters('pre_comment_author_url', $_COOKIE['comment_author_url_'.COOKIEHASH]);
  533. $comment_author_url = stripslashes($comment_author_url);
  534. $_COOKIE['comment_author_url_'.COOKIEHASH] = $comment_author_url;
  535. }
  536. }
  537. /**
  538. * Validates whether this comment is allowed to be made.
  539. *
  540. * @since 2.0.0
  541. * @uses $wpdb
  542. * @uses apply_filters() Calls 'pre_comment_approved' hook on the type of comment
  543. * @uses apply_filters() Calls 'comment_duplicate_trigger' hook on commentdata.
  544. * @uses do_action() Calls 'check_comment_flood' hook on $comment_author_IP, $comment_author_email, and $comment_date_gmt
  545. *
  546. * @param array $commentdata Contains information on the comment
  547. * @return mixed Signifies the approval status (0|1|'spam')
  548. */
  549. function wp_allow_comment($commentdata) {
  550. global $wpdb;
  551. extract($commentdata, EXTR_SKIP);
  552. // Simple duplicate check
  553. // expected_slashed ($comment_post_ID, $comment_author, $comment_author_email, $comment_content)
  554. $dupe = "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = '$comment_post_ID' AND comment_approved != 'trash' AND ( comment_author = '$comment_author' ";
  555. if ( $comment_author_email )
  556. $dupe .= "OR comment_author_email = '$comment_author_email' ";
  557. $dupe .= ") AND comment_content = '$comment_content' LIMIT 1";
  558. if ( $wpdb->get_var($dupe) ) {
  559. do_action( 'comment_duplicate_trigger', $commentdata );
  560. if ( defined('DOING_AJAX') )
  561. die( __('Duplicate comment detected; it looks as though you&#8217;ve already said that!') );
  562. wp_die( __('Duplicate comment detected; it looks as though you&#8217;ve already said that!') );
  563. }
  564. do_action( 'check_comment_flood', $comment_author_IP, $comment_author_email, $comment_date_gmt );
  565. if ( isset($user_id) && $user_id) {
  566. $userdata = get_userdata($user_id);
  567. $user = new WP_User($user_id);
  568. $post_author = $wpdb->get_var($wpdb->prepare("SELECT post_author FROM $wpdb->posts WHERE ID = %d LIMIT 1", $comment_post_ID));
  569. }
  570. if ( isset($userdata) && ( $user_id == $post_author || $user->has_cap('moderate_comments') ) ) {
  571. // The author and the admins get respect.
  572. $approved = 1;
  573. } else {
  574. // Everyone else's comments will be checked.
  575. if ( check_comment($comment_author, $comment_author_email, $comment_author_url, $comment_content, $comment_author_IP, $comment_agent, $comment_type) )
  576. $approved = 1;
  577. else
  578. $approved = 0;
  579. if ( wp_blacklist_check($comment_author, $comment_author_email, $comment_author_url, $comment_content, $comment_author_IP, $comment_agent) )
  580. $approved = 'spam';
  581. }
  582. $approved = apply_filters( 'pre_comment_approved', $approved, $commentdata );
  583. return $approved;
  584. }
  585. /**
  586. * Check whether comment flooding is occurring.
  587. *
  588. * Won't run, if current user can manage options, so to not block
  589. * administrators.
  590. *
  591. * @since 2.3.0
  592. * @uses $wpdb
  593. * @uses apply_filters() Calls 'comment_flood_filter' filter with first
  594. * parameter false, last comment timestamp, new comment timestamp.
  595. * @uses do_action() Calls 'comment_flood_trigger' action with parameters with
  596. * last comment timestamp and new comment timestamp.
  597. *
  598. * @param string $ip Comment IP.
  599. * @param string $email Comment author email address.
  600. * @param string $date MySQL time string.
  601. */
  602. function check_comment_flood_db( $ip, $email, $date ) {
  603. global $wpdb;
  604. if ( current_user_can( 'manage_options' ) )
  605. return; // don't throttle admins
  606. $hour_ago = gmdate( 'Y-m-d H:i:s', time() - 3600 );
  607. if ( $lasttime = $wpdb->get_var( $wpdb->prepare( "SELECT `comment_date_gmt` FROM `$wpdb->comments` WHERE `comment_date_gmt` >= %s AND ( `comment_author_IP` = %s OR `comment_author_email` = %s ) ORDER BY `comment_date_gmt` DESC LIMIT 1", $hour_ago, $ip, $email ) ) ) {
  608. $time_lastcomment = mysql2date('U', $lasttime, false);
  609. $time_newcomment = mysql2date('U', $date, false);
  610. $flood_die = apply_filters('comment_flood_filter', false, $time_lastcomment, $time_newcomment);
  611. if ( $flood_die ) {
  612. do_action('comment_flood_trigger', $time_lastcomment, $time_newcomment);
  613. if ( defined('DOING_AJAX') )
  614. die( __('You are posting comments too quickly. Slow down.') );
  615. wp_die( __('You are posting comments too quickly. Slow down.'), '', array('response' => 403) );
  616. }
  617. }
  618. }
  619. /**
  620. * Separates an array of comments into an array keyed by comment_type.
  621. *
  622. * @since 2.7.0
  623. *
  624. * @param array $comments Array of comments
  625. * @return array Array of comments keyed by comment_type.
  626. */
  627. function &separate_comments(&$comments) {
  628. $comments_by_type = array('comment' => array(), 'trackback' => array(), 'pingback' => array(), 'pings' => array());
  629. $count = count($comments);
  630. for ( $i = 0; $i < $count; $i++ ) {
  631. $type = $comments[$i]->comment_type;
  632. if ( empty($type) )
  633. $type = 'comment';
  634. $comments_by_type[$type][] = &$comments[$i];
  635. if ( 'trackback' == $type || 'pingback' == $type )
  636. $comments_by_type['pings'][] = &$comments[$i];
  637. }
  638. return $comments_by_type;
  639. }
  640. /**
  641. * Calculate the total number of comment pages.
  642. *
  643. * @since 2.7.0
  644. * @uses get_query_var() Used to fill in the default for $per_page parameter.
  645. * @uses get_option() Used to fill in defaults for parameters.
  646. * @uses Walker_Comment
  647. *
  648. * @param array $comments Optional array of comment objects. Defaults to $wp_query->comments
  649. * @param int $per_page Optional comments per page.
  650. * @param boolean $threaded Optional control over flat or threaded comments.
  651. * @return int Number of comment pages.
  652. */
  653. function get_comment_pages_count( $comments = null, $per_page = null, $threaded = null ) {
  654. global $wp_query;
  655. if ( null === $comments && null === $per_page && null === $threaded && !empty($wp_query->max_num_comment_pages) )
  656. return $wp_query->max_num_comment_pages;
  657. if ( !$comments || !is_array($comments) )
  658. $comments = $wp_query->comments;
  659. if ( empty($comments) )
  660. return 0;
  661. if ( !isset($per_page) )
  662. $per_page = (int) get_query_var('comments_per_page');
  663. if ( 0 === $per_page )
  664. $per_page = (int) get_option('comments_per_page');
  665. if ( 0 === $per_page )
  666. return 1;
  667. if ( !isset($threaded) )
  668. $threaded = get_option('thread_comments');
  669. if ( $threaded ) {
  670. $walker = new Walker_Comment;
  671. $count = ceil( $walker->get_number_of_root_elements( $comments ) / $per_page );
  672. } else {
  673. $count = ceil( count( $comments ) / $per_page );
  674. }
  675. return $count;
  676. }
  677. /**
  678. * Calculate what page number a comment will appear on for comment paging.
  679. *
  680. * @since 2.7.0
  681. * @uses get_comment() Gets the full comment of the $comment_ID parameter.
  682. * @uses get_option() Get various settings to control function and defaults.
  683. * @uses get_page_of_comment() Used to loop up to top level comment.
  684. *
  685. * @param int $comment_ID Comment ID.
  686. * @param array $args Optional args.
  687. * @return int|null Comment page number or null on error.
  688. */
  689. function get_page_of_comment( $comment_ID, $args = array() ) {
  690. global $wpdb;
  691. if ( !$comment = get_comment( $comment_ID ) )
  692. return;
  693. $defaults = array( 'type' => 'all', 'page' => '', 'per_page' => '', 'max_depth' => '' );
  694. $args = wp_parse_args( $args, $defaults );
  695. if ( '' === $args['per_page'] && get_option('page_comments') )
  696. $args['per_page'] = get_query_var('comments_per_page');
  697. if ( empty($args['per_page']) ) {
  698. $args['per_page'] = 0;
  699. $args['page'] = 0;
  700. }
  701. if ( $args['per_page'] < 1 )
  702. return 1;
  703. if ( '' === $args['max_depth'] ) {
  704. if ( get_option('thread_comments') )
  705. $args['max_depth'] = get_option('thread_comments_depth');
  706. else
  707. $args['max_depth'] = -1;
  708. }
  709. // Find this comment's top level parent if threading is enabled
  710. if ( $args['max_depth'] > 1 && 0 != $comment->comment_parent )
  711. return get_page_of_comment( $comment->comment_parent, $args );
  712. $allowedtypes = array(
  713. 'comment' => '',
  714. 'pingback' => 'pingback',
  715. 'trackback' => 'trackback',
  716. );
  717. $comtypewhere = ( 'all' != $args['type'] && isset($allowedtypes[$args['type']]) ) ? " AND comment_type = '" . $allowedtypes[$args['type']] . "'" : '';
  718. // Count comments older than this one
  719. $oldercoms = $wpdb->get_var( $wpdb->prepare( "SELECT COUNT(comment_ID) FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_parent = 0 AND comment_approved = '1' AND comment_date_gmt < '%s'" . $comtypewhere, $comment->comment_post_ID, $comment->comment_date_gmt ) );
  720. // No older comments? Then it's page #1.
  721. if ( 0 == $oldercoms )
  722. return 1;
  723. // Divide comments older than this one by comments per page to get this comment's page number
  724. return ceil( ( $oldercoms + 1 ) / $args['per_page'] );
  725. }
  726. /**
  727. * Does comment contain blacklisted characters or words.
  728. *
  729. * @since 1.5.0
  730. * @uses do_action() Calls 'wp_blacklist_check' hook for all parameters.
  731. *
  732. * @param string $author The author of the comment
  733. * @param string $email The email of the comment
  734. * @param string $url The url used in the comment
  735. * @param string $comment The comment content
  736. * @param string $user_ip The comment author IP address
  737. * @param string $user_agent The author's browser user agent
  738. * @return bool True if comment contains blacklisted content, false if comment does not
  739. */
  740. function wp_blacklist_check($author, $email, $url, $comment, $user_ip, $user_agent) {
  741. do_action('wp_blacklist_check', $author, $email, $url, $comment, $user_ip, $user_agent);
  742. $mod_keys = trim( get_option('blacklist_keys') );
  743. if ( '' == $mod_keys )
  744. return false; // If moderation keys are empty
  745. $words = explode("\n", $mod_keys );
  746. foreach ( (array) $words as $word ) {
  747. $word = trim($word);
  748. // Skip empty lines
  749. if ( empty($word) ) { continue; }
  750. // Do some escaping magic so that '#' chars in the
  751. // spam words don't break things:
  752. $word = preg_quote($word, '#');
  753. $pattern = "#$word#i";
  754. if (
  755. preg_match($pattern, $author)
  756. || preg_match($pattern, $email)
  757. || preg_match($pattern, $url)
  758. || preg_match($pattern, $comment)
  759. || preg_match($pattern, $user_ip)
  760. || preg_match($pattern, $user_agent)
  761. )
  762. return true;
  763. }
  764. return false;
  765. }
  766. /**
  767. * Retrieve total comments for blog or single post.
  768. *
  769. * The properties of the returned object contain the 'moderated', 'approved',
  770. * and spam comments for either the entire blog or single post. Those properties
  771. * contain the amount of comments that match the status. The 'total_comments'
  772. * property contains the integer of total comments.
  773. *
  774. * The comment stats are cached and then retrieved, if they already exist in the
  775. * cache.
  776. *
  777. * @since 2.5.0
  778. *
  779. * @param int $post_id Optional. Post ID.
  780. * @return object Comment stats.
  781. */
  782. function wp_count_comments( $post_id = 0 ) {
  783. global $wpdb;
  784. $post_id = (int) $post_id;
  785. $stats = apply_filters('wp_count_comments', array(), $post_id);
  786. if ( !empty($stats) )
  787. return $stats;
  788. $count = wp_cache_get("comments-{$post_id}", 'counts');
  789. if ( false !== $count )
  790. return $count;
  791. $where = '';
  792. if ( $post_id > 0 )
  793. $where = $wpdb->prepare( "WHERE comment_post_ID = %d", $post_id );
  794. $count = $wpdb->get_results( "SELECT comment_approved, COUNT( * ) AS num_comments FROM {$wpdb->comments} {$where} GROUP BY comment_approved", ARRAY_A );
  795. $total = 0;
  796. $approved = array('0' => 'moderated', '1' => 'approved', 'spam' => 'spam', 'trash' => 'trash', 'post-trashed' => 'post-trashed');
  797. foreach ( (array) $count as $row ) {
  798. // Don't count post-trashed toward totals
  799. if ( 'post-trashed' != $row['comment_approved'] && 'trash' != $row['comment_approved'] )
  800. $total += $row['num_comments'];
  801. if ( isset( $approved[$row['comment_approved']] ) )
  802. $stats[$approved[$row['comment_approved']]] = $row['num_comments'];
  803. }
  804. $stats['total_comments'] = $total;
  805. foreach ( $approved as $key ) {
  806. if ( empty($stats[$key]) )
  807. $stats[$key] = 0;
  808. }
  809. $stats = (object) $stats;
  810. wp_cache_set("comments-{$post_id}", $stats, 'counts');
  811. return $stats;
  812. }
  813. /**
  814. * Trashes or deletes a comment.
  815. *
  816. * The comment is moved to trash instead of permanently deleted unless trash is
  817. * disabled, item is already in the trash, or $force_delete is true.
  818. *
  819. * The post comment count will be updated if the comment was approved and has a
  820. * post ID available.
  821. *
  822. * @since 2.0.0
  823. * @uses $wpdb
  824. * @uses do_action() Calls 'delete_comment' hook on comment ID
  825. * @uses do_action() Calls 'deleted_comment' hook on comment ID after deletion, on success
  826. * @uses do_action() Calls 'wp_set_comment_status' hook on comment ID with 'delete' set for the second parameter
  827. * @uses wp_transition_comment_status() Passes new and old comment status along with $comment object
  828. *
  829. * @param int $comment_id Comment ID
  830. * @param bool $force_delete Whether to bypass trash and force deletion. Default is false.
  831. * @return bool False if delete comment query failure, true on success.
  832. */
  833. function wp_delete_comment($comment_id, $force_delete = false) {
  834. global $wpdb;
  835. if (!$comment = get_comment($comment_id))
  836. return false;
  837. if ( !$force_delete && EMPTY_TRASH_DAYS && !in_array( wp_get_comment_status($comment_id), array( 'trash', 'spam' ) ) )
  838. return wp_trash_comment($comment_id);
  839. do_action('delete_comment', $comment_id);
  840. // Move children up a level.
  841. $children = $wpdb->get_col( $wpdb->prepare("SELECT comment_ID FROM $wpdb->comments WHERE comment_parent = %d", $comment_id) );
  842. if ( !empty($children) ) {
  843. $wpdb->update($wpdb->comments, array('comment_parent' => $comment->comment_parent), array('comment_parent' => $comment_id));
  844. clean_comment_cache($children);
  845. }
  846. // Delete metadata
  847. $meta_ids = $wpdb->get_col( $wpdb->prepare( "SELECT meta_id FROM $wpdb->commentmeta WHERE comment_id = %d ", $comment_id ) );
  848. if ( !empty($meta_ids) ) {
  849. do_action( 'delete_commentmeta', $meta_ids );
  850. $in_meta_ids = "'" . implode("', '", $meta_ids) . "'";
  851. $wpdb->query( "DELETE FROM $wpdb->commentmeta WHERE meta_id IN ($in_meta_ids)" );
  852. do_action( 'deleted_commentmeta', $meta_ids );
  853. }
  854. if ( ! $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->comments WHERE comment_ID = %d LIMIT 1", $comment_id) ) )
  855. return false;
  856. do_action('deleted_comment', $comment_id);
  857. $post_id = $comment->comment_post_ID;
  858. if ( $post_id && $comment->comment_approved == 1 )
  859. wp_update_comment_count($post_id);
  860. clean_comment_cache($comment_id);
  861. do_action('wp_set_comment_status', $comment_id, 'delete');
  862. wp_transition_comment_status('delete', $comment->comment_approved, $comment);
  863. return true;
  864. }
  865. /**
  866. * Moves a comment to the Trash
  867. *
  868. * If trash is disabled, comment is permanently deleted.
  869. *
  870. * @since 2.9.0
  871. * @uses do_action() on 'trash_comment' before trashing
  872. * @uses do_action() on 'trashed_comment' after trashing
  873. * @uses wp_delete_comment() if trash is disabled
  874. *
  875. * @param int $comment_id Comment ID.
  876. * @return mixed False on failure
  877. */
  878. function wp_trash_comment($comment_id) {
  879. if ( !EMPTY_TRASH_DAYS )
  880. return wp_delete_comment($comment_id, true);
  881. if ( !$comment = get_comment($comment_id) )
  882. return false;
  883. do_action('trash_comment', $comment_id);
  884. if ( wp_set_comment_status($comment_id, 'trash') ) {
  885. add_comment_meta($comment_id, '_wp_trash_meta_status', $comment->comment_approved);
  886. add_comment_meta($comment_id, '_wp_trash_meta_time', time() );
  887. do_action('trashed_comment', $comment_id);
  888. return true;
  889. }
  890. return false;
  891. }
  892. /**
  893. * Removes a comment from the Trash
  894. *
  895. * @since 2.9.0
  896. * @uses do_action() on 'untrash_comment' before untrashing
  897. * @uses do_action() on 'untrashed_comment' after untrashing
  898. *
  899. * @param int $comment_id Comment ID.
  900. * @return mixed False on failure
  901. */
  902. function wp_untrash_comment($comment_id) {
  903. if ( ! (int)$comment_id )
  904. return false;
  905. do_action('untrash_comment', $comment_id);
  906. $status = (string) get_comment_meta($comment_id, '_wp_trash_meta_status', true);
  907. if ( empty($status) )
  908. $status = '0';
  909. if ( wp_set_comment_status($comment_id, $status) ) {
  910. delete_comment_meta($comment_id, '_wp_trash_meta_time');
  911. delete_comment_meta($comment_id, '_wp_trash_meta_status');
  912. do_action('untrashed_comment', $comment_id);
  913. return true;
  914. }
  915. return false;
  916. }
  917. /**
  918. * Marks a comment as Spam
  919. *
  920. * @since 2.9.0
  921. * @uses do_action() on 'spam_comment' before spamming
  922. * @uses do_action() on 'spammed_comment' after spamming
  923. *
  924. * @param int $comment_id Comment ID.
  925. * @return mixed False on failure
  926. */
  927. function wp_spam_comment($comment_id) {
  928. if ( !$comment = get_comment($comment_id) )
  929. return false;
  930. do_action('spam_comment', $comment_id);
  931. if ( wp_set_comment_status($comment_id, 'spam') ) {
  932. add_comment_meta($comment_id, '_wp_trash_meta_status', $comment->comment_approved);
  933. do_action('spammed_comment', $comment_id);
  934. return true;
  935. }
  936. return false;
  937. }
  938. /**
  939. * Removes a comment from the Spam
  940. *
  941. * @since 2.9.0
  942. * @uses do_action() on 'unspam_comment' before unspamming
  943. * @uses do_action() on 'unspammed_comment' after unspamming
  944. *
  945. * @param int $comment_id Comment ID.
  946. * @return mixed False on failure
  947. */
  948. function wp_unspam_comment($comment_id) {
  949. if ( ! (int)$comment_id )
  950. return false;
  951. do_action('unspam_comment', $comment_id);
  952. $status = (string) get_comment_meta($comment_id, '_wp_trash_meta_status', true);
  953. if ( empty($status) )
  954. $status = '0';
  955. if ( wp_set_comment_status($comment_id, $status) ) {
  956. delete_comment_meta($comment_id, '_wp_trash_meta_status');
  957. do_action('unspammed_comment', $comment_id);
  958. return true;
  959. }
  960. return false;
  961. }
  962. /**
  963. * The status of a comment by ID.
  964. *
  965. * @since 1.0.0
  966. *
  967. * @param int $comment_id Comment ID
  968. * @return string|bool Status might be 'trash', 'approved', 'unapproved', 'spam'. False on failure.
  969. */
  970. function wp_get_comment_status($comment_id) {
  971. $comment = get_comment($comment_id);
  972. if ( !$comment )
  973. return false;
  974. $approved = $comment->comment_approved;
  975. if ( $approved == NULL )
  976. return false;
  977. elseif ( $approved == '1' )
  978. return 'approved';
  979. elseif ( $approved == '0' )
  980. return 'unapproved';
  981. elseif ( $approved == 'spam' )
  982. return 'spam';
  983. elseif ( $approved == 'trash' )
  984. return 'trash';
  985. else
  986. return false;
  987. }
  988. /**
  989. * Call hooks for when a comment status transition occurs.
  990. *
  991. * Calls hooks for comment status transitions. If the new comment status is not the same
  992. * as the previous comment status, then two hooks will be ran, the first is
  993. * 'transition_comment_status' with new status, old status, and comment data. The
  994. * next action called is 'comment_OLDSTATUS_to_NEWSTATUS' the NEWSTATUS is the
  995. * $new_status parameter and the OLDSTATUS is $old_status parameter; it has the
  996. * comment data.
  997. *
  998. * The final action will run whether or not the comment statuses are the same. The
  999. * action is named 'comment_NEWSTATUS_COMMENTTYPE', NEWSTATUS is from the $new_status
  1000. * parameter and COMMENTTYPE is comment_type comment data.
  1001. *
  1002. * @since 2.7.0
  1003. *
  1004. * @param string $new_status New comment status.
  1005. * @param string $old_status Previous comment status.
  1006. * @param object $comment Comment data.
  1007. */
  1008. function wp_transition_comment_status($new_status, $old_status, $comment) {
  1009. // Translate raw statuses to human readable formats for the hooks
  1010. // This is not a complete list of comment status, it's only the ones that need to be renamed
  1011. $comment_statuses = array(
  1012. 0 => 'unapproved',
  1013. 'hold' => 'unapproved', // wp_set_comment_status() uses "hold"
  1014. 1 => 'approved',
  1015. 'approve' => 'approved', // wp_set_comment_status() uses "approve"
  1016. );
  1017. if ( isset($comment_statuses[$new_status]) ) $new_status = $comment_statuses[$new_status];
  1018. if ( isset($comment_statuses[$old_status]) ) $old_status = $comment_statuses[$old_status];
  1019. // Call the hooks
  1020. if ( $new_status != $old_status ) {
  1021. do_action('transition_comment_status', $new_status, $old_status, $comment);
  1022. do_action("comment_{$old_status}_to_{$new_status}", $comment);
  1023. }
  1024. do_action("comment_{$new_status}_{$comment->comment_type}", $comment->comment_ID, $comment);
  1025. }
  1026. /**
  1027. * Get current commenter's name, email, and URL.
  1028. *
  1029. * Expects cookies content to already be sanitized. User of this function might
  1030. * wish to recheck the returned array for validity.
  1031. *
  1032. * @see sanitize_comment_cookies() Use to sanitize cookies
  1033. *
  1034. * @since 2.0.4
  1035. *
  1036. * @return array Comment author, email, url respectively.
  1037. */
  1038. function wp_get_current_commenter() {
  1039. // Cookies should already be sanitized.
  1040. $comment_author = '';
  1041. if ( isset($_COOKIE['comment_author_'.COOKIEHASH]) )
  1042. $comment_author = $_COOKIE['comment_author_'.COOKIEHASH];
  1043. $comment_author_email = '';
  1044. if ( isset($_COOKIE['comment_author_email_'.COOKIEHASH]) )
  1045. $comment_author_email = $_COOKIE['comment_author_email_'.COOKIEHASH];
  1046. $comment_author_url = '';
  1047. if ( isset($_COOKIE['comment_author_url_'.COOKIEHASH]) )
  1048. $comment_author_url = $_COOKIE['comment_author_url_'.COOKIEHASH];
  1049. return apply_filters('wp_get_current_commenter', compact('comment_author', 'comment_author_email', 'comment_author_url'));
  1050. }
  1051. /**
  1052. * Inserts a comment to the database.
  1053. *
  1054. * The available comment data key names are 'comment_author_IP', 'comment_date',
  1055. * 'comment_date_gmt', 'comment_parent', 'comment_approved', and 'user_id'.
  1056. *
  1057. * @since 2.0.0
  1058. * @uses $wpdb
  1059. *
  1060. * @param array $commentdata Contains information on the comment.
  1061. * @return int The new comment's ID.
  1062. */
  1063. function wp_insert_comment($commentdata) {
  1064. global $wpdb;
  1065. extract(stripslashes_deep($commentdata), EXTR_SKIP);
  1066. if ( ! isset($comment_author_IP) )
  1067. $comment_author_IP = '';
  1068. if ( ! isset($comment_date) )
  1069. $comment_date = current_time('mysql');
  1070. if ( ! isset($comment_date_gmt) )
  1071. $comment_date_gmt = get_gmt_from_date($comment_date);
  1072. if ( ! isset($comment_parent) )
  1073. $comment_parent = 0;
  1074. if ( ! isset($comment_approved) )
  1075. $comment_approved = 1;
  1076. if ( ! isset($comment_karma) )
  1077. $comment_karma = 0;
  1078. if ( ! isset($user_id) )
  1079. $user_id = 0;
  1080. if ( ! isset($comment_type) )
  1081. $comment_type = '';
  1082. $data = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_author_IP', 'comment_date', 'comment_date_gmt', 'comment_content', 'comment_karma', 'comment_approved', 'comment_agent', 'comment_type', 'comment_parent', 'user_id');
  1083. $wpdb->insert($wpdb->comments, $data);
  1084. $id = (int) $wpdb->insert_id;
  1085. if ( $comment_approved == 1 )
  1086. wp_update_comment_count($comment_post_ID);
  1087. $comment = get_comment($id);
  1088. do_action('wp_insert_comment', $id, $comment);
  1089. return $id;
  1090. }
  1091. /**
  1092. * Filters and sanitizes comment data.
  1093. *
  1094. * Sets the comment data 'filtered' field to true when finished. This can be
  1095. * checked as to whether the comment should be filtered and to keep from
  1096. * filtering the same comment more than once.
  1097. *
  1098. * @since 2.0.0
  1099. * @uses apply_filters() Calls 'pre_user_id' hook on comment author's user ID
  1100. * @uses apply_filters() Calls 'pre_comment_user_agent' hook on comment author's user agent
  1101. * @uses apply_filters() Calls 'pre_comment_author_name' hook on comment author's name
  1102. * @uses apply_filters() Calls 'pre_comment_content' hook on the comment's content
  1103. * @uses apply_filters() Calls 'pre_comment_user_ip' hook on comment author's IP
  1104. * @uses apply_filters() Calls 'pre_comment_author_url' hook on comment author's URL
  1105. * @uses apply_filters() Calls 'pre_comment_author_email' hook on comment author's email address
  1106. *
  1107. * @param array $commentdata Contains information on the comment.
  1108. * @return array Parsed comment information.
  1109. */
  1110. function wp_filter_comment($commentdata) {
  1111. if ( isset($commentdata['user_ID']) )
  1112. $commentdata['user_id'] = apply_filters('pre_user_id', $commentdata['user_ID']);
  1113. elseif ( isset($commentdata['user_id']) )
  1114. $commentdata['user_id'] = apply_filters('pre_user_id', $commentdata['user_id']);
  1115. $commentdata['comment_agent'] = apply_filters('pre_comment_user_agent', ( isset( $commentdata['comment_agent'] ) ? $commentdata['comment_agent'] : '' ) );
  1116. $commentdata['comment_author'] = apply_filters('pre_comment_author_name', $commentdata['comment_author']);
  1117. $commentdata['comment_content'] = apply_filters('pre_comment_content', $commentdata['comment_content']);
  1118. $commentdata['comment_author_IP'] = apply_filters('pre_comment_user_ip', $commentdata['comment_author_IP']);
  1119. $commentdata['comment_author_url'] = apply_filters('pre_comment_author_url', $commentdata['comment_author_url']);
  1120. $commentdata['comment_author_email'] = apply_filters('pre_comment_author_email', $commentdata['comment_author_email']);
  1121. $commentdata['filtered'] = true;
  1122. return $commentdata;
  1123. }
  1124. /**
  1125. * Whether comment should be blocked because of comment flood.
  1126. *
  1127. * @since 2.1.0
  1128. *
  1129. * @param bool $block Whether plugin has already blocked comment.
  1130. * @param int $time_lastcomment Timestamp for last comment.
  1131. * @param int $time_newcomment Timestamp for new comment.
  1132. * @return bool Whether comment should be blocked.
  1133. */
  1134. function wp_throttle_comment_flood($block, $time_lastcomment, $time_newcomment) {
  1135. if ( $block ) // a plugin has already blocked... we'll let that decision stand
  1136. return $block;
  1137. if ( ($time_newcomment - $time_lastcomment) < 15 )
  1138. return true;
  1139. return false;
  1140. }
  1141. /**
  1142. * Adds a new comment to the database.
  1143. *
  1144. * Filters new comment to ensure that the fields are sanitized and valid before
  1145. * inserting comment into database. Calls 'comment_post' action with comment ID
  1146. * and whether comment is approved by WordPress. Also has 'preprocess_comment'
  1147. * filter for processing the comment data before the function handles it.
  1148. *
  1149. * We use REMOTE_ADDR here directly. If you are behind a proxy, you should ensure
  1150. * that it is properly set, such as in wp-config.php, for your environment.
  1151. * See {@link http://core.trac.wordpress.org/ticket/9235}
  1152. *
  1153. * @since 1.5.0
  1154. * @uses apply_filters() Calls 'preprocess_comment' hook on $commentdata parameter array before processing
  1155. * @uses do_action() Calls 'comment_post' hook on $comment_ID returned from adding the comment and if the comment was approved.
  1156. * @uses wp_filter_comment() Used to filter comment before adding comment.
  1157. * @uses wp_allow_comment() checks to see if comment is approved.
  1158. * @uses wp_insert_comment() Does the actual comment insertion to the database.
  1159. *
  1160. * @param array $commentdata Contains information on the comment.
  1161. * @return int The ID of the comment after adding.
  1162. */
  1163. function wp_new_comment( $commentdata ) {
  1164. $commentdata = apply_filters('preprocess_comment', $commentdata);
  1165. $commentdata['comment_post_ID'] = (int) $commentdata['comment_post_ID'];
  1166. if ( isset($commentdata['user_ID']) )
  1167. $commentdata['user_id'] = $commentdata['user_ID'] = (int) $commentdata['user_ID'];
  1168. elseif ( isset($commentdata['user_id']) )
  1169. $commentdata['user_id'] = (int) $commentdata['user_id'];
  1170. $commentdata['comment_parent'] = isset($commentdata['comment_parent']) ? absint($commentdata['comment_parent']) : 0;
  1171. $parent_status = ( 0 < $commentdata['comment_parent'] ) ? wp_get_comment_status($commentdata['comment_parent']) : '';
  1172. $commentdata['comment_parent'] = ( 'approved' == $parent_status || 'unapproved' == $parent_status ) ? $commentdata['comment_parent'] : 0;
  1173. $commentdata['comment_author_IP'] = preg_replace( '/[^0-9a-fA-F:., ]/', '',$_SERVER['REMOTE_ADDR'] );
  1174. $commentdata['comment_agent'] = substr($_SERVER['HTTP_USER_AGENT'], 0, 254);
  1175. $commentdata['comment_date'] = current_time('mysql');
  1176. $commentdata['comment_date_gmt'] = current_time('mysql', 1);
  1177. $commentdata = wp_filter_comment($commentdata);
  1178. $commentdata['comment_approved'] = wp_allow_comment($commentdata);
  1179. $comment_ID = wp_insert_comment($commentdata);
  1180. do_action('comment_post', $comment_ID, $commentdata['comment_approved']);
  1181. if ( 'spam' !== $commentdata['comment_approved'] ) { // If it's spam save it silently for later crunching
  1182. if ( '0' == $commentdata['comment_approved'] )
  1183. wp_notify_moderator($comment_ID);
  1184. $post = &get_post($commentdata['comment_post_ID']); // Don't notify if it's your own comment
  1185. if ( get_option('comments_notify') && $commentdata['comment_approved'] && ( ! isset( $commentdata['user_id'] ) || $post->post_author != $commentdata['user_id'] ) )
  1186. wp_notify_postauthor($comment_ID, isset( $commentdata['comment_type'] ) ? $commentdata['comment_type'] : '' );
  1187. }
  1188. return $comment_ID;
  1189. }
  1190. /**
  1191. * Sets the status of a comment.
  1192. *
  1193. * The 'wp_set_comment_status' action is called after the comment is handled and
  1194. * will only be called, if the comment status is either 'hold', 'approve', or
  1195. * 'spam'. If the comment status is not in the list, then false is returned and
  1196. * if the status is 'delete', then the comment is deleted without calling the
  1197. * action.
  1198. *
  1199. * @since 1.0.0
  1200. * @uses wp_transition_comment_status() Passes new and old comment status along with $comment object
  1201. *
  1202. * @param int $comment_id Comment ID.
  1203. * @param string $comment_status New comment status, either 'hold', 'approve', 'spam', or 'delete'.
  1204. * @param bool $wp_error Whether to return a WP_Error object if there is a failure. Default is false.
  1205. * @return bool False on failure or deletion and true on success.
  1206. */
  1207. function wp_set_comment_status($comment_id, $comment_status, $wp_error = false) {
  1208. global $wpdb;
  1209. $status = '0';
  1210. switch ( $comment_status ) {
  1211. case 'hold':
  1212. case '0':
  1213. $status = '0';
  1214. break;
  1215. case 'approve':
  1216. case '1':
  1217. $status = '1';
  1218. if ( get_option('comments_notify') ) {
  1219. $comment = get_comment($comment_id);
  1220. wp_notify_postauthor($comment_id, $comment->comment_type);
  1221. }
  1222. break;
  1223. case 'spam':
  1224. $status = 'spam';
  1225. break;
  1226. case 'trash':
  1227. $status = 'trash';
  1228. break;
  1229. default:
  1230. return false;
  1231. }
  1232. $comment_old = clone get_comment($comment_id);
  1233. if ( !$wpdb->update( $wpdb->comments, array('comment_approved' => $status), array('comment_ID' => $comment_id) ) ) {
  1234. if ( $wp_error )
  1235. return new WP_Error('db_update_error', __('Could not update comment status'), $wpdb->last_error);
  1236. else
  1237. return false;
  1238. }
  1239. clean_comment_cache($comment_id);
  1240. $comment = get_comment($comment_id);
  1241. do_action('wp_set_comment_status', $comment_id, $comment_status);
  1242. wp_transition_comment_status($comment_status, $comment_old->comment_approved, $comment);
  1243. wp_update_comment_count($comment->comment_post_ID);
  1244. return true;
  1245. }
  1246. /**
  1247. * Updates an existing comment in the database.
  1248. *
  1249. * Filters the comment and makes sure certain fields are valid before updating.
  1250. *
  1251. * @since 2.0.0
  1252. * @uses $wpdb
  1253. * @uses wp_transition_comment_status() Passes new and old comment status along with $comment object
  1254. *
  1255. * @param array $commentarr Contains information on the comment.
  1256. * @return int Comment was updated if value is 1, or was not updated if value is 0.
  1257. */
  1258. function wp_update_comment($commentarr) {
  1259. global $wpdb;
  1260. // First, get all of the original fields
  1261. $comment = get_comment($commentarr['comment_ID'], ARRAY_A);
  1262. // Escape data pulled from DB.
  1263. $comment = esc_sql($comment);
  1264. $old_status = $comment['comment_approved'];
  1265. // Merge old and new fields with new fields overwriting old ones.
  1266. $commentarr = array_merge($comment, $commentarr);
  1267. $commentarr = wp_filter_comment( $commentarr );
  1268. // Now extract the merged array.
  1269. extract(stripslashes_deep($commentarr), EXTR_SKIP);
  1270. $comment_content = apply_filters('comment_save_pre', $comment_content);
  1271. $comment_date_gmt = get_gmt_from_date($comment_date);
  1272. if ( !isset($comment_approved) )
  1273. $comment_approved = 1;
  1274. else if ( 'hold' == $comment_approved )
  1275. $comment_approved = 0;
  1276. else if ( 'approve' == $comment_approved )
  1277. $comment_approved = 1;
  1278. $data = compact('comment_content', 'comment_author', 'comment_author_email', 'comment_approved', 'comment_karma', 'comment_author_url', 'comment_date', 'comment_date_gmt');
  1279. $rval = $wpdb->update( $wpdb->comments, $data, compact( 'comment_ID' ) );
  1280. clean_comment_cache($comment_ID);
  1281. wp_update_comment_count($comment_post_ID);
  1282. do_action('edit_comment', $comment_ID);
  1283. $comment = get_comment($comment_ID);
  1284. wp_transition_comment_status($comment->comment_approved, $old_status, $comment);
  1285. return $rval;
  1286. }
  1287. /**
  1288. * Whether to defer comment counting.
  1289. *
  1290. * When setting $defer to true, all post comment counts will not be updated
  1291. * until $defer is set to false. When $defer is set to false, then all
  1292. * previously deferred updated post comment counts will then be automatically
  1293. * updated without having to call wp_update_comment_count() after.
  1294. *
  1295. * @since 2.5.0
  1296. * @staticvar bool $_defer
  1297. *
  1298. * @param bool $defer
  1299. * @return unknown
  1300. */
  1301. function wp_defer_comment_counting($defer=null) {
  1302. static $_defer = false;
  1303. if ( is_bool($defer) ) {
  1304. $_defer = $defer;
  1305. // flush any deferred counts
  1306. if ( !$defer )
  1307. wp_update_comment_count( null, true );
  1308. }
  1309. return $_defer;
  1310. }
  1311. /**
  1312. * Updates the comment count for post(s).
  1313. *
  1314. * When $do_deferred is false (is by default) and the comments have been set to
  1315. * be deferred, the post_id will be added to a queue, which will be updated at a
  1316. * later date and only updated once per post ID.
  1317. *
  1318. * If the comments have not be set up to be deferred, then the post will be
  1319. * updated. When $do_deferred is set to true, then all previous deferred post
  1320. * IDs will be updated along with the current $post_id.
  1321. *
  1322. * @since 2.1.0
  1323. * @see wp_update_comment_count_now() For what could cause a false return value
  1324. *
  1325. * @param int $post_id Post ID
  1326. * @param bool $do_deferred Whether to process previously deferred post comment counts
  1327. * @return bool True on success, false on failure
  1328. */
  1329. function wp_update_comment_count($post_id, $do_deferred=false) {
  1330. static $_deferred = array();
  1331. if ( $do_deferred ) {
  1332. $_deferred = array_unique($_deferred);
  1333. foreach ( $_deferred as $i => $_post_id ) {
  1334. wp_update_comment_count_now($_post_id);
  1335. unset( $_deferred[$i] ); /** @todo Move this outside of the foreach and reset $_deferred to an array instead */
  1336. }
  1337. }
  1338. if ( wp_defer_comment_counting() ) {
  1339. $_deferred[] = $post_id;
  1340. return true;
  1341. }
  1342. elseif ( $post_id ) {
  1343. return wp_update_comment_count_now($post_id);
  1344. }
  1345. }
  1346. /**
  1347. * Updates the comment count for the post.
  1348. *
  1349. * @since 2.5.0
  1350. * @uses $wpdb
  1351. * @uses do_action() Calls 'wp_update_comment_count' hook on $post_id, $new, and $old
  1352. * @uses do_action() Calls 'edit_posts' hook on $post_id and $post
  1353. *
  1354. * @param int $post_id Post ID
  1355. * @return bool False on '0' $post_id or if post with ID does not exist. True on success.
  1356. */
  1357. function wp_update_comment_count_now($post_id) {
  1358. global $wpdb;
  1359. $post_id = (int) $post_id;
  1360. if ( !$post_id )
  1361. return false;
  1362. if ( !$post = get_post($post_id) )
  1363. return false;
  1364. $old = (int) $post->comment_count;
  1365. $new = (int) $wpdb->get_var( $wpdb->prepare("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved = '1'", $post_id) );
  1366. $wpdb->update( $wpdb->posts, array('comment_count' => $new), array('ID' => $post_id) );
  1367. if ( 'page' == $post->post_type )
  1368. clean_page_cache( $post_id );
  1369. else
  1370. clean_post_cache( $post_id );
  1371. do_action('wp_update_comment_count', $post_id, $new, $old);
  1372. do_action('edit_post', $post_id, $post);
  1373. return true;
  1374. }
  1375. //
  1376. // Ping and trackback functions.
  1377. //
  1378. /**
  1379. * Finds a pingback server URI based on the given URL.
  1380. *
  1381. * Checks the HTML for the rel="pingback" link and x-pingback headers. It does
  1382. * a check for the x-pingback headers first and returns that, if available. The
  1383. * check for the rel="pingback" has more overhead than just the header.
  1384. *
  1385. * @since 1.5.0
  1386. *
  1387. * @param string $url URL to ping.
  1388. * @param int $deprecated Not Used.
  1389. * @return bool|string False on failure, string containing URI on success.
  1390. */
  1391. function discover_pingback_server_uri( $url, $deprecated = '' ) {
  1392. if ( !empty( $deprecated ) )
  1393. _deprecated_argument( __FUNCTION__, '2.7' );
  1394. $pingback_str_dquote = 'rel="pingback"';
  1395. $pingback_str_squote = 'rel=\'pingback\'';
  1396. /** @todo Should use Filter Extension or custom preg_match instead. */
  1397. $parsed_url = parse_url($url);
  1398. if ( ! isset( $parsed_url['host'] ) ) // Not an URL. This should never happen.
  1399. return false;
  1400. //Do not search for a pingback server on our own uploads
  1401. $uploads_dir = wp_upload_dir();
  1402. if ( 0 === strpos($url, $uploads_dir['baseurl']) )
  1403. return false;
  1404. $response = wp_remote_head( $url, array( 'timeout' => 2, 'httpversion' => '1.0' ) );
  1405. if ( is_wp_error( $response ) )
  1406. return false;
  1407. if ( wp_remote_retrieve_header( $response, 'x-pingback' ) )
  1408. return wp_remote_retrieve_header( $response, 'x-pingback' );
  1409. // Not an (x)html, sgml, or xml page, no use going further.
  1410. if ( preg_match('#(image|audio|video|model)/#is', wp_remote_retrieve_header( $response, 'content-type' )) )
  1411. return false;
  1412. // Now do a GET since we're going to look in the html headers (and we're sure its not a binary file)
  1413. $response = wp_remote_get( $url, array( 'timeout' => 2, 'httpversion' => '1.0' ) );
  1414. if ( is_wp_error( $response ) )
  1415. return false;
  1416. $contents = wp_remote_retrieve_body( $response );
  1417. $pingback_link_offset_dquote = strpos($contents, $pingback_str_dquote);
  1418. $pingback_link_offset_squote = strpos($contents, $pingback_str_squote);
  1419. if ( $pingback_link_offset_dquote || $pingback_link_offset_squote ) {
  1420. $quote = ($pingback_link_offset_dquote) ? '"' : '\'';
  1421. $pingback_link_offset = ($quote=='"') ? $pingback_link_offset_dquote : $pingback_link_offset_squote;
  1422. $pingback_href_pos = @strpos($contents, 'href=', $pingback_link_offset);
  1423. $pingback_href_start = $pingback_href_pos+6;
  1424. $pingback_href_end = @strpos($contents, $quote, $pingback_href_start);
  1425. $pingback_server_url_len = $pingback_href_end - $pingback_href_start;
  1426. $pingback_server_url = substr($contents, $pingback_href_start, $pingback_server_url_len);
  1427. // We may find rel="pingback" but an incomplete pingback URL
  1428. if ( $pingback_server_url_len > 0 ) { // We got it!
  1429. return $pingback_server_url;
  1430. }
  1431. }
  1432. return false;
  1433. }
  1434. /**
  1435. * Perform all pingbacks, enclosures, trackbacks, and send to pingback services.
  1436. *
  1437. * @since 2.1.0
  1438. * @uses $wpdb
  1439. */
  1440. function do_all_pings() {
  1441. global $wpdb;
  1442. // Do pingbacks
  1443. while ($ping = $wpdb->get_row("SELECT ID, post_content, meta_id FROM {$wpdb->posts}, {$wpdb->postmeta} WHERE {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id AND {$wpdb->postmeta}.meta_key = '_pingme' LIMIT 1")) {
  1444. delete_metadata_by_mid( 'post', $ping->meta_id );
  1445. pingback( $ping->post_content, $ping->ID );
  1446. }
  1447. // Do Enclosures
  1448. while ($enclosure = $wpdb->get_row("SELECT ID, post_content, meta_id FROM {$wpdb->posts}, {$wpdb->postmeta} WHERE {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id AND {$wpdb->postmeta}.meta_key = '_encloseme' LIMIT 1")) {
  1449. delete_metadata_by_mid( 'post', $enclosure->meta_id );
  1450. do_enclose( $enclosure->post_content, $enclosure->ID );
  1451. }
  1452. // Do Trackbacks
  1453. $trackbacks = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE to_ping <> '' AND post_status = 'publish'");
  1454. if ( is_array($trackbacks) )
  1455. foreach ( $trackbacks as $trackback )
  1456. do_trackbacks($trackback);
  1457. //Do Update Services/Generic Pings
  1458. generic_ping();
  1459. }
  1460. /**
  1461. * Perform trackbacks.
  1462. *
  1463. * @since 1.5.0
  1464. * @uses $wpdb
  1465. *
  1466. * @param int $post_id Post ID to do trackbacks on.
  1467. */
  1468. function do_trackbacks($post_id) {
  1469. global $wpdb;
  1470. $post = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $post_id) );
  1471. $to_ping = get_to_ping($post_id);
  1472. $pinged = get_pung($post_id);
  1473. if ( empty($to_ping) ) {
  1474. $wpdb->update($wpdb->posts, array('to_ping' => ''), array('ID' => $post_id) );
  1475. return;
  1476. }
  1477. if ( empty($post->post_excerpt) )
  1478. $excerpt = apply_filters('the_content', $post->post_content);
  1479. else
  1480. $excerpt = apply_filters('the_excerpt', $post->post_excerpt);
  1481. $excerpt = str_replace(']]>', ']]&gt;', $excerpt);
  1482. $excerpt = wp_html_excerpt($excerpt, 252) . '...';
  1483. $post_title = apply_filters('the_title', $post->post_title, $post->ID);
  1484. $post_title = strip_tags($post_title);
  1485. if ( $to_ping ) {
  1486. foreach ( (array) $to_ping as $tb_ping ) {
  1487. $tb_ping = trim($tb_ping);
  1488. if ( !in_array($tb_ping, $pinged) ) {
  1489. trackback($tb_ping, $post_title, $excerpt, $post_id);
  1490. $pinged[] = $tb_ping;
  1491. } else {
  1492. $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s, '')) WHERE ID = %d", $tb_ping, $post_id) );
  1493. }
  1494. }
  1495. }
  1496. }
  1497. /**
  1498. * Sends pings to all of the ping site services.
  1499. *
  1500. * @since 1.2.0
  1501. *
  1502. * @param int $post_id Post ID. Not actually used.
  1503. * @return int Same as Post ID from parameter
  1504. */
  1505. function generic_ping($post_id = 0) {
  1506. $services = get_option('ping_sites');
  1507. $services = explode("\n", $services);
  1508. foreach ( (array) $services as $service ) {
  1509. $service = trim($service);
  1510. if ( '' != $service )
  1511. weblog_ping($service);
  1512. }
  1513. return $post_id;
  1514. }
  1515. /**
  1516. * Pings back the links found in a post.
  1517. *
  1518. * @since 0.71
  1519. * @uses $wp_version
  1520. * @uses IXR_Client
  1521. *
  1522. * @param string $content Post content to check for links.
  1523. * @param int $post_ID Post ID.
  1524. */
  1525. function pingback($content, $post_ID) {
  1526. global $wp_version;
  1527. include_once(ABSPATH . WPINC . '/class-IXR.php');
  1528. include_once(ABSPATH . WPINC . '/class-wp-http-ixr-client.php');
  1529. // original code by Mort (http://mort.mine.nu:8080)
  1530. $post_links = array();
  1531. $pung = get_pung($post_ID);
  1532. // Variables
  1533. $ltrs = '\w';
  1534. $gunk = '/#~:.?+=&%@!\-';
  1535. $punc = '.:?\-';
  1536. $any = $ltrs . $gunk . $punc;
  1537. // Step 1
  1538. // Parsing the post, external links (if any) are stored in the $post_links array
  1539. // This regexp comes straight from phpfreaks.com
  1540. // http://www.phpfreaks.com/quickcode/Extract_All_URLs_on_a_Page/15.php
  1541. preg_match_all("{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp);
  1542. // Step 2.
  1543. // Walking thru the links array
  1544. // first we get rid of links pointing to sites, not to specific files
  1545. // Example:
  1546. // http://dummy-weblog.org
  1547. // http://dummy-weblog.org/
  1548. // http://dummy-weblog.org/post.php
  1549. // We don't wanna ping first and second types, even if they have a valid <link/>
  1550. foreach ( (array) $post_links_temp[0] as $link_test ) :
  1551. if ( !in_array($link_test, $pung) && (url_to_postid($link_test) != $post_ID) // If we haven't pung it already and it isn't a link to itself
  1552. && !is_local_attachment($link_test) ) : // Also, let's never ping local attachments.
  1553. if ( $test = @parse_url($link_test) ) {
  1554. if ( isset($test['query']) )
  1555. $post_links[] = $link_test;
  1556. elseif ( isset( $test['path'] ) && ( $test['path'] != '/' ) && ( $test['path'] != '' ) )
  1557. $post_links[] = $link_test;
  1558. }
  1559. endif;
  1560. endforeach;
  1561. do_action_ref_array('pre_ping', array(&$post_links, &$pung));
  1562. foreach ( (array) $post_links as $pagelinkedto ) {
  1563. $pingback_server_url = discover_pingback_server_uri( $pagelinkedto );
  1564. if ( $pingback_server_url ) {
  1565. @ set_time_limit( 60 );
  1566. // Now, the RPC call
  1567. $pagelinkedfrom = get_permalink($post_ID);
  1568. // using a timeout of 3 seconds should be enough to cover slow servers
  1569. $client = new WP_HTTP_IXR_Client($pingback_server_url);
  1570. $client->timeout = 3;
  1571. $client->useragent = apply_filters( 'pingback_useragent', $client->useragent . ' -- WordPress/' . $wp_version, $client->useragent, $pingback_server_url, $pagelinkedto, $pagelinkedfrom);
  1572. // when set to true, this outputs debug messages by itself
  1573. $client->debug = false;
  1574. if ( $client->query('pingback.ping', $pagelinkedfrom, $pagelinkedto) || ( isset($client->error->code) && 48 == $client->error->code ) ) // Already registered
  1575. add_ping( $post_ID, $pagelinkedto );
  1576. }
  1577. }
  1578. }
  1579. /**
  1580. * Check whether blog is public before returning sites.
  1581. *
  1582. * @since 2.1.0
  1583. *
  1584. * @param mixed $sites Will return if blog is public, will not return if not public.
  1585. * @return mixed Empty string if blog is not public, returns $sites, if site is public.
  1586. */
  1587. function privacy_ping_filter($sites) {
  1588. if ( '0' != get_option('blog_public') )
  1589. return $sites;
  1590. else
  1591. return '';
  1592. }
  1593. /**
  1594. * Send a Trackback.
  1595. *
  1596. * Updates database when sending trackback to prevent duplicates.
  1597. *
  1598. * @since 0.71
  1599. * @uses $wpdb
  1600. *
  1601. * @param string $trackback_url URL to send trackbacks.
  1602. * @param string $title Title of post.
  1603. * @param string $excerpt Excerpt of post.
  1604. * @param int $ID Post ID.
  1605. * @return mixed Database query from update.
  1606. */
  1607. function trackback($trackback_url, $title, $excerpt, $ID) {
  1608. global $wpdb;
  1609. if ( empty($trackback_url) )
  1610. return;
  1611. $options = array();
  1612. $options['timeout'] = 4;
  1613. $options['body'] = array(
  1614. 'title' => $title,
  1615. 'url' => get_permalink($ID),
  1616. 'blog_name' => get_option('blogname'),
  1617. 'excerpt' => $excerpt
  1618. );
  1619. $response = wp_remote_post($trackback_url, $options);
  1620. if ( is_wp_error( $response ) )
  1621. return;
  1622. $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET pinged = CONCAT(pinged, '\n', %s) WHERE ID = %d", $trackback_url, $ID) );
  1623. return $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, %s, '')) WHERE ID = %d", $trackback_url, $ID) );
  1624. }
  1625. /**
  1626. * Send a pingback.
  1627. *
  1628. * @since 1.2.0
  1629. * @uses $wp_version
  1630. * @uses IXR_Client
  1631. *
  1632. * @param string $server Host of blog to connect to.
  1633. * @param string $path Path to send the ping.
  1634. */
  1635. function weblog_ping($server = '', $path = '') {
  1636. global $wp_version;
  1637. include_once(ABSPATH . WPINC . '/class-IXR.php');
  1638. include_once(ABSPATH . WPINC . '/class-wp-http-ixr-client.php');
  1639. // using a timeout of 3 seconds should be enough to cover slow servers
  1640. $client = new WP_HTTP_IXR_Client($server, ((!strlen(trim($path)) || ('/' == $path)) ? false : $path));
  1641. $client->timeout = 3;
  1642. $client->useragent .= ' -- WordPress/'.$wp_version;
  1643. // when set to true, this outputs debug messages by itself
  1644. $client->debug = false;
  1645. $home = trailingslashit( home_url() );
  1646. if ( !$client->query('weblogUpdates.extendedPing', get_option('blogname'), $home, get_bloginfo('rss2_url') ) ) // then try a normal ping
  1647. $client->query('weblogUpdates.ping', get_option('blogname'), $home);
  1648. }
  1649. //
  1650. // Cache
  1651. //
  1652. /**
  1653. * Removes comment ID from the comment cache.
  1654. *
  1655. * @since 2.3.0
  1656. * @package WordPress
  1657. * @subpackage Cache
  1658. *
  1659. * @param int|array $ids Comment ID or array of comment IDs to remove from cache
  1660. */
  1661. function clean_comment_cache($ids) {
  1662. foreach ( (array) $ids as $id )
  1663. wp_cache_delete($id, 'comment');
  1664. wp_cache_set('last_changed', time(), 'comment');
  1665. }
  1666. /**
  1667. * Updates the comment cache of given comments.
  1668. *
  1669. * Will add the comments in $comments to the cache. If comment ID already exists
  1670. * in the comment cache then it will not be updated. The comment is added to the
  1671. * cache using the comment group with the key using the ID of the comments.
  1672. *
  1673. * @since 2.3.0
  1674. * @package WordPress
  1675. * @subpackage Cache
  1676. *
  1677. * @param array $comments Array of comment row objects
  1678. */
  1679. function update_comment_cache($comments) {
  1680. foreach ( (array) $comments as $comment )
  1681. wp_cache_add($comment->comment_ID, $comment, 'comment');
  1682. }
  1683. //
  1684. // Internal
  1685. //
  1686. /**
  1687. * Close comments on old posts on the fly, without any extra DB queries. Hooked to the_posts.
  1688. *
  1689. * @access private
  1690. * @since 2.7.0
  1691. *
  1692. * @param object $posts Post data object.
  1693. * @param object $query Query object.
  1694. * @return object
  1695. */
  1696. function _close_comments_for_old_posts( $posts, $query ) {
  1697. if ( empty( $posts ) || ! $query->is_singular() || ! get_option( 'close_comments_for_old_posts' ) )
  1698. return $posts;
  1699. $post_types = apply_filters( 'close_comments_for_post_types', array( 'post' ) );
  1700. if ( ! in_array( $posts[0]->post_type, $post_types ) )
  1701. return $posts;
  1702. $days_old = (int) get_option( 'close_comments_days_old' );
  1703. if ( ! $days_old )
  1704. return $posts;
  1705. if ( time() - strtotime( $posts[0]->post_date_gmt ) > ( $days_old * 24 * 60 * 60 ) ) {
  1706. $posts[0]->comment_status = 'closed';
  1707. $posts[0]->ping_status = 'closed';
  1708. }
  1709. return $posts;
  1710. }
  1711. /**
  1712. * Close comments on an old post. Hooked to comments_open and pings_open.
  1713. *
  1714. * @access private
  1715. * @since 2.7.0
  1716. *
  1717. * @param bool $open Comments open or closed
  1718. * @param int $post_id Post ID
  1719. * @return bool $open
  1720. */
  1721. function _close_comments_for_old_post( $open, $post_id ) {
  1722. if ( ! $open )
  1723. return $open;
  1724. if ( !get_option('close_comments_for_old_posts') )
  1725. return $open;
  1726. $days_old = (int) get_option('close_comments_days_old');
  1727. if ( !$days_old )
  1728. return $open;
  1729. $post = get_post($post_id);
  1730. $post_types = apply_filters( 'close_comments_for_post_types', array( 'post' ) );
  1731. if ( ! in_array( $post->post_type, $post_types ) )
  1732. return $open;
  1733. if ( time() - strtotime( $post->post_date_gmt ) > ( $days_old * 24 * 60 * 60 ) )
  1734. return false;
  1735. return $open;
  1736. }
  1737. ?>