PageRenderTime 49ms CodeModel.GetById 11ms RepoModel.GetById 1ms app.codeStats 0ms

/tags/2.7/wp-includes/comment.php

#
PHP | 1627 lines | 826 code | 226 blank | 575 comment | 225 complexity | 1f8479ac86b56dbf1ef620811a4f0379 MD5 | raw file
Possible License(s): AGPL-1.0, LGPL-2.0, LGPL-2.1, GPL-2.0

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

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

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