PageRenderTime 2372ms CodeModel.GetById 662ms app.highlight 582ms RepoModel.GetById 885ms app.codeStats 2ms

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

#
PHP | 825 lines | 610 code | 159 blank | 56 comment | 152 complexity | b06a7ad5df2da9d2af2879275d8ce556 MD5 | raw file
  1<?php
  2
  3function check_comment($author, $email, $url, $comment, $user_ip, $user_agent, $comment_type) {
  4	global $wpdb;
  5
  6	if ( 1 == get_option('comment_moderation') )
  7		return false; // If moderation is set to manual
  8
  9	if ( preg_match_all("|(href\t*?=\t*?['\"]?)?(https?:)?//|i", $comment, $out) >= get_option('comment_max_links') )
 10		return false; // Check # of external links
 11
 12	$mod_keys = trim(get_option('moderation_keys'));
 13	if ( !empty($mod_keys) ) {
 14		$words = explode("\n", $mod_keys );
 15
 16		foreach ($words as $word) {
 17			$word = trim($word);
 18
 19			// Skip empty lines
 20			if ( empty($word) )
 21				continue;
 22
 23			// Do some escaping magic so that '#' chars in the
 24			// spam words don't break things:
 25			$word = preg_quote($word, '#');
 26
 27			$pattern = "#$word#i";
 28			if ( preg_match($pattern, $author) ) return false;
 29			if ( preg_match($pattern, $email) ) return false;
 30			if ( preg_match($pattern, $url) ) return false;
 31			if ( preg_match($pattern, $comment) ) return false;
 32			if ( preg_match($pattern, $user_ip) ) return false;
 33			if ( preg_match($pattern, $user_agent) ) return false;
 34		}
 35	}
 36
 37	// Comment whitelisting:
 38	if ( 1 == get_option('comment_whitelist')) {
 39		if ( 'trackback' == $comment_type || 'pingback' == $comment_type ) { // check if domain is in blogroll
 40			$uri = parse_url($url);
 41			$domain = $uri['host'];
 42			$uri = parse_url( get_option('home') );
 43			$home_domain = $uri['host'];
 44			if ( $wpdb->get_var("SELECT link_id FROM $wpdb->links WHERE link_url LIKE ('%$domain%') LIMIT 1") || $domain == $home_domain )
 45				return true;
 46			else
 47				return false;
 48		} elseif ( $author != '' && $email != '' ) {
 49			$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");
 50			if ( ( 1 == $ok_to_comment ) &&
 51				( empty($mod_keys) || false === strpos( $email, $mod_keys) ) )
 52					return true;
 53			else
 54				return false;
 55		} else {
 56			return false;
 57		}
 58	}
 59	return true;
 60}
 61
 62
 63function get_approved_comments($post_id) {
 64	global $wpdb;
 65
 66	$post_id = (int) $post_id;
 67	return $wpdb->get_results("SELECT * FROM $wpdb->comments WHERE comment_post_ID = '$post_id' AND comment_approved = '1' ORDER BY comment_date");
 68}
 69
 70
 71// Retrieves comment data given a comment ID or comment object.
 72// Handles comment caching.
 73function &get_comment(&$comment, $output = OBJECT) {
 74	global $wpdb;
 75
 76	if ( empty($comment) ) {
 77		if ( isset($GLOBALS['comment']) )
 78			$_comment = & $GLOBALS['comment'];
 79		else
 80			$_comment = null;
 81	} elseif ( is_object($comment) ) {
 82		wp_cache_add($comment->comment_ID, $comment, 'comment');
 83		$_comment = $comment;
 84	} else {
 85		$comment = (int) $comment;
 86		if ( isset($GLOBALS['comment']) && ($GLOBALS['comment']->comment_ID == $comment) ) {
 87			$_comment = & $GLOBALS['comment'];
 88		} elseif ( ! $_comment = wp_cache_get($comment, 'comment') ) {
 89			$_comment = $wpdb->get_row("SELECT * FROM $wpdb->comments WHERE comment_ID = '$comment' LIMIT 1");
 90			wp_cache_add($_comment->comment_ID, $_comment, 'comment');
 91		}
 92	}
 93
 94	$_comment = apply_filters('get_comment', $_comment);
 95
 96	if ( $output == OBJECT ) {
 97		return $_comment;
 98	} elseif ( $output == ARRAY_A ) {
 99		return get_object_vars($_comment);
100	} elseif ( $output == ARRAY_N ) {
101		return array_values(get_object_vars($_comment));
102	} else {
103		return $_comment;
104	}
105}
106
107
108// Deprecate in favor of get_comment()?
109function get_commentdata( $comment_ID, $no_cache = 0, $include_unapproved = false ) { // less flexible, but saves DB queries
110	global $postc, $id, $commentdata, $wpdb;
111	if ( $no_cache ) {
112		$query = "SELECT * FROM $wpdb->comments WHERE comment_ID = '$comment_ID'";
113		if ( false == $include_unapproved )
114			$query .= " AND comment_approved = '1'";
115		$myrow = $wpdb->get_row($query, ARRAY_A);
116	} else {
117		$myrow['comment_ID']           = $postc->comment_ID;
118		$myrow['comment_post_ID']      = $postc->comment_post_ID;
119		$myrow['comment_author']       = $postc->comment_author;
120		$myrow['comment_author_email'] = $postc->comment_author_email;
121		$myrow['comment_author_url']   = $postc->comment_author_url;
122		$myrow['comment_author_IP']    = $postc->comment_author_IP;
123		$myrow['comment_date']         = $postc->comment_date;
124		$myrow['comment_content']      = $postc->comment_content;
125		$myrow['comment_karma']        = $postc->comment_karma;
126		$myrow['comment_approved']     = $postc->comment_approved;
127		$myrow['comment_type']         = $postc->comment_type;
128	}
129	return $myrow;
130}
131
132
133function get_lastcommentmodified($timezone = 'server') {
134	global $cache_lastcommentmodified, $pagenow, $wpdb;
135	$add_seconds_blog = get_option('gmt_offset') * 3600;
136	$add_seconds_server = date('Z');
137	$now = current_time('mysql', 1);
138	if ( !isset($cache_lastcommentmodified[$timezone]) ) {
139		switch ( strtolower($timezone)) {
140			case 'gmt':
141				$lastcommentmodified = $wpdb->get_var("SELECT comment_date_gmt FROM $wpdb->comments WHERE comment_date_gmt <= '$now' AND comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
142				break;
143			case 'blog':
144				$lastcommentmodified = $wpdb->get_var("SELECT comment_date FROM $wpdb->comments WHERE comment_date_gmt <= '$now' AND comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
145				break;
146			case 'server':
147				$lastcommentmodified = $wpdb->get_var("SELECT DATE_ADD(comment_date_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb->comments WHERE comment_date_gmt <= '$now' AND comment_approved = '1' ORDER BY comment_date_gmt DESC LIMIT 1");
148				break;
149		}
150		$cache_lastcommentmodified[$timezone] = $lastcommentmodified;
151	} else {
152		$lastcommentmodified = $cache_lastcommentmodified[$timezone];
153	}
154	return $lastcommentmodified;
155}
156
157
158function sanitize_comment_cookies() {
159	if ( isset($_COOKIE['comment_author_'.COOKIEHASH]) ) {
160		$comment_author = apply_filters('pre_comment_author_name', $_COOKIE['comment_author_'.COOKIEHASH]);
161		$comment_author = stripslashes($comment_author);
162		$comment_author = attribute_escape($comment_author);
163		$_COOKIE['comment_author_'.COOKIEHASH] = $comment_author;
164	}
165
166	if ( isset($_COOKIE['comment_author_email_'.COOKIEHASH]) ) {
167		$comment_author_email = apply_filters('pre_comment_author_email', $_COOKIE['comment_author_email_'.COOKIEHASH]);
168		$comment_author_email = stripslashes($comment_author_email);
169		$comment_author_email = attribute_escape($comment_author_email);
170		$_COOKIE['comment_author_email_'.COOKIEHASH] = $comment_author_email;
171	}
172
173	if ( isset($_COOKIE['comment_author_url_'.COOKIEHASH]) ) {
174		$comment_author_url = apply_filters('pre_comment_author_url', $_COOKIE['comment_author_url_'.COOKIEHASH]);
175		$comment_author_url = stripslashes($comment_author_url);
176		$_COOKIE['comment_author_url_'.COOKIEHASH] = $comment_author_url;
177	}
178}
179
180
181function wp_allow_comment($commentdata) {
182	global $wpdb;
183	extract($commentdata, EXTR_SKIP);
184
185	// Simple duplicate check
186	$dupe = "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = '$comment_post_ID' AND ( comment_author = '$comment_author' ";
187	if ( $comment_author_email )
188		$dupe .= "OR comment_author_email = '$comment_author_email' ";
189	$dupe .= ") AND comment_content = '$comment_content' LIMIT 1";
190	if ( $wpdb->get_var($dupe) )
191		wp_die( __('Duplicate comment detected; it looks as though you\'ve already said that!') );
192
193	do_action( 'check_comment_flood', $comment_author_IP, $comment_author_email, $comment_date_gmt );
194
195	if ( $user_id ) {
196		$userdata = get_userdata($user_id);
197		$user = new WP_User($user_id);
198		$post_author = $wpdb->get_var("SELECT post_author FROM $wpdb->posts WHERE ID = '$comment_post_ID' LIMIT 1");
199	}
200
201	if ( $userdata && ( $user_id == $post_author || $user->has_cap('level_9') ) ) {
202		// The author and the admins get respect.
203		$approved = 1;
204	 } else {
205		// Everyone else's comments will be checked.
206		if ( check_comment($comment_author, $comment_author_email, $comment_author_url, $comment_content, $comment_author_IP, $comment_agent, $comment_type) )
207			$approved = 1;
208		else
209			$approved = 0;
210		if ( wp_blacklist_check($comment_author, $comment_author_email, $comment_author_url, $comment_content, $comment_author_IP, $comment_agent) )
211			$approved = 'spam';
212	}
213
214	$approved = apply_filters('pre_comment_approved', $approved);
215	return $approved;
216}
217
218function check_comment_flood_db( $ip, $email, $date ) {
219	global $wpdb;
220	if ( $lasttime = $wpdb->get_var("SELECT comment_date_gmt FROM $wpdb->comments WHERE comment_author_IP = '$ip' OR comment_author_email = '$email' ORDER BY comment_date DESC LIMIT 1") ) {
221		$time_lastcomment = mysql2date('U', $lasttime);
222		$time_newcomment  = mysql2date('U', $date);
223		$flood_die = apply_filters('comment_flood_filter', false, $time_lastcomment, $time_newcomment);
224		if ( $flood_die ) {
225			do_action('comment_flood_trigger', $time_lastcomment, $time_newcomment);
226			wp_die( __('You are posting comments too quickly.  Slow down.') );
227		}
228	}
229}
230
231function wp_blacklist_check($author, $email, $url, $comment, $user_ip, $user_agent) {
232	global $wpdb;
233
234	do_action('wp_blacklist_check', $author, $email, $url, $comment, $user_ip, $user_agent);
235
236	if ( preg_match_all('/&#(\d+);/', $comment . $author . $url, $chars) ) {
237		foreach ( (array) $chars[1] as $char ) {
238			// If it's an encoded char in the normal ASCII set, reject
239			if ( 38 == $char )
240				continue; // Unless it's &
241			if ( $char < 128 )
242				return true;
243		}
244	}
245
246	$mod_keys = trim( get_option('blacklist_keys') );
247	if ( '' == $mod_keys )
248		return false; // If moderation keys are empty
249	$words = explode("\n", $mod_keys );
250
251	foreach ( (array) $words as $word ) {
252		$word = trim($word);
253
254		// Skip empty lines
255		if ( empty($word) ) { continue; }
256
257		// Do some escaping magic so that '#' chars in the
258		// spam words don't break things:
259		$word = preg_quote($word, '#');
260
261		$pattern = "#$word#i";
262		if (
263			   preg_match($pattern, $author)
264			|| preg_match($pattern, $email)
265			|| preg_match($pattern, $url)
266			|| preg_match($pattern, $comment)
267			|| preg_match($pattern, $user_ip)
268			|| preg_match($pattern, $user_agent)
269		 )
270			return true;
271	}
272	return false;
273}
274
275
276function wp_delete_comment($comment_id) {
277	global $wpdb;
278	do_action('delete_comment', $comment_id);
279
280	$comment = get_comment($comment_id);
281
282	if ( ! $wpdb->query("DELETE FROM $wpdb->comments WHERE comment_ID='$comment_id' LIMIT 1") )
283		return false;
284
285	$post_id = $comment->comment_post_ID;
286	if ( $post_id && $comment->comment_approved == 1 )
287		wp_update_comment_count($post_id);
288
289	clean_comment_cache($comment_id);
290
291	do_action('wp_set_comment_status', $comment_id, 'delete');
292	return true;
293}
294
295
296function wp_get_comment_status($comment_id) {
297	global $wpdb;
298
299	$comment = get_comment($comment_id);
300	if ( !$comment )
301		return false;
302
303	$approved = $comment->comment_approved;
304
305	if ( $approved == NULL )
306		return 'deleted';
307	elseif ( $approved == '1' )
308		return 'approved';
309	elseif ( $approved == '0' )
310		return 'unapproved';
311	elseif ( $approved == 'spam' )
312		return 'spam';
313	else
314		return false;
315}
316
317
318function wp_get_current_commenter() {
319	// Cookies should already be sanitized.
320
321	$comment_author = '';
322	if ( isset($_COOKIE['comment_author_'.COOKIEHASH]) )
323		$comment_author = $_COOKIE['comment_author_'.COOKIEHASH];
324
325	$comment_author_email = '';
326	if ( isset($_COOKIE['comment_author_email_'.COOKIEHASH]) )
327		$comment_author_email = $_COOKIE['comment_author_email_'.COOKIEHASH];
328
329	$comment_author_url = '';
330	if ( isset($_COOKIE['comment_author_url_'.COOKIEHASH]) )
331		$comment_author_url = $_COOKIE['comment_author_url_'.COOKIEHASH];
332
333	return compact('comment_author', 'comment_author_email', 'comment_author_url');
334}
335
336
337function wp_insert_comment($commentdata) {
338	global $wpdb;
339	extract($commentdata, EXTR_SKIP);
340
341	if ( ! isset($comment_author_IP) )
342		$comment_author_IP = preg_replace( '/[^0-9., ]/', '',$_SERVER['REMOTE_ADDR'] );
343	if ( ! isset($comment_date) )
344		$comment_date = current_time('mysql');
345	if ( ! isset($comment_date_gmt) )
346		$comment_date_gmt = get_gmt_from_date($comment_date);
347	if ( ! isset($comment_parent) )
348		$comment_parent = 0;
349	if ( ! isset($comment_approved) )
350		$comment_approved = 1;
351	if ( ! isset($user_id) )
352		$user_id = 0;
353
354	$result = $wpdb->query("INSERT INTO $wpdb->comments
355	(comment_post_ID, comment_author, comment_author_email, comment_author_url, comment_author_IP, comment_date, comment_date_gmt, comment_content, comment_approved, comment_agent, comment_type, comment_parent, user_id)
356	VALUES
357	('$comment_post_ID', '$comment_author', '$comment_author_email', '$comment_author_url', '$comment_author_IP', '$comment_date', '$comment_date_gmt', '$comment_content', '$comment_approved', '$comment_agent', '$comment_type', '$comment_parent', '$user_id')
358	");
359
360	$id = (int) $wpdb->insert_id;
361
362	if ( $comment_approved == 1)
363		wp_update_comment_count($comment_post_ID);
364
365	return $id;
366}
367
368
369function wp_filter_comment($commentdata) {
370	$commentdata['user_id']              = apply_filters('pre_user_id', $commentdata['user_ID']);
371	$commentdata['comment_agent']        = apply_filters('pre_comment_user_agent', $commentdata['comment_agent']);
372	$commentdata['comment_author']       = apply_filters('pre_comment_author_name', $commentdata['comment_author']);
373	$commentdata['comment_content']      = apply_filters('pre_comment_content', $commentdata['comment_content']);
374	$commentdata['comment_author_IP']    = apply_filters('pre_comment_user_ip', $commentdata['comment_author_IP']);
375	$commentdata['comment_author_url']   = apply_filters('pre_comment_author_url', $commentdata['comment_author_url']);
376	$commentdata['comment_author_email'] = apply_filters('pre_comment_author_email', $commentdata['comment_author_email']);
377	$commentdata['filtered'] = true;
378	return $commentdata;
379}
380
381
382function wp_throttle_comment_flood($block, $time_lastcomment, $time_newcomment) {
383	if ( $block ) // a plugin has already blocked... we'll let that decision stand
384		return $block;
385	if ( ($time_newcomment - $time_lastcomment) < 15 )
386		return true;
387	return false;
388}
389
390
391function wp_new_comment( $commentdata ) {
392	$commentdata = apply_filters('preprocess_comment', $commentdata);
393
394	$commentdata['comment_post_ID'] = (int) $commentdata['comment_post_ID'];
395	$commentdata['user_ID']         = (int) $commentdata['user_ID'];
396
397	$commentdata['comment_author_IP'] = preg_replace( '/[^0-9., ]/', '',$_SERVER['REMOTE_ADDR'] );
398	$commentdata['comment_agent']     = $_SERVER['HTTP_USER_AGENT'];
399
400	$commentdata['comment_date']     = current_time('mysql');
401	$commentdata['comment_date_gmt'] = current_time('mysql', 1);
402
403	$commentdata = wp_filter_comment($commentdata);
404
405	$commentdata['comment_approved'] = wp_allow_comment($commentdata);
406
407	$comment_ID = wp_insert_comment($commentdata);
408
409	do_action('comment_post', $comment_ID, $commentdata['comment_approved']);
410
411	if ( 'spam' !== $commentdata['comment_approved'] ) { // If it's spam save it silently for later crunching
412		if ( '0' == $commentdata['comment_approved'] )
413			wp_notify_moderator($comment_ID);
414
415		$post = &get_post($commentdata['comment_post_ID']); // Don't notify if it's your own comment
416
417		if ( get_option('comments_notify') && $commentdata['comment_approved'] && $post->post_author != $commentdata['user_ID'] )
418			wp_notify_postauthor($comment_ID, $commentdata['comment_type']);
419	}
420
421	return $comment_ID;
422}
423
424
425function wp_set_comment_status($comment_id, $comment_status) {
426	global $wpdb;
427
428	switch ( $comment_status ) {
429		case 'hold':
430			$query = "UPDATE $wpdb->comments SET comment_approved='0' WHERE comment_ID='$comment_id' LIMIT 1";
431			break;
432		case 'approve':
433			$query = "UPDATE $wpdb->comments SET comment_approved='1' WHERE comment_ID='$comment_id' LIMIT 1";
434			break;
435		case 'spam':
436			$query = "UPDATE $wpdb->comments SET comment_approved='spam' WHERE comment_ID='$comment_id' LIMIT 1";
437			break;
438		case 'delete':
439			return wp_delete_comment($comment_id);
440			break;
441		default:
442			return false;
443	}
444
445	if ( !$wpdb->query($query) )
446		return false;
447
448	clean_comment_cache($comment_id);
449
450	do_action('wp_set_comment_status', $comment_id, $comment_status);
451	$comment = get_comment($comment_id);
452	wp_update_comment_count($comment->comment_post_ID);
453
454	return true;
455}
456
457
458function wp_update_comment($commentarr) {
459	global $wpdb;
460
461	// First, get all of the original fields
462	$comment = get_comment($commentarr['comment_ID'], ARRAY_A);
463
464	// Escape data pulled from DB.
465	foreach ( (array) $comment as $key => $value )
466		$comment[$key] = $wpdb->escape($value);
467
468	// Merge old and new fields with new fields overwriting old ones.
469	$commentarr = array_merge($comment, $commentarr);
470
471	$commentarr = wp_filter_comment( $commentarr );
472
473	// Now extract the merged array.
474	extract($commentarr, EXTR_SKIP);
475
476	$comment_content = apply_filters('comment_save_pre', $comment_content);
477
478	$comment_date_gmt = get_gmt_from_date($comment_date);
479
480	$result = $wpdb->query(
481		"UPDATE $wpdb->comments SET
482			comment_content      = '$comment_content',
483			comment_author       = '$comment_author',
484			comment_author_email = '$comment_author_email',
485			comment_approved     = '$comment_approved',
486			comment_author_url   = '$comment_author_url',
487			comment_date         = '$comment_date',
488			comment_date_gmt     = '$comment_date_gmt'
489		WHERE comment_ID = $comment_ID" );
490
491	$rval = $wpdb->rows_affected;
492
493	clean_comment_cache($comment_ID);
494	wp_update_comment_count($comment_post_ID);
495	do_action('edit_comment', $comment_ID);
496	return $rval;
497}
498
499
500function wp_update_comment_count($post_id) {
501	global $wpdb, $comment_count_cache;
502	$post_id = (int) $post_id;
503	if ( !$post_id )
504		return false;
505	if ( !$post = get_post($post_id) )
506		return false;
507
508	$old = (int) $post->comment_count;
509	$new = (int) $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_post_ID = '$post_id' AND comment_approved = '1'");
510	$wpdb->query("UPDATE $wpdb->posts SET comment_count = '$new' WHERE ID = '$post_id'");
511	$comment_count_cache[$post_id] = $new;
512
513	if ( 'page' == $post->post_type )
514		clean_page_cache( $post_id );
515	else
516		clean_post_cache( $post_id );
517
518	do_action('wp_update_comment_count', $post_id, $new, $old);
519	do_action('edit_post', $post_id, $post);
520
521	return true;
522}
523
524
525//
526// Ping and trackback functions.
527//
528
529function discover_pingback_server_uri($url, $timeout_bytes = 2048) {
530	global $wp_version;
531
532	$byte_count = 0;
533	$contents = '';
534	$headers = '';
535	$pingback_str_dquote = 'rel="pingback"';
536	$pingback_str_squote = 'rel=\'pingback\'';
537	$x_pingback_str = 'x-pingback: ';
538	$pingback_href_original_pos = 27;
539
540	extract(parse_url($url), EXTR_SKIP);
541
542	if ( !isset($host) ) // Not an URL. This should never happen.
543		return false;
544
545	$path  = ( !isset($path) ) ? '/'          : $path;
546	$path .= ( isset($query) ) ? '?' . $query : '';
547	$port  = ( isset($port)  ) ? $port        : 80;
548
549	// Try to connect to the server at $host
550	$fp = @fsockopen($host, $port, $errno, $errstr, 2);
551	if ( !$fp ) // Couldn't open a connection to $host
552		return false;
553
554	// Send the GET request
555	$request = "GET $path HTTP/1.1\r\nHost: $host\r\nUser-Agent: WordPress/$wp_version \r\n\r\n";
556	// ob_end_flush();
557	fputs($fp, $request);
558
559	// Let's check for an X-Pingback header first
560	while ( !feof($fp) ) {
561		$line = fgets($fp, 512);
562		if ( trim($line) == '' )
563			break;
564		$headers .= trim($line)."\n";
565		$x_pingback_header_offset = strpos(strtolower($headers), $x_pingback_str);
566		if ( $x_pingback_header_offset ) {
567			// We got it!
568			preg_match('#x-pingback: (.+)#is', $headers, $matches);
569			$pingback_server_url = trim($matches[1]);
570			return $pingback_server_url;
571		}
572		if ( strpos(strtolower($headers), 'content-type: ') ) {
573			preg_match('#content-type: (.+)#is', $headers, $matches);
574			$content_type = trim($matches[1]);
575		}
576	}
577
578	if ( preg_match('#(image|audio|video|model)/#is', $content_type) ) // Not an (x)html, sgml, or xml page, no use going further
579		return false;
580
581	while ( !feof($fp) ) {
582		$line = fgets($fp, 1024);
583		$contents .= trim($line);
584		$pingback_link_offset_dquote = strpos($contents, $pingback_str_dquote);
585		$pingback_link_offset_squote = strpos($contents, $pingback_str_squote);
586		if ( $pingback_link_offset_dquote || $pingback_link_offset_squote ) {
587			$quote = ($pingback_link_offset_dquote) ? '"' : '\'';
588			$pingback_link_offset = ($quote=='"') ? $pingback_link_offset_dquote : $pingback_link_offset_squote;
589			$pingback_href_pos = @strpos($contents, 'href=', $pingback_link_offset);
590			$pingback_href_start = $pingback_href_pos+6;
591			$pingback_href_end = @strpos($contents, $quote, $pingback_href_start);
592			$pingback_server_url_len = $pingback_href_end - $pingback_href_start;
593			$pingback_server_url = substr($contents, $pingback_href_start, $pingback_server_url_len);
594			// We may find rel="pingback" but an incomplete pingback URL
595			if ( $pingback_server_url_len > 0 ) // We got it!
596				return $pingback_server_url;
597		}
598		$byte_count += strlen($line);
599		if ( $byte_count > $timeout_bytes ) {
600			// It's no use going further, there probably isn't any pingback
601			// server to find in this file. (Prevents loading large files.)
602			return false;
603		}
604	}
605
606	// We didn't find anything.
607	return false;
608}
609
610
611function do_all_pings() {
612	global $wpdb;
613
614	// Do pingbacks
615	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")) {
616		$wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE post_id = {$ping->ID} AND meta_key = '_pingme';");
617		pingback($ping->post_content, $ping->ID);
618	}
619
620	// Do Enclosures
621	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")) {
622		$wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE post_id = {$enclosure->ID} AND meta_key = '_encloseme';");
623		do_enclose($enclosure->post_content, $enclosure->ID);
624	}
625
626	// Do Trackbacks
627	$trackbacks = $wpdb->get_results("SELECT ID FROM $wpdb->posts WHERE CHAR_LENGTH(TRIM(to_ping)) > 7 AND post_status = 'publish'");
628	if ( is_array($trackbacks) ) {
629		foreach ( $trackbacks as $trackback )
630			do_trackbacks($trackback->ID);
631	}
632
633	//Do Update Services/Generic Pings
634	generic_ping();
635}
636
637function do_trackbacks($post_id) {
638	global $wpdb;
639
640	$post = $wpdb->get_row("SELECT * FROM $wpdb->posts WHERE ID = $post_id");
641	$to_ping = get_to_ping($post_id);
642	$pinged  = get_pung($post_id);
643	if ( empty($to_ping) ) {
644		$wpdb->query("UPDATE $wpdb->posts SET to_ping = '' WHERE ID = '$post_id'");
645		return;
646	}
647
648	if ( empty($post->post_excerpt) )
649		$excerpt = apply_filters('the_content', $post->post_content);
650	else
651		$excerpt = apply_filters('the_excerpt', $post->post_excerpt);
652	$excerpt = str_replace(']]>', ']]&gt;', $excerpt);
653	$excerpt = strip_tags($excerpt);
654	if ( function_exists('mb_strcut') ) // For international trackbacks
655    	$excerpt = mb_strcut($excerpt, 0, 252, get_option('blog_charset')) . '...';
656	else
657		$excerpt = substr($excerpt, 0, 252) . '...';
658
659	$post_title = apply_filters('the_title', $post->post_title);
660	$post_title = strip_tags($post_title);
661
662	if ( $to_ping ) {
663		foreach ( (array) $to_ping as $tb_ping ) {
664			$tb_ping = trim($tb_ping);
665			if ( !in_array($tb_ping, $pinged) ) {
666				trackback($tb_ping, $post_title, $excerpt, $post_id);
667				$pinged[] = $tb_ping;
668			} else {
669				$wpdb->query("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, '$tb_ping', '')) WHERE ID = '$post_id'");
670			}
671		}
672	}
673}
674
675
676function generic_ping($post_id = 0) {
677	$services = get_option('ping_sites');
678	$services = preg_replace("|(\s)+|", '$1', $services); // Kill dupe lines
679	$services = trim($services);
680	if ( '' != $services ) {
681		$services = explode("\n", $services);
682		foreach ( (array) $services as $service )
683			weblog_ping($service);
684	}
685
686	return $post_id;
687}
688
689
690function pingback($content, $post_ID) {
691	global $wp_version, $wpdb;
692	include_once(ABSPATH . WPINC . '/class-IXR.php');
693
694	// original code by Mort (http://mort.mine.nu:8080)
695	$post_links = array();
696
697	$pung = get_pung($post_ID);
698
699	// Variables
700	$ltrs = '\w';
701	$gunk = '/#~:.?+=&%@!\-';
702	$punc = '.:?\-';
703	$any = $ltrs . $gunk . $punc;
704
705	// Step 1
706	// Parsing the post, external links (if any) are stored in the $post_links array
707	// This regexp comes straight from phpfreaks.com
708	// http://www.phpfreaks.com/quickcode/Extract_All_URLs_on_a_Page/15.php
709	preg_match_all("{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp);
710
711	// Step 2.
712	// Walking thru the links array
713	// first we get rid of links pointing to sites, not to specific files
714	// Example:
715	// http://dummy-weblog.org
716	// http://dummy-weblog.org/
717	// http://dummy-weblog.org/post.php
718	// We don't wanna ping first and second types, even if they have a valid <link/>
719
720	foreach ( $post_links_temp[0] as $link_test ) :
721		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
722				&& !is_local_attachment($link_test) ) : // Also, let's never ping local attachments.
723			$test = parse_url($link_test);
724			if ( isset($test['query']) )
725				$post_links[] = $link_test;
726			elseif ( ($test['path'] != '/') && ($test['path'] != '') )
727				$post_links[] = $link_test;
728		endif;
729	endforeach;
730
731	do_action_ref_array('pre_ping', array(&$post_links, &$pung));
732
733	foreach ( (array) $post_links as $pagelinkedto ) {
734		$pingback_server_url = discover_pingback_server_uri($pagelinkedto, 2048);
735
736		if ( $pingback_server_url ) {
737			@ set_time_limit( 60 );
738			 // Now, the RPC call
739			$pagelinkedfrom = get_permalink($post_ID);
740
741			// using a timeout of 3 seconds should be enough to cover slow servers
742			$client = new IXR_Client($pingback_server_url);
743			$client->timeout = 3;
744			$client->useragent .= ' -- WordPress/' . $wp_version;
745
746			// when set to true, this outputs debug messages by itself
747			$client->debug = false;
748
749			if ( $client->query('pingback.ping', $pagelinkedfrom, $pagelinkedto) || ( isset($client->error->code) && 48 == $client->error->code ) ) // Already registered
750				add_ping( $post_ID, $pagelinkedto );
751		}
752	}
753}
754
755
756function privacy_ping_filter($sites) {
757	if ( '0' != get_option('blog_public') )
758		return $sites;
759	else
760		return '';
761}
762
763// Send a Trackback
764function trackback($trackback_url, $title, $excerpt, $ID) {
765	global $wpdb, $wp_version;
766
767	if ( empty($trackback_url) )
768		return;
769
770	$title = urlencode($title);
771	$excerpt = urlencode($excerpt);
772	$blog_name = urlencode(get_option('blogname'));
773	$tb_url = $trackback_url;
774	$url = urlencode(get_permalink($ID));
775	$query_string = "title=$title&url=$url&blog_name=$blog_name&excerpt=$excerpt";
776	$trackback_url = parse_url($trackback_url);
777	$http_request = 'POST ' . $trackback_url['path'] . ($trackback_url['query'] ? '?'.$trackback_url['query'] : '') . " HTTP/1.0\r\n";
778	$http_request .= 'Host: '.$trackback_url['host']."\r\n";
779	$http_request .= 'Content-Type: application/x-www-form-urlencoded; charset='.get_option('blog_charset')."\r\n";
780	$http_request .= 'Content-Length: '.strlen($query_string)."\r\n";
781	$http_request .= "User-Agent: WordPress/" . $wp_version;
782	$http_request .= "\r\n\r\n";
783	$http_request .= $query_string;
784	if ( '' == $trackback_url['port'] )
785		$trackback_url['port'] = 80;
786	$fs = @fsockopen($trackback_url['host'], $trackback_url['port'], $errno, $errstr, 4);
787	@fputs($fs, $http_request);
788	@fclose($fs);
789
790	$tb_url = addslashes( $tb_url );
791	$wpdb->query("UPDATE $wpdb->posts SET pinged = CONCAT(pinged, '\n', '$tb_url') WHERE ID = '$ID'");
792	return $wpdb->query("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, '$tb_url', '')) WHERE ID = '$ID'");
793}
794
795
796function weblog_ping($server = '', $path = '') {
797	global $wp_version;
798	include_once(ABSPATH . WPINC . '/class-IXR.php');
799
800	// using a timeout of 3 seconds should be enough to cover slow servers
801	$client = new IXR_Client($server, ((!strlen(trim($path)) || ('/' == $path)) ? false : $path));
802	$client->timeout = 3;
803	$client->useragent .= ' -- WordPress/'.$wp_version;
804
805	// when set to true, this outputs debug messages by itself
806	$client->debug = false;
807	$home = trailingslashit( get_option('home') );
808	if ( !$client->query('weblogUpdates.extendedPing', get_option('blogname'), $home, get_bloginfo('rss2_url') ) ) // then try a normal ping
809		$client->query('weblogUpdates.ping', get_option('blogname'), $home);
810}
811
812//
813// Cache
814//
815
816function clean_comment_cache($id) {
817	wp_cache_delete($id, 'comment');
818}
819
820function update_comment_cache($comments) {
821	foreach ( $comments as $comment )
822		wp_cache_add($comment->comment_ID, $comment, 'comment');
823}
824
825?>