PageRenderTime 353ms CodeModel.GetById 121ms app.highlight 147ms RepoModel.GetById 74ms app.codeStats 1ms

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

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