PageRenderTime 61ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/comment.php

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