PageRenderTime 63ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

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

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

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