PageRenderTime 128ms CodeModel.GetById 21ms app.highlight 83ms RepoModel.GetById 1ms app.codeStats 1ms

/wp-includes/comment.php

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