PageRenderTime 58ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/comment.php

https://github.com/schr/wordpress
PHP | 1641 lines | 823 code | 235 blank | 583 comment | 232 complexity | 8572525a5c5081950d8885504505d6c7 MD5 | raw file

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("/<[Aa][^>]*[Hh][Rr][Ee][Ff]=['\"]([^\"'>]+)[^>]*>/", 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. /* translators: comment status */
  226. 'approve' => _x('Approved', 'adjective'),
  227. /* translators: comment status */
  228. 'spam' => _x('Spam', 'adjective'),
  229. );
  230. return $status;
  231. }
  232. /**
  233. * The date the last comment was modified.
  234. *
  235. * @since 1.5.0
  236. * @uses $wpdb
  237. * @global array $cache_lastcommentmodified
  238. *
  239. * @param string $timezone Which timezone to use in reference to 'gmt', 'blog',
  240. * or 'server' locations.
  241. * @return string Last comment modified date.
  242. */
  243. function get_lastcommentmodified($timezone = 'server') {
  244. global $cache_lastcommentmodified, $wpdb;
  245. if ( isset($cache_lastcommentmodified[$timezone]) )
  246. return $cache_lastcommentmodified[$timezone];
  247. $add_seconds_server = date('Z');
  248. switch ( strtolower($timezone)) {
  249. case 'gmt':
  250. $lastcommentmodified = $wpdb->get_var("SELECT comment_date_gmt FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
  251. break;
  252. case 'blog':
  253. $lastcommentmodified = $wpdb->get_var("SELECT comment_date FROM $wpdb->comments WHERE comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
  254. break;
  255. case 'server':
  256. $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));
  257. break;
  258. }
  259. $cache_lastcommentmodified[$timezone] = $lastcommentmodified;
  260. return $lastcommentmodified;
  261. }
  262. /**
  263. * The amount of comments in a post or total comments.
  264. *
  265. * A lot like {@link wp_count_comments()}, in that they both return comment
  266. * stats (albeit with different types). The {@link wp_count_comments()} actual
  267. * caches, but this function does not.
  268. *
  269. * @since 2.0.0
  270. * @uses $wpdb
  271. *
  272. * @param int $post_id Optional. Comment amount in post if > 0, else total comments blog wide.
  273. * @return array The amount of spam, approved, awaiting moderation, and total comments.
  274. */
  275. function get_comment_count( $post_id = 0 ) {
  276. global $wpdb;
  277. $post_id = (int) $post_id;
  278. $where = '';
  279. if ( $post_id > 0 ) {
  280. $where = $wpdb->prepare("WHERE comment_post_ID = %d", $post_id);
  281. }
  282. $totals = (array) $wpdb->get_results("
  283. SELECT comment_approved, COUNT( * ) AS total
  284. FROM {$wpdb->comments}
  285. {$where}
  286. GROUP BY comment_approved
  287. ", ARRAY_A);
  288. $comment_count = array(
  289. "approved" => 0,
  290. "awaiting_moderation" => 0,
  291. "spam" => 0,
  292. "total_comments" => 0
  293. );
  294. foreach ( $totals as $row ) {
  295. switch ( $row['comment_approved'] ) {
  296. case 'spam':
  297. $comment_count['spam'] = $row['total'];
  298. $comment_count["total_comments"] += $row['total'];
  299. break;
  300. case 1:
  301. $comment_count['approved'] = $row['total'];
  302. $comment_count['total_comments'] += $row['total'];
  303. break;
  304. case 0:
  305. $comment_count['awaiting_moderation'] = $row['total'];
  306. $comment_count['total_comments'] += $row['total'];
  307. break;
  308. default:
  309. break;
  310. }
  311. }
  312. return $comment_count;
  313. }
  314. /**
  315. * Sanitizes the cookies sent to the user already.
  316. *
  317. * Will only do anything if the cookies have already been created for the user.
  318. * Mostly used after cookies had been sent to use elsewhere.
  319. *
  320. * @since 2.0.4
  321. */
  322. function sanitize_comment_cookies() {
  323. if ( isset($_COOKIE['comment_author_'.COOKIEHASH]) ) {
  324. $comment_author = apply_filters('pre_comment_author_name', $_COOKIE['comment_author_'.COOKIEHASH]);
  325. $comment_author = stripslashes($comment_author);
  326. $comment_author = attribute_escape($comment_author);
  327. $_COOKIE['comment_author_'.COOKIEHASH] = $comment_author;
  328. }
  329. if ( isset($_COOKIE['comment_author_email_'.COOKIEHASH]) ) {
  330. $comment_author_email = apply_filters('pre_comment_author_email', $_COOKIE['comment_author_email_'.COOKIEHASH]);
  331. $comment_author_email = stripslashes($comment_author_email);
  332. $comment_author_email = attribute_escape($comment_author_email);
  333. $_COOKIE['comment_author_email_'.COOKIEHASH] = $comment_author_email;
  334. }
  335. if ( isset($_COOKIE['comment_author_url_'.COOKIEHASH]) ) {
  336. $comment_author_url = apply_filters('pre_comment_author_url', $_COOKIE['comment_author_url_'.COOKIEHASH]);
  337. $comment_author_url = stripslashes($comment_author_url);
  338. $_COOKIE['comment_author_url_'.COOKIEHASH] = $comment_author_url;
  339. }
  340. }
  341. /**
  342. * Validates whether this comment is allowed to be made or not.
  343. *
  344. * @since 2.0.0
  345. * @uses $wpdb
  346. * @uses apply_filters() Calls 'pre_comment_approved' hook on the type of comment
  347. * @uses do_action() Calls 'check_comment_flood' hook on $comment_author_IP, $comment_author_email, and $comment_date_gmt
  348. *
  349. * @param array $commentdata Contains information on the comment
  350. * @return mixed Signifies the approval status (0|1|'spam')
  351. */
  352. function wp_allow_comment($commentdata) {
  353. global $wpdb;
  354. extract($commentdata, EXTR_SKIP);
  355. // Simple duplicate check
  356. // expected_slashed ($comment_post_ID, $comment_author, $comment_author_email, $comment_content)
  357. $dupe = "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = '$comment_post_ID' AND ( comment_author = '$comment_author' ";
  358. if ( $comment_author_email )
  359. $dupe .= "OR comment_author_email = '$comment_author_email' ";
  360. $dupe .= ") AND comment_content = '$comment_content' LIMIT 1";
  361. if ( $wpdb->get_var($dupe) ) {
  362. if ( defined('DOING_AJAX') )
  363. die( __('Duplicate comment detected; it looks as though you\'ve already said that!') );
  364. wp_die( __('Duplicate comment detected; it looks as though you\'ve already said that!') );
  365. }
  366. do_action( 'check_comment_flood', $comment_author_IP, $comment_author_email, $comment_date_gmt );
  367. if ( $user_id ) {
  368. $userdata = get_userdata($user_id);
  369. $user = new WP_User($user_id);
  370. $post_author = $wpdb->get_var($wpdb->prepare("SELECT post_author FROM $wpdb->posts WHERE ID = %d LIMIT 1", $comment_post_ID));
  371. }
  372. if ( isset($userdata) && ( $user_id == $post_author || $user->has_cap('moderate_comments') ) ) {
  373. // The author and the admins get respect.
  374. $approved = 1;
  375. } else {
  376. // Everyone else's comments will be checked.
  377. if ( check_comment($comment_author, $comment_author_email, $comment_author_url, $comment_content, $comment_author_IP, $comment_agent, $comment_type) )
  378. $approved = 1;
  379. else
  380. $approved = 0;
  381. if ( wp_blacklist_check($comment_author, $comment_author_email, $comment_author_url, $comment_content, $comment_author_IP, $comment_agent) )
  382. $approved = 'spam';
  383. }
  384. $approved = apply_filters('pre_comment_approved', $approved);
  385. return $approved;
  386. }
  387. /**
  388. * Check whether comment flooding is occurring.
  389. *
  390. * Won't run, if current user can manage options, so to not block
  391. * administrators.
  392. *
  393. * @since 2.3.0
  394. * @uses $wpdb
  395. * @uses apply_filters() Calls 'comment_flood_filter' filter with first
  396. * parameter false, last comment timestamp, new comment timestamp.
  397. * @uses do_action() Calls 'comment_flood_trigger' action with parameters with
  398. * last comment timestamp and new comment timestamp.
  399. *
  400. * @param string $ip Comment IP.
  401. * @param string $email Comment author email address.
  402. * @param string $date MySQL time string.
  403. */
  404. function check_comment_flood_db( $ip, $email, $date ) {
  405. global $wpdb;
  406. if ( current_user_can( 'manage_options' ) )
  407. return; // don't throttle admins
  408. 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) ) ) {
  409. $time_lastcomment = mysql2date('U', $lasttime);
  410. $time_newcomment = mysql2date('U', $date);
  411. $flood_die = apply_filters('comment_flood_filter', false, $time_lastcomment, $time_newcomment);
  412. if ( $flood_die ) {
  413. do_action('comment_flood_trigger', $time_lastcomment, $time_newcomment);
  414. if ( defined('DOING_AJAX') )
  415. die( __('You are posting comments too quickly. Slow down.') );
  416. wp_die( __('You are posting comments too quickly. Slow down.'), '', array('response' => 403) );
  417. }
  418. }
  419. }
  420. /**
  421. * Separates an array of comments into an array keyed by comment_type.
  422. *
  423. * @since 2.7.0
  424. *
  425. * @param array $comments Array of comments
  426. * @return array Array of comments keyed by comment_type.
  427. */
  428. function &separate_comments(&$comments) {
  429. $comments_by_type = array('comment' => array(), 'trackback' => array(), 'pingback' => array(), 'pings' => array());
  430. $count = count($comments);
  431. for ( $i = 0; $i < $count; $i++ ) {
  432. $type = $comments[$i]->comment_type;
  433. if ( empty($type) )
  434. $type = 'comment';
  435. $comments_by_type[$type][] = &$comments[$i];
  436. if ( 'trackback' == $type || 'pingback' == $type )
  437. $comments_by_type['pings'][] = &$comments[$i];
  438. }
  439. return $comments_by_type;
  440. }
  441. /**
  442. * Calculate the total number of comment pages.
  443. *
  444. * @since 2.7.0
  445. * @uses get_query_var() Used to fill in the default for $per_page parameter.
  446. * @uses get_option() Used to fill in defaults for parameters.
  447. * @uses Walker_Comment
  448. *
  449. * @param array $comments Optional array of comment objects. Defaults to $wp_query->comments
  450. * @param int $per_page Optional comments per page.
  451. * @param boolean $threaded Optional control over flat or threaded comments.
  452. * @return int Number of comment pages.
  453. */
  454. function get_comment_pages_count( $comments = null, $per_page = null, $threaded = null ) {
  455. global $wp_query;
  456. if ( null === $comments && null === $per_page && null === $threaded && !empty($wp_query->max_num_comment_pages) )
  457. return $wp_query->max_num_comment_pages;
  458. if ( !$comments || !is_array($comments) )
  459. $comments = $wp_query->comments;
  460. if ( empty($comments) )
  461. return 0;
  462. if ( !isset($per_page) )
  463. $per_page = (int) get_query_var('comments_per_page');
  464. if ( 0 === $per_page )
  465. $per_page = (int) get_option('comments_per_page');
  466. if ( 0 === $per_page )
  467. return 1;
  468. if ( !isset($threaded) )
  469. $threaded = get_option('thread_comments');
  470. if ( $threaded ) {
  471. $walker = new Walker_Comment;
  472. $count = ceil( $walker->get_number_of_root_elements( $comments ) / $per_page );
  473. } else {
  474. $count = ceil( count( $comments ) / $per_page );
  475. }
  476. return $count;
  477. }
  478. /**
  479. * Calculate what page number a comment will appear on for comment paging.
  480. *
  481. * @since 2.7.0
  482. * @uses get_comment() Gets the full comment of the $comment_ID parameter.
  483. * @uses get_option() Get various settings to control function and defaults.
  484. * @uses get_page_of_comment() Used to loop up to top level comment.
  485. *
  486. * @param int $comment_ID Comment ID.
  487. * @param array $args Optional args.
  488. * @return int|null Comment page number or null on error.
  489. */
  490. function get_page_of_comment( $comment_ID, $args = array() ) {
  491. global $wpdb;
  492. if ( !$comment = get_comment( $comment_ID ) )
  493. return;
  494. $defaults = array( 'type' => 'all', 'page' => '', 'per_page' => '', 'max_depth' => '' );
  495. $args = wp_parse_args( $args, $defaults );
  496. if ( '' === $args['per_page'] && get_option('page_comments') )
  497. $args['per_page'] = get_query_var('comments_per_page');
  498. if ( empty($args['per_page']) ) {
  499. $args['per_page'] = 0;
  500. $args['page'] = 0;
  501. }
  502. if ( $args['per_page'] < 1 )
  503. return 1;
  504. if ( '' === $args['max_depth'] ) {
  505. if ( get_option('thread_comments') )
  506. $args['max_depth'] = get_option('thread_comments_depth');
  507. else
  508. $args['max_depth'] = -1;
  509. }
  510. // Find this comment's top level parent if threading is enabled
  511. if ( $args['max_depth'] > 1 && 0 != $comment->comment_parent )
  512. return get_page_of_comment( $comment->comment_parent, $args );
  513. $allowedtypes = array(
  514. 'comment' => '',
  515. 'pingback' => 'pingback',
  516. 'trackback' => 'trackback',
  517. );
  518. $comtypewhere = ( 'all' != $args['type'] && isset($allowedtypes[$args['type']]) ) ? " AND comment_type = '" . $allowedtypes[$args['type']] . "'" : '';
  519. // Count comments older than this one
  520. $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 ) );
  521. // No older comments? Then it's page #1.
  522. if ( 0 == $oldercoms )
  523. return 1;
  524. // Divide comments older than this one by comments per page to get this comment's page number
  525. return ceil( ( $oldercoms + 1 ) / $args['per_page'] );
  526. }
  527. /**
  528. * Does comment contain blacklisted characters or words.
  529. *
  530. * @since 1.5.0
  531. * @uses do_action() Calls 'wp_blacklist_check' hook for all parameters.
  532. *
  533. * @param string $author The author of the comment
  534. * @param string $email The email of the comment
  535. * @param string $url The url used in the comment
  536. * @param string $comment The comment content
  537. * @param string $user_ip The comment author IP address
  538. * @param string $user_agent The author's browser user agent
  539. * @return bool True if comment contains blacklisted content, false if comment does not
  540. */
  541. function wp_blacklist_check($author, $email, $url, $comment, $user_ip, $user_agent) {
  542. do_action('wp_blacklist_check', $author, $email, $url, $comment, $user_ip, $user_agent);
  543. if ( preg_match_all('/&#(\d+);/', $comment . $author . $url, $chars) ) {
  544. foreach ( (array) $chars[1] as $char ) {
  545. // If it's an encoded char in the normal ASCII set, reject
  546. if ( 38 == $char )
  547. continue; // Unless it's &
  548. if ( $char < 128 )
  549. return true;
  550. }
  551. }
  552. $mod_keys = trim( get_option('blacklist_keys') );
  553. if ( '' == $mod_keys )
  554. return false; // If moderation keys are empty
  555. $words = explode("\n", $mod_keys );
  556. foreach ( (array) $words as $word ) {
  557. $word = trim($word);
  558. // Skip empty lines
  559. if ( empty($word) ) { continue; }
  560. // Do some escaping magic so that '#' chars in the
  561. // spam words don't break things:
  562. $word = preg_quote($word, '#');
  563. $pattern = "#$word#i";
  564. if (
  565. preg_match($pattern, $author)
  566. || preg_match($pattern, $email)
  567. || preg_match($pattern, $url)
  568. || preg_match($pattern, $comment)
  569. || preg_match($pattern, $user_ip)
  570. || preg_match($pattern, $user_agent)
  571. )
  572. return true;
  573. }
  574. return false;
  575. }
  576. /**
  577. * Retrieve total comments for blog or single post.
  578. *
  579. * The properties of the returned object contain the 'moderated', 'approved',
  580. * and spam comments for either the entire blog or single post. Those properties
  581. * contain the amount of comments that match the status. The 'total_comments'
  582. * property contains the integer of total comments.
  583. *
  584. * The comment stats are cached and then retrieved, if they already exist in the
  585. * cache.
  586. *
  587. * @since 2.5.0
  588. *
  589. * @param int $post_id Optional. Post ID.
  590. * @return object Comment stats.
  591. */
  592. function wp_count_comments( $post_id = 0 ) {
  593. global $wpdb;
  594. $post_id = (int) $post_id;
  595. $stats = apply_filters('wp_count_comments', array(), $post_id);
  596. if ( !empty($stats) )
  597. return $stats;
  598. $count = wp_cache_get("comments-{$post_id}", 'counts');
  599. if ( false !== $count )
  600. return $count;
  601. $where = '';
  602. if( $post_id > 0 )
  603. $where = $wpdb->prepare( "WHERE comment_post_ID = %d", $post_id );
  604. $count = $wpdb->get_results( "SELECT comment_approved, COUNT( * ) AS num_comments FROM {$wpdb->comments} {$where} GROUP BY comment_approved", ARRAY_A );
  605. $total = 0;
  606. $approved = array('0' => 'moderated', '1' => 'approved', 'spam' => 'spam');
  607. $known_types = array_keys( $approved );
  608. foreach( (array) $count as $row_num => $row ) {
  609. $total += $row['num_comments'];
  610. if ( in_array( $row['comment_approved'], $known_types ) )
  611. $stats[$approved[$row['comment_approved']]] = $row['num_comments'];
  612. }
  613. $stats['total_comments'] = $total;
  614. foreach ( $approved as $key ) {
  615. if ( empty($stats[$key]) )
  616. $stats[$key] = 0;
  617. }
  618. $stats = (object) $stats;
  619. wp_cache_set("comments-{$post_id}", $stats, 'counts');
  620. return $stats;
  621. }
  622. /**
  623. * Removes comment ID and maybe updates post comment count.
  624. *
  625. * The post comment count will be updated if the comment was approved and has a
  626. * post ID available.
  627. *
  628. * @since 2.0.0
  629. * @uses $wpdb
  630. * @uses do_action() Calls 'delete_comment' hook on comment ID
  631. * @uses do_action() Calls 'wp_set_comment_status' hook on comment ID with 'delete' set for the second parameter
  632. * @uses wp_transition_comment_status() Passes new and old comment status along with $comment object
  633. *
  634. * @param int $comment_id Comment ID
  635. * @return bool False if delete comment query failure, true on success.
  636. */
  637. function wp_delete_comment($comment_id) {
  638. global $wpdb;
  639. do_action('delete_comment', $comment_id);
  640. $comment = get_comment($comment_id);
  641. if ( ! $wpdb->query( $wpdb->prepare("DELETE FROM $wpdb->comments WHERE comment_ID = %d LIMIT 1", $comment_id) ) )
  642. return false;
  643. // Move children up a level.
  644. $children = $wpdb->get_col( $wpdb->prepare("SELECT comment_ID FROM $wpdb->comments WHERE comment_parent = %d", $comment_id) );
  645. if ( !empty($children) ) {
  646. $wpdb->update($wpdb->comments, array('comment_parent' => $comment->comment_parent), array('comment_parent' => $comment_id));
  647. clean_comment_cache($children);
  648. }
  649. $post_id = $comment->comment_post_ID;
  650. if ( $post_id && $comment->comment_approved == 1 )
  651. wp_update_comment_count($post_id);
  652. clean_comment_cache($comment_id);
  653. do_action('wp_set_comment_status', $comment_id, 'delete');
  654. wp_transition_comment_status('delete', $comment->comment_approved, $comment);
  655. return true;
  656. }
  657. /**
  658. * The status of a comment by ID.
  659. *
  660. * @since 1.0.0
  661. *
  662. * @param int $comment_id Comment ID
  663. * @return string|bool Status might be 'deleted', 'approved', 'unapproved', 'spam'. False on failure.
  664. */
  665. function wp_get_comment_status($comment_id) {
  666. $comment = get_comment($comment_id);
  667. if ( !$comment )
  668. return false;
  669. $approved = $comment->comment_approved;
  670. if ( $approved == NULL )
  671. return 'deleted';
  672. elseif ( $approved == '1' )
  673. return 'approved';
  674. elseif ( $approved == '0' )
  675. return 'unapproved';
  676. elseif ( $approved == 'spam' )
  677. return 'spam';
  678. else
  679. return false;
  680. }
  681. /**
  682. * Call hooks for when a comment status transition occurs.
  683. *
  684. * Calls hooks for comment status transitions. If the new comment status is not the same
  685. * as the previous comment status, then two hooks will be ran, the first is
  686. * 'transition_comment_status' with new status, old status, and comment data. The
  687. * next action called is 'comment_OLDSTATUS_to_NEWSTATUS' the NEWSTATUS is the
  688. * $new_status parameter and the OLDSTATUS is $old_status parameter; it has the
  689. * comment data.
  690. *
  691. * The final action will run whether or not the comment statuses are the same. The
  692. * action is named 'comment_NEWSTATUS_COMMENTTYPE', NEWSTATUS is from the $new_status
  693. * parameter and COMMENTTYPE is comment_type comment data.
  694. *
  695. * @since 2.7.0
  696. *
  697. * @param string $new_status New comment status.
  698. * @param string $old_status Previous comment status.
  699. * @param object $comment Comment data.
  700. */
  701. function wp_transition_comment_status($new_status, $old_status, $comment) {
  702. // Translate raw statuses to human readable formats for the hooks
  703. // This is not a complete list of comment status, it's only the ones that need to be renamed
  704. $comment_statuses = array(
  705. 0 => 'unapproved',
  706. 'hold' => 'unapproved', // wp_set_comment_status() uses "hold"
  707. 1 => 'approved',
  708. 'approve' => 'approved', // wp_set_comment_status() uses "approve"
  709. );
  710. if ( isset($comment_statuses[$new_status]) ) $new_status = $comment_statuses[$new_status];
  711. if ( isset($comment_statuses[$old_status]) ) $old_status = $comment_statuses[$old_status];
  712. // Call the hooks
  713. if ( $new_status != $old_status ) {
  714. do_action('transition_comment_status', $new_status, $old_status, $comment);
  715. do_action("comment_${old_status}_to_$new_status", $comment);
  716. }
  717. do_action("comment_${new_status}_$comment->comment_type", $comment->comment_ID, $comment);
  718. }
  719. /**
  720. * Get current commenter's name, email, and URL.
  721. *
  722. * Expects cookies content to already be sanitized. User of this function might
  723. * wish to recheck the returned array for validity.
  724. *
  725. * @see sanitize_comment_cookies() Use to sanitize cookies
  726. *
  727. * @since 2.0.4
  728. *
  729. * @return array Comment author, email, url respectively.
  730. */
  731. function wp_get_current_commenter() {
  732. // Cookies should already be sanitized.
  733. $comment_author = '';
  734. if ( isset($_COOKIE['comment_author_'.COOKIEHASH]) )
  735. $comment_author = $_COOKIE['comment_author_'.COOKIEHASH];
  736. $comment_author_email = '';
  737. if ( isset($_COOKIE['comment_author_email_'.COOKIEHASH]) )
  738. $comment_author_email = $_COOKIE['comment_author_email_'.COOKIEHASH];
  739. $comment_author_url = '';
  740. if ( isset($_COOKIE['comment_author_url_'.COOKIEHASH]) )
  741. $comment_author_url = $_COOKIE['comment_author_url_'.COOKIEHASH];
  742. return compact('comment_author', 'comment_author_email', 'comment_author_url');
  743. }
  744. /**
  745. * Inserts a comment to the database.
  746. *
  747. * The available comment data key names are 'comment_author_IP', 'comment_date',
  748. * 'comment_date_gmt', 'comment_parent', 'comment_approved', and 'user_id'.
  749. *
  750. * @since 2.0.0
  751. * @uses $wpdb
  752. *
  753. * @param array $commentdata Contains information on the comment.
  754. * @return int The new comment's ID.
  755. */
  756. function wp_insert_comment($commentdata) {
  757. global $wpdb;
  758. extract(stripslashes_deep($commentdata), EXTR_SKIP);
  759. if ( ! isset($comment_author_IP) )
  760. $comment_author_IP = '';
  761. if ( ! isset($comment_date) )
  762. $comment_date = current_time('mysql');
  763. if ( ! isset($comment_date_gmt) )
  764. $comment_date_gmt = get_gmt_from_date($comment_date);
  765. if ( ! isset($comment_parent) )
  766. $comment_parent = 0;
  767. if ( ! isset($comment_approved) )
  768. $comment_approved = 1;
  769. if ( ! isset($comment_karma) )
  770. $comment_karma = 0;
  771. if ( ! isset($user_id) )
  772. $user_id = 0;
  773. if ( ! isset($comment_type) )
  774. $comment_type = '';
  775. $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');
  776. $wpdb->insert($wpdb->comments, $data);
  777. $id = (int) $wpdb->insert_id;
  778. if ( $comment_approved == 1 )
  779. wp_update_comment_count($comment_post_ID);
  780. $comment = get_comment($id);
  781. do_action('wp_insert_comment', $id, $comment);
  782. return $id;
  783. }
  784. /**
  785. * Filters and sanitizes comment data.
  786. *
  787. * Sets the comment data 'filtered' field to true when finished. This can be
  788. * checked as to whether the comment should be filtered and to keep from
  789. * filtering the same comment more than once.
  790. *
  791. * @since 2.0.0
  792. * @uses apply_filters() Calls 'pre_user_id' hook on comment author's user ID
  793. * @uses apply_filters() Calls 'pre_comment_user_agent' hook on comment author's user agent
  794. * @uses apply_filters() Calls 'pre_comment_author_name' hook on comment author's name
  795. * @uses apply_filters() Calls 'pre_comment_content' hook on the comment's content
  796. * @uses apply_filters() Calls 'pre_comment_user_ip' hook on comment author's IP
  797. * @uses apply_filters() Calls 'pre_comment_author_url' hook on comment author's URL
  798. * @uses apply_filters() Calls 'pre_comment_author_email' hook on comment author's email address
  799. *
  800. * @param array $commentdata Contains information on the comment.
  801. * @return array Parsed comment information.
  802. */
  803. function wp_filter_comment($commentdata) {
  804. $commentdata['user_id'] = apply_filters('pre_user_id', $commentdata['user_ID']);
  805. $commentdata['comment_agent'] = apply_filters('pre_comment_user_agent', $commentdata['comment_agent']);
  806. $commentdata['comment_author'] = apply_filters('pre_comment_author_name', $commentdata['comment_author']);
  807. $commentdata['comment_content'] = apply_filters('pre_comment_content', $commentdata['comment_content']);
  808. $commentdata['comment_author_IP'] = apply_filters('pre_comment_user_ip', $commentdata['comment_author_IP']);
  809. $commentdata['comment_author_url'] = apply_filters('pre_comment_author_url', $commentdata['comment_author_url']);
  810. $commentdata['comment_author_email'] = apply_filters('pre_comment_author_email', $commentdata['comment_author_email']);
  811. $commentdata['filtered'] = true;
  812. return $commentdata;
  813. }
  814. /**
  815. * Whether comment should be blocked because of comment flood.
  816. *
  817. * @since 2.1.0
  818. *
  819. * @param bool $block Whether plugin has already blocked comment.
  820. * @param int $time_lastcomment Timestamp for last comment.
  821. * @param int $time_newcomment Timestamp for new comment.
  822. * @return bool Whether comment should be blocked.
  823. */
  824. function wp_throttle_comment_flood($block, $time_lastcomment, $time_newcomment) {
  825. if ( $block ) // a plugin has already blocked... we'll let that decision stand
  826. return $block;
  827. if ( ($time_newcomment - $time_lastcomment) < 15 )
  828. return true;
  829. return false;
  830. }
  831. /**
  832. * Adds a new comment to the database.
  833. *
  834. * Filters new comment to ensure that the fields are sanitized and valid before
  835. * inserting comment into database. Calls 'comment_post' action with comment ID
  836. * and whether comment is approved by WordPress. Also has 'preprocess_comment'
  837. * filter for processing the comment data before the function handles it.
  838. *
  839. * @since 1.5.0
  840. * @uses apply_filters() Calls 'preprocess_comment' hook on $commentdata parameter array before processing
  841. * @uses do_action() Calls 'comment_post' hook on $comment_ID returned from adding the comment and if the comment was approved.
  842. * @uses wp_filter_comment() Used to filter comment before adding comment.
  843. * @uses wp_allow_comment() checks to see if comment is approved.
  844. * @uses wp_insert_comment() Does the actual comment insertion to the database.
  845. *
  846. * @param array $commentdata Contains information on the comment.
  847. * @return int The ID of the comment after adding.
  848. */
  849. function wp_new_comment( $commentdata ) {
  850. $commentdata = apply_filters('preprocess_comment', $commentdata);
  851. $commentdata['comment_post_ID'] = (int) $commentdata['comment_post_ID'];
  852. $commentdata['user_ID'] = (int) $commentdata['user_ID'];
  853. $commentdata['comment_parent'] = absint($commentdata['comment_parent']);
  854. $parent_status = ( 0 < $commentdata['comment_parent'] ) ? wp_get_comment_status($commentdata['comment_parent']) : '';
  855. $commentdata['comment_parent'] = ( 'approved' == $parent_status || 'unapproved' == $parent_status ) ? $commentdata['comment_parent'] : 0;
  856. $commentdata['comment_author_IP'] = preg_replace( '/[^0-9a-fA-F:., ]/', '',$_SERVER['REMOTE_ADDR'] );
  857. $commentdata['comment_agent'] = $_SERVER['HTTP_USER_AGENT'];
  858. $commentdata['comment_date'] = current_time('mysql');
  859. $commentdata['comment_date_gmt'] = current_time('mysql', 1);
  860. $commentdata = wp_filter_comment($commentdata);
  861. $commentdata['comment_approved'] = wp_allow_comment($commentdata);
  862. $comment_ID = wp_insert_comment($commentdata);
  863. do_action('comment_post', $comment_ID, $commentdata['comment_approved']);
  864. if ( 'spam' !== $commentdata['comment_approved'] ) { // If it's spam save it silently for later crunching
  865. if ( '0' == $commentdata['comment_approved'] )
  866. wp_notify_moderator($comment_ID);
  867. $post = &get_post($commentdata['comment_post_ID']); // Don't notify if it's your own comment
  868. if ( get_option('comments_notify') && $commentdata['comment_approved'] && $post->post_author != $commentdata['user_ID'] )
  869. wp_notify_postauthor($comment_ID, $commentdata['comment_type']);
  870. }
  871. return $comment_ID;
  872. }
  873. /**
  874. * Sets the status of a comment.
  875. *
  876. * The 'wp_set_comment_status' action is called after the comment is handled and
  877. * will only be called, if the comment status is either 'hold', 'approve', or
  878. * 'spam'. If the comment status is not in the list, then false is returned and
  879. * if the status is 'delete', then the comment is deleted without calling the
  880. * action.
  881. *
  882. * @since 1.0.0
  883. * @uses wp_transition_comment_status() Passes new and old comment status along with $comment object
  884. *
  885. * @param int $comment_id Comment ID.
  886. * @param string $comment_status New comment status, either 'hold', 'approve', 'spam', or 'delete'.
  887. * @param bool $wp_error Whether to return a WP_Error object if there is a failure. Default is false.
  888. * @return bool False on failure or deletion and true on success.
  889. */
  890. function wp_set_comment_status($comment_id, $comment_status, $wp_error = false) {
  891. global $wpdb;
  892. $status = '0';
  893. switch ( $comment_status ) {
  894. case 'hold':
  895. $status = '0';
  896. break;
  897. case 'approve':
  898. $status = '1';
  899. if ( get_option('comments_notify') ) {
  900. $comment = get_comment($comment_id);
  901. wp_notify_postauthor($comment_id, $comment->comment_type);
  902. }
  903. break;
  904. case 'spam':
  905. $status = 'spam';
  906. break;
  907. case 'delete':
  908. return wp_delete_comment($comment_id);
  909. break;
  910. default:
  911. return false;
  912. }
  913. if ( !$wpdb->update( $wpdb->comments, array('comment_approved' => $status), array('comment_ID' => $comment_id) ) ) {
  914. if ( $wp_error )
  915. return new WP_Error('db_update_error', __('Could not update comment status'), $wpdb->last_error);
  916. else
  917. return false;
  918. }
  919. clean_comment_cache($comment_id);
  920. $comment = get_comment($comment_id);
  921. do_action('wp_set_comment_status', $comment_id, $comment_status);
  922. wp_transition_comment_status($comment_status, $comment->comment_approved, $comment);
  923. wp_update_comment_count($comment->comment_post_ID);
  924. return true;
  925. }
  926. /**
  927. * Updates an existing comment in the database.
  928. *
  929. * Filters the comment and makes sure certain fields are valid before updating.
  930. *
  931. * @since 2.0.0
  932. * @uses $wpdb
  933. * @uses wp_transition_comment_status() Passes new and old comment status along with $comment object
  934. *
  935. * @param array $commentarr Contains information on the comment.
  936. * @return int Comment was updated if value is 1, or was not updated if value is 0.
  937. */
  938. function wp_update_comment($commentarr) {
  939. global $wpdb;
  940. // First, get all of the original fields
  941. $comment = get_comment($commentarr['comment_ID'], ARRAY_A);
  942. // Escape data pulled from DB.
  943. $comment = $wpdb->escape($comment);
  944. // Merge old and new fields with new fields overwriting old ones.
  945. $commentarr = array_merge($comment, $commentarr);
  946. $commentarr = wp_filter_comment( $commentarr );
  947. // Now extract the merged array.
  948. extract(stripslashes_deep($commentarr), EXTR_SKIP);
  949. $comment_content = apply_filters('comment_save_pre', $comment_content);
  950. $comment_date_gmt = get_gmt_from_date($comment_date);
  951. if ( !isset($comment_approved) )
  952. $comment_approved = 1;
  953. else if ( 'hold' == $comment_approved )
  954. $comment_approved = 0;
  955. else if ( 'approve' == $comment_approved )
  956. $comment_approved = 1;
  957. $data = compact('comment_content', 'comment_author', 'comment_author_email', 'comment_approved', 'comment_karma', 'comment_author_url', 'comment_date', 'comment_date_gmt');
  958. $wpdb->update($wpdb->comments, $data, compact('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->update( $wpdb->posts, array('comment_count' => $new), array('ID' => $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. //Do not search for a pingback server on our own uploads
  1079. $uploads_dir = wp_upload_dir();
  1080. if ( 0 === strpos($url, $uploads_dir['baseurl']) )
  1081. return false;
  1082. $response = wp_remote_head( $url, array( 'timeout' => 2, 'httpversion' => '1.0' ) );
  1083. if ( is_wp_error( $response ) )
  1084. return false;
  1085. if ( isset( $response['headers']['x-pingback'] ) )
  1086. return $response['headers']['x-pingback'];
  1087. // Not an (x)html, sgml, or xml page, no use going further.
  1088. if ( isset( $response['headers']['content-type'] ) && preg_match('#(image|audio|video|model)/#is', $response['headers']['content-type']) )
  1089. return false;
  1090. // Now do a GET since we're going to look in the html headers (and we're sure its not a binary file)
  1091. $response = wp_remote_get( $url, array( 'timeout' => 2, 'httpversion' => '1.0' ) );
  1092. if ( is_wp_error( $response ) )
  1093. return false;
  1094. $contents = $response['body'];
  1095. $pingback_link_offset_dquote = strpos($contents, $pingback_str_dquote);
  1096. $pingback_link_offset_squote = strpos($contents, $pingback_str_squote);
  1097. if ( $pingback_link_offset_dquote || $pingback_link_offset_squote ) {
  1098. $quote = ($pingback_link_offset_dquote) ? '"' : '\'';
  1099. $pingback_link_offset = ($quote=='"') ? $pingback_link_offset_dquote : $pingback_link_offset_squote;
  1100. $pingback_href_pos = @strpos($contents, 'href=', $pingback_link_offset);
  1101. $pingback_href_start = $pingback_href_pos+6;
  1102. $pingback_href_end = @strpos($contents, $quote, $pingback_href_start);
  1103. $pingback_server_url_len = $pingback_href_end - $pingback_href_start;
  1104. $pingback_server_url = substr($contents, $pingback_href_start, $pingback_server_url_len);
  1105. // We may find rel="pingback" but an incomplete pingback URL
  1106. if ( $pingback_server_url_len > 0 ) { // We got it!
  1107. return $pingback_server_url;
  1108. }
  1109. }
  1110. return false;
  1111. }
  1112. /**
  1113. * Perform all pingbacks, enclosures, trackbacks, and send to pingback services.
  1114. *
  1115. * @since 2.1.0
  1116. * @uses $wpdb
  1117. */
  1118. function do_all_pings() {
  1119. global $wpdb;
  1120. // Do pingbacks
  1121. 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")) {
  1122. $wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE post_id = {$ping->ID} AND meta_key = '_pingme';");
  1123. pingback($ping->post_content, $ping->ID);
  1124. }
  1125. // Do Enclosures
  1126. 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")) {
  1127. $wpdb->query( $wpdb->prepare("DELETE FROM {$wpdb->postmeta} WHERE post_id = %d AND meta_key = '_encloseme';", $enclosure->ID) );
  1128. do_enclose($enclosure->post_content, $enclosure->ID);
  1129. }
  1130. // Do Trackbacks
  1131. $trackbacks = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE to_ping <> '' AND post_status = 'publish'");
  1132. if ( is_array($trackbacks) )
  1133. foreach ( $trackbacks as $trackback )
  1134. do_trackbacks($trackback);
  1135. //Do Update Services/Generic Pings
  1136. generic_ping();
  1137. }
  1138. /**
  1139. * Perform trackbacks.
  1140. *
  1141. * @since 1.5.0
  1142. * @uses $wpdb
  1143. *
  1144. * @param int $post_id Post ID to do trackbacks on.
  1145. */
  1146. function do_trackbacks($post_id) {
  1147. global $wpdb;
  1148. $post = $wpdb->get_row( $wpdb->prepare("SELECT * FROM $wpdb->posts WHERE ID = %d", $post_id) );
  1149. $to_ping = get_to_ping($post_id);
  1150. $pinged = get_pung($post_id);
  1151. if ( empty($to_ping) ) {
  1152. $wpdb->update($wpdb->posts, array('to_ping' => ''), array('ID' => $post_id) );
  1153. return;
  1154. }
  1155. if ( empty($post->post_excerpt) )
  1156. $excerpt = apply_filters('the_content', $post->post_content);
  1157. else
  1158. $excerpt = apply_filters('the_excerpt', $post->post_excerpt);
  1159. $excerpt = str_replace(']]>', ']]&gt;', $excerpt);
  1160. $excerpt = wp_html_excerpt($excerpt, 252) . '...';
  1161. $post_title = apply_filters('the_title', $post->post_title);
  1162. $post_title = strip_tags($post_title);
  1163. if ( $to_ping ) {
  1164. foreach ( (array) $to_ping as $tb_ping ) {
  1165. $tb_ping = trim($tb_ping);
  1166. if ( !in_array($tb_ping, $pinged) ) {
  1167. trackback($tb_ping, $post_title, $excerpt, $post_id);
  1168. $pinged[] = $tb_ping;
  1169. } else {
  1170. $wpdb->query( $wpdb->prepare("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, '$tb_ping', '')) WHERE ID = %d", $post_id) );
  1171. }
  1172. }
  1173. }
  1174. }
  1175. /**
  1176. * Sends pings to all of the ping site services.
  1177. *
  1178. * @since 1.2.0
  1179. *
  1180. * @param int $post_id Post ID. Not actually used.
  1181. * @return int Same as Post ID from parameter
  1182. */
  1183. function generic_ping($post_id = 0) {
  1184. $services = get_option('ping_sites');
  1185. $services = explode("\n", $services);
  1186. foreach ( (array) $services as $service ) {
  1187. $service = trim($service);
  1188. if ( '' != $service )
  1189. weblog_ping($service);
  1190. }
  1191. return $post_id;
  1192. }
  1193. /**
  1194. * Pings back the links found in a post.
  1195. *
  1196. * @since 0.71
  1197. * @uses $wp_version
  1198. * @uses IXR_Client
  1199. *
  1200. * @param string $content Post content to check for links.
  1201. * @param int $post_ID Post ID.
  1202. */
  1203. function pingback($content, $post_ID) {
  1204. global $wp_version;
  1205. include_once(ABSPATH . WPINC . '/class-IXR.php');
  1206. // original code by Mort (http://mort.mine.nu:8080)
  1207. $post_links = array();
  1208. $pung = get_pung($post_ID);
  1209. // Variables
  1210. $ltrs = '\w';
  1211. $gunk = '/#~:.?+=&%@!\-';
  1212. $punc = '.:?\-';
  1213. $any = $ltrs . $gunk . $punc;
  1214. // Step 1
  1215. // Parsing the post, external links (if any) are stored in the $post_links array
  1216. // This regexp comes straight from phpfreaks.com
  1217. // http://www.phpfreaks.com/quickcode/Extract_All_URLs_on_a_Page/15.php
  1218. preg_match_all("{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp);
  1219. // Step 2.
  1220. // Walking thru the links array
  1221. // first we get rid of links pointing to sites, not to specific files
  1222. // Example:
  1223. // http://dummy-weblog.org
  1224. // http://dummy-weblog.org/
  1225. // http://dummy-weblog.org/post.php
  1226. // We don't wanna ping first and second types, even if they have a valid <link/>
  1227. foreach ( (array) $post_links_temp[0] as $link_test ) :
  1228. 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
  1229. && !is_local_attachment($link_test) ) : // Also, let's never ping local attachments.
  1230. if ( $test = @parse_url($link_test) ) {
  1231. if ( isset($test['query']) )
  1232. $post_links[] = $link_test;
  1233. elseif ( ($test['path'] != '/') && ($test['path'] != '') )
  1234. $post_links[] = $link_test;
  1235. }
  1236. endif;
  1237. endforeach;
  1238. do_action_ref_array('pre_ping', array(&$post_links, &$pung));
  1239. foreach ( (array) $post_links as $pagelinkedto ) {
  1240. $pingback_server_url = discover_pingback_server_uri($pagelinkedto, 2048);
  1241. if ( $pingback_server_url ) {
  1242. @ set_time_limit( 60 );
  1243. // Now, the RPC call
  1244. $pagelinkedfrom = get_permalink($post_ID);
  1245. // using a timeout of 3 seconds should be enough to cover slow servers
  1246. $client = new IXR_Client($pingback_server_url);
  1247. $client->timeout = 3;
  1248. $client->useragent .= ' -- WordPress/' . $wp_version;
  1249. // when set to true, this outputs debug messages by itself
  1250. $client->debug = false;
  1251. if ( $client->query('pingback.ping', $pagelinkedfrom, $pagelinkedto) || ( isset($client->error->code) && 48 == $client->error->code ) ) // Already registered
  1252. add_ping( $post_ID, $pagelinkedto );
  1253. }
  1254. }
  1255. }
  1256. /**
  1257. * Check whether blog is public before returning sites.
  1258. *
  1259. * @since 2.1.0
  1260. *
  1261. * @param mixed $sites Will return if blog is public, will not return if not public.
  1262. * @return mixed Empty string if blog is not public, returns $sites, if si…

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