PageRenderTime 99ms CodeModel.GetById 52ms RepoModel.GetById 2ms app.codeStats 0ms

/wp-includes/comment.php

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