Wordpress 2.0.2
[autoinstalls/wordpress.git] / wp-includes / comment-functions.php
1 <?php
2
3 // Template functions
4
5 function comments_template( $file = '/comments.php' ) {
6         global $wp_query, $withcomments, $post, $wpdb, $id, $comment, $user_login, $user_ID, $user_identity;
7
8         if ( is_single() || is_page() || $withcomments ) :
9                 $req = get_settings('require_name_email');
10                 $comment_author = '';
11                 if ( isset($_COOKIE['comment_author_'.COOKIEHASH]) ) {
12                         $comment_author = apply_filters('pre_comment_author_name', $_COOKIE['comment_author_'.COOKIEHASH]);
13                         $comment_author = stripslashes($comment_author);
14                         $comment_author = wp_specialchars($comment_author, true);
15                 }
16                 $comment_author_email = '';
17                 if ( isset($_COOKIE['comment_author_email_'.COOKIEHASH]) ) {
18                         $comment_author_email = apply_filters('pre_comment_author_email', $_COOKIE['comment_author_email_'.COOKIEHASH]);
19                         $comment_author_email = stripslashes($comment_author_email);
20                         $comment_author_email = wp_specialchars($comment_author_email, true);           
21                 }
22                 $comment_author_url = '';
23                 if ( isset($_COOKIE['comment_author_url_'.COOKIEHASH]) ) {
24                         $comment_author_url = apply_filters('pre_comment_author_url', $_COOKIE['comment_author_url_'.COOKIEHASH]);
25                         $comment_author_url = stripslashes($comment_author_url);
26                         $comment_author_url = wp_specialchars($comment_author_url, true);               
27                 }
28
29         if ( empty($comment_author) ) {
30                 $comments = $wpdb->get_results("SELECT * FROM $wpdb->comments WHERE comment_post_ID = '$post->ID' AND comment_approved = '1' ORDER BY comment_date");
31         } else {
32                 $author_db = $wpdb->escape($comment_author);
33                 $email_db  = $wpdb->escape($comment_author_email);
34                 $comments = $wpdb->get_results("SELECT * FROM $wpdb->comments WHERE comment_post_ID = '$post->ID' AND ( comment_approved = '1' OR ( comment_author = '$author_db' AND comment_author_email = '$email_db' AND comment_approved = '0' ) ) ORDER BY comment_date");
35         }
36
37         get_currentuserinfo();
38
39         define('COMMENTS_TEMPLATE', true);
40         $include = apply_filters('comments_template', TEMPLATEPATH . $file );
41         if ( file_exists( $include ) )
42                 require( $include );
43         else
44                 require( ABSPATH . 'wp-content/themes/default/comments.php');
45
46         endif;
47 }
48
49 function wp_new_comment( $commentdata ) {
50         $commentdata = apply_filters('preprocess_comment', $commentdata);
51
52         $commentdata['comment_post_ID'] = (int) $commentdata['comment_post_ID'];
53         $commentdata['user_ID']         = (int) $commentdata['user_ID'];
54
55         $commentdata['comment_author_IP'] = $_SERVER['REMOTE_ADDR'];
56         $commentdata['comment_agent']     = $_SERVER['HTTP_USER_AGENT'];
57
58         $commentdata['comment_date']     = current_time('mysql');
59         $commentdata['comment_date_gmt'] = current_time('mysql', 1);
60         
61
62         $commentdata = wp_filter_comment($commentdata);
63
64         $commentdata['comment_approved'] = wp_allow_comment($commentdata);
65
66         $comment_ID = wp_insert_comment($commentdata);
67
68         do_action('comment_post', $comment_ID, $commentdata['comment_approved']);
69
70         if ( 'spam' !== $commentdata['comment_approved'] ) { // If it's spam save it silently for later crunching
71                 if ( '0' == $commentdata['comment_approved'] )
72                         wp_notify_moderator($comment_ID);
73
74                 $post = &get_post($commentdata['comment_post_ID']); // Don't notify if it's your own comment
75
76                 if ( get_settings('comments_notify') && $commentdata['comment_approved'] && $post->post_author != $commentdata['user_ID'] )
77                         wp_notify_postauthor($comment_ID, $commentdata['comment_type']);
78         }
79
80         return $comment_ID;
81 }
82
83 function wp_insert_comment($commentdata) {
84         global $wpdb;
85         extract($commentdata);
86
87         if ( ! isset($comment_author_IP) )
88                 $comment_author_IP = $_SERVER['REMOTE_ADDR'];
89         if ( ! isset($comment_date) )
90                 $comment_date = current_time('mysql');
91         if ( ! isset($comment_date_gmt) )
92                 $comment_date_gmt = gmdate('Y-m-d H:i:s', strtotime($comment_date) );
93         if ( ! isset($comment_parent) )
94                 $comment_parent = 0;
95         if ( ! isset($comment_approved) )
96                 $comment_approved = 1;
97
98         $result = $wpdb->query("INSERT INTO $wpdb->comments 
99         (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)
100         VALUES 
101         ('$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')
102         ");
103
104         $id = $wpdb->insert_id;
105
106         if ( $comment_approved == 1) {
107                 $count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_post_ID = '$comment_post_ID' AND comment_approved = '1'");
108                 $wpdb->query( "UPDATE $wpdb->posts SET comment_count = $count WHERE ID = '$comment_post_ID'" );
109         }
110         return $id;
111 }
112
113 function wp_filter_comment($commentdata) {
114         $commentdata['user_id']              = apply_filters('pre_user_id', $commentdata['user_ID']);
115         $commentdata['comment_agent']        = apply_filters('pre_comment_user_agent', $commentdata['comment_agent']);
116         $commentdata['comment_author']       = apply_filters('pre_comment_author_name', $commentdata['comment_author']);
117         $commentdata['comment_content']      = apply_filters('pre_comment_content', $commentdata['comment_content']);
118         $commentdata['comment_author_IP']    = apply_filters('pre_comment_user_ip', $commentdata['comment_author_IP']);
119         $commentdata['comment_author_url']   = apply_filters('pre_comment_author_url', $commentdata['comment_author_url']);
120         $commentdata['comment_author_email'] = apply_filters('pre_comment_author_email', $commentdata['comment_author_email']);
121         $commentdata['filtered'] = true;
122         return $commentdata;
123 }
124
125 function wp_allow_comment($commentdata) {
126         global $wpdb;
127         extract($commentdata);
128
129         $comment_user_domain = apply_filters('pre_comment_user_domain', gethostbyaddr($comment_author_IP) );
130
131         // Simple duplicate check
132         $dupe = "SELECT comment_ID FROM $wpdb->comments WHERE comment_post_ID = '$comment_post_ID' AND ( comment_author = '$comment_author' ";
133         if ( $comment_author_email )
134                 $dupe .= "OR comment_author_email = '$comment_author_email' ";
135         $dupe .= ") AND comment_content = '$comment_content' LIMIT 1";
136         if ( $wpdb->get_var($dupe) )
137                 die( __('Duplicate comment detected; it looks as though you\'ve already said that!') );
138
139         // Simple flood-protection
140         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") ) {
141                 $time_lastcomment = mysql2date('U', $lasttime);
142                 $time_newcomment  = mysql2date('U', $comment_date_gmt);
143                 if ( ($time_newcomment - $time_lastcomment) < 15 ) {
144                         do_action('comment_flood_trigger', $time_lastcomment, $time_newcomment);
145                         die( __('Sorry, you can only post a new comment once every 15 seconds. Slow down cowboy.') );
146                 }
147         }
148
149         if ( $user_id ) {
150                 $userdata = get_userdata($user_id);
151                 $user = new WP_User($user_id);
152                 $post_author = $wpdb->get_var("SELECT post_author FROM $wpdb->posts WHERE ID = '$comment_post_ID' LIMIT 1");
153         }
154
155         // The author and the admins get respect.
156         if ( $userdata && ( $user_id == $post_author || $user->has_cap('level_9') ) ) {
157                 $approved = 1;
158         }
159
160         // Everyone else's comments will be checked.
161         else {
162                 if ( check_comment($comment_author, $comment_author_email, $comment_author_url, $comment_content, $comment_author_IP, $comment_agent, $comment_type) )
163                         $approved = 1;
164                 else
165                         $approved = 0;
166                 if ( wp_blacklist_check($comment_author, $comment_author_email, $comment_author_url, $comment_content, $comment_author_IP, $comment_agent) )
167                         $approved = 'spam';
168         }
169
170         $approved = apply_filters('pre_comment_approved', $approved);
171         return $approved;
172 }
173
174
175 function wp_update_comment($commentarr) {
176         global $wpdb;
177
178         // First, get all of the original fields
179         $comment = get_comment($commentarr['comment_ID'], ARRAY_A);
180
181         // Escape data pulled from DB.
182         foreach ($comment as $key => $value)
183                 $comment[$key] = $wpdb->escape($value);
184
185         // Merge old and new fields with new fields overwriting old ones.
186         $commentarr = array_merge($comment, $commentarr);
187
188         // Now extract the merged array.
189         extract($commentarr);
190
191         $comment_content = apply_filters('comment_save_pre', $comment_content);
192
193         $result = $wpdb->query(
194                 "UPDATE $wpdb->comments SET
195                         comment_content = '$comment_content',
196                         comment_author = '$comment_author',
197                         comment_author_email = '$comment_author_email',
198                         comment_approved = '$comment_approved',
199                         comment_author_url = '$comment_author_url',
200                         comment_date = '$comment_date'
201                 WHERE comment_ID = $comment_ID" );
202
203         $rval = $wpdb->rows_affected;
204
205         $c = $wpdb->get_row( "SELECT count(*) as c FROM {$wpdb->comments} WHERE comment_post_ID = '$comment_post_ID' AND comment_approved = '1'" );
206         if( is_object( $c ) )
207                 $wpdb->query( "UPDATE $wpdb->posts SET comment_count = '$c->c' WHERE ID = '$comment_post_ID'" );
208
209         do_action('edit_comment', $comment_ID);
210
211         return $rval;
212 }
213
214 function wp_delete_comment($comment_id) {
215         global $wpdb;
216         do_action('delete_comment', $comment_id);
217
218         $comment = get_comment($comment_id);
219
220         if ( ! $wpdb->query("DELETE FROM $wpdb->comments WHERE comment_ID='$comment_id' LIMIT 1") )
221                 return false;
222
223         $post_id = $comment->comment_post_ID;
224         if ( $post_id && $comment->comment_approved == 1 )
225                 $wpdb->query( "UPDATE $wpdb->posts SET comment_count = comment_count - 1 WHERE ID = '$post_id'" );
226
227         do_action('wp_set_comment_status', $comment_id, 'delete');
228         return true;
229 }
230
231 function clean_url( $url ) {
232         if ('' == $url) return $url;
233         $url = preg_replace('|[^a-z0-9-~+_.?#=&;,/:]|i', '', $url);
234         $url = str_replace(';//', '://', $url);
235         $url = (!strstr($url, '://')) ? 'http://'.$url : $url;
236         $url = preg_replace('/&([^#])(?![a-z]{2,8};)/', '&#038;$1', $url);
237         return $url;
238 }
239
240 function get_comments_number( $post_id = 0 ) {
241         global $wpdb, $comment_count_cache, $id;
242         $post_id = (int) $post_id;
243
244         if ( !$post_id )
245                 $post_id = $id;
246
247         if ( !isset($comment_count_cache[$post_id]) )
248                 $comment_count_cache[$id] = $wpdb->get_var("SELECT comment_count FROM $wpdb->posts WHERE ID = '$post_id'");
249         
250         return apply_filters('get_comments_number', $comment_count_cache[$post_id]);
251 }
252
253 function comments_number( $zero = 'No Comments', $one = '1 Comment', $more = '% Comments', $number = '' ) {
254         global $id, $comment;
255         $number = get_comments_number( $id );
256         if ($number == 0) {
257                 $blah = $zero;
258         } elseif ($number == 1) {
259                 $blah = $one;
260         } elseif ($number  > 1) {
261                 $blah = str_replace('%', $number, $more);
262         }
263         echo apply_filters('comments_number', $blah);
264 }
265
266 function get_comments_link() {
267         return get_permalink() . '#comments';
268 }
269
270 function get_comment_link() {
271         global $comment;
272         return get_permalink( $comment->comment_post_ID ) . '#comment-' . $comment->comment_ID;
273 }
274
275 function comments_link( $file = '', $echo = true ) {
276     echo get_comments_link();
277 }
278
279 function comments_popup_script($width=400, $height=400, $file='') {
280     global $wpcommentspopupfile, $wptrackbackpopupfile, $wppingbackpopupfile, $wpcommentsjavascript;
281
282                 if (empty ($file)) {
283                         $wpcommentspopupfile = '';  // Use the index.
284                 } else {
285                         $wpcommentspopupfile = $file;
286                 }
287
288     $wpcommentsjavascript = 1;
289     $javascript = "<script type='text/javascript'>\nfunction wpopen (macagna) {\n    window.open(macagna, '_blank', 'width=$width,height=$height,scrollbars=yes,status=yes');\n}\n</script>\n";
290     echo $javascript;
291 }
292
293 function comments_popup_link($zero='No Comments', $one='1 Comment', $more='% Comments', $CSSclass='', $none='Comments Off') {
294         global $id, $wpcommentspopupfile, $wpcommentsjavascript, $post, $wpdb;
295         global $comment_count_cache;
296         
297         if (! is_single() && ! is_page()) {
298         if ( !isset($comment_count_cache[$id]) )
299                 $comment_count_cache[$id] = $wpdb->get_var("SELECT COUNT(comment_ID) FROM $wpdb->comments WHERE comment_post_ID = $id AND comment_approved = '1';");
300         
301         $number = $comment_count_cache[$id];
302         
303         if (0 == $number && 'closed' == $post->comment_status && 'closed' == $post->ping_status) {
304                 echo $none;
305                 return;
306         } else {
307                 if (!empty($post->post_password)) { // if there's a password
308                         if ($_COOKIE['wp-postpass_'.COOKIEHASH] != $post->post_password) {  // and it doesn't match the cookie
309                                 echo(__('Enter your password to view comments'));
310                                 return;
311                         }
312                 }
313                 echo '<a href="';
314                 if ($wpcommentsjavascript) {
315                         if ( empty($wpcommentspopupfile) )
316                                 $home = get_settings('home');
317                         else
318                                 $home = get_settings('siteurl');
319                         echo $home . '/' . $wpcommentspopupfile.'?comments_popup='.$id;
320                         echo '" onclick="wpopen(this.href); return false"';
321                 } else { // if comments_popup_script() is not in the template, display simple comment link
322                         if ( 0 == $number )
323                                 echo get_permalink() . '#respond';
324                         else
325                                 comments_link();
326                         echo '"';
327                 }
328                 if (!empty($CSSclass)) {
329                         echo ' class="'.$CSSclass.'"';
330                 }
331                 echo ' title="' . sprintf( __('Comment on %s'), $post->post_title ) .'">';
332                 comments_number($zero, $one, $more, $number);
333                 echo '</a>';
334         }
335         }
336 }
337
338 function get_comment_ID() {
339         global $comment;
340         return apply_filters('get_comment_ID', $comment->comment_ID);
341 }
342
343 function comment_ID() {
344         echo get_comment_ID();
345 }
346
347 function get_comment_author() {
348         global $comment;
349         if ( empty($comment->comment_author) )
350                 $author = __('Anonymous');
351         else
352                 $author = $comment->comment_author;
353         return apply_filters('get_comment_author', $author);
354 }
355
356 function comment_author() {
357         $author = apply_filters('comment_author', get_comment_author() );
358         echo $author;
359 }
360
361 function get_comment_author_email() {
362         global $comment;
363         return apply_filters('get_comment_author_email', $comment->comment_author_email);       
364 }
365
366 function comment_author_email() {
367         echo apply_filters('author_email', get_comment_author_email() );
368 }
369
370 function get_comment_author_link() {
371         global $comment;
372         $url    = get_comment_author_url();
373         $author = get_comment_author();
374
375         if ( empty( $url ) || 'http://' == $url )
376                 $return = $author;
377         else
378                 $return = "<a href='$url' rel='external nofollow'>$author</a>";
379         return apply_filters('get_comment_author_link', $return);
380 }
381
382 function comment_author_link() {
383         echo get_comment_author_link();
384 }
385
386 function get_comment_type() {
387         global $comment;
388
389         if ( '' == $comment->comment_type )
390                 $comment->comment_type = 'comment';
391
392         return apply_filters('get_comment_type', $comment->comment_type);
393 }
394
395 function comment_type($commenttxt = 'Comment', $trackbacktxt = 'Trackback', $pingbacktxt = 'Pingback') {
396         $type = get_comment_type();
397         switch( $type ) {
398                 case 'trackback' :
399                         echo $trackbacktxt;
400                         break;
401                 case 'pingback' :
402                         echo $pingbacktxt;
403                         break;
404                 default :
405                         echo $commenttxt;
406         }
407 }
408
409 function get_comment_author_url() {
410         global $comment;
411         return apply_filters('get_comment_author_url', $comment->comment_author_url);
412 }
413
414 function comment_author_url() {
415         echo apply_filters('comment_url', get_comment_author_url());
416 }
417
418 function comment_author_email_link($linktext='', $before='', $after='') {
419         global $comment;
420         $email = apply_filters('comment_email', $comment->comment_author_email);
421         if ((!empty($email)) && ($email != '@')) {
422         $display = ($linktext != '') ? $linktext : $email;
423                 echo $before;
424                 echo "<a href='mailto:$email'>$display</a>";
425                 echo $after;
426         }
427 }
428
429 function get_comment_author_url_link( $linktext = '', $before = '', $after = '' ) {
430         global $comment;
431         $url = get_comment_author_url();
432         $display = ($linktext != '') ? $linktext : $url;
433         $return = "$before<a href='$url' rel='external'>$display</a>$after";
434         return apply_filters('get_comment_author_url_link', $return);
435 }
436
437 function comment_author_url_link( $linktext = '', $before = '', $after = '' ) {
438         echo get_comment_author_url_link( $linktext, $before, $after );
439 }
440
441 function get_comment_author_IP() {
442         global $comment;
443         return apply_filters('get_comment_author_IP', $comment->comment_author_IP);
444 }
445
446 function comment_author_IP() {
447         echo get_comment_author_IP();
448 }
449
450 function get_comment_text() {
451         global $comment;
452         return apply_filters('get_comment_text', $comment->comment_content);
453 }
454
455 function comment_text() {
456         echo apply_filters('comment_text', get_comment_text() );
457 }
458
459 function get_comment_excerpt() {
460         global $comment;
461         $comment_text = strip_tags($comment->comment_content);
462         $blah = explode(' ', $comment_text);
463         if (count($blah) > 20) {
464                 $k = 20;
465                 $use_dotdotdot = 1;
466         } else {
467                 $k = count($blah);
468                 $use_dotdotdot = 0;
469         }
470         $excerpt = '';
471         for ($i=0; $i<$k; $i++) {
472                 $excerpt .= $blah[$i] . ' ';
473         }
474         $excerpt .= ($use_dotdotdot) ? '...' : '';
475         return apply_filters('get_comment_excerpt', $excerpt);
476 }
477
478 function comment_excerpt() {
479         echo apply_filters('comment_excerpt', get_comment_excerpt() );
480 }
481
482 function get_comment_date( $d = '' ) {
483         global $comment;
484         if ( '' == $d )
485                 $date = mysql2date( get_settings('date_format'), $comment->comment_date);
486         else
487                 $date = mysql2date($d, $comment->comment_date);
488         return apply_filters('get_comment_date', $date);
489 }
490
491 function comment_date( $d = '' ) {
492         echo get_comment_date( $d );
493 }
494
495 function get_comment_time( $d = '', $gmt = false ) {
496         global $comment;
497         $comment_date = $gmt? $comment->comment_date_gmt : $comment->comment_date;
498         if ( '' == $d )
499                 $date = mysql2date(get_settings('time_format'), $comment_date);
500         else
501                 $date = mysql2date($d, $comment_date);
502         return apply_filters('get_comment_time', $date);
503 }
504
505 function comment_time( $d = '' ) {
506         echo get_comment_time($d);
507 }
508
509 function get_trackback_url() {
510         global $id;
511         $tb_url = get_settings('siteurl') . '/wp-trackback.php?p=' . $id;
512
513         if ( '' != get_settings('permalink_structure') )
514                 $tb_url = trailingslashit(get_permalink()) . 'trackback/';
515
516         return $tb_url;
517 }
518 function trackback_url( $display = true ) {
519         if ( $display)
520                 echo get_trackback_url();
521         else
522                 return get_trackback_url();
523 }
524
525 function trackback_rdf($timezone = 0) {
526         global $id;
527         if (!stristr($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator')) {
528         echo '<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" 
529             xmlns:dc="http://purl.org/dc/elements/1.1/"
530             xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
531                 <rdf:Description rdf:about="';
532         the_permalink();
533         echo '"'."\n";
534         echo '    dc:identifier="';
535         the_permalink();
536         echo '"'."\n";
537         echo '    dc:title="'.str_replace('--', '&#x2d;&#x2d;', wptexturize(strip_tags(get_the_title()))).'"'."\n";
538         echo '    trackback:ping="'.trackback_url(0).'"'." />\n";
539         echo '</rdf:RDF>';
540         }
541 }
542
543 function comments_open() {
544         global $post;
545         if ( 'open' == $post->comment_status )
546                 return true;
547         else
548                 return false;
549 }
550
551 function pings_open() {
552         global $post;
553         if ( 'open' == $post->ping_status ) 
554                 return true;
555         else
556                 return false;
557 }
558
559 // Non-template functions
560
561 function get_lastcommentmodified($timezone = 'server') {
562         global $cache_lastcommentmodified, $pagenow, $wpdb;
563         $add_seconds_blog = get_settings('gmt_offset') * 3600;
564         $add_seconds_server = date('Z');
565         $now = current_time('mysql', 1);
566         if ( !isset($cache_lastcommentmodified[$timezone]) ) {
567                 switch(strtolower($timezone)) {
568                         case 'gmt':
569                                 $lastcommentmodified = $wpdb->get_var("SELECT comment_date_gmt FROM $wpdb->comments WHERE comment_date_gmt <= '$now' ORDER BY comment_date_gmt DESC LIMIT 1");
570                                 break;
571                         case 'blog':
572                                 $lastcommentmodified = $wpdb->get_var("SELECT comment_date FROM $wpdb->comments WHERE comment_date_gmt <= '$now' ORDER BY comment_date_gmt DESC LIMIT 1");
573                                 break;
574                         case 'server':
575                                 $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");
576                                 break;
577                 }
578                 $cache_lastcommentmodified[$timezone] = $lastcommentmodified;
579         } else {
580                 $lastcommentmodified = $cache_lastcommentmodified[$timezone];
581         }
582         return $lastcommentmodified;
583 }
584
585 function get_commentdata( $comment_ID, $no_cache = 0, $include_unapproved = false ) { // less flexible, but saves DB queries
586         global $postc, $id, $commentdata, $wpdb;
587         if ($no_cache) {
588                 $query = "SELECT * FROM $wpdb->comments WHERE comment_ID = '$comment_ID'";
589                 if (false == $include_unapproved) {
590                     $query .= " AND comment_approved = '1'";
591                 }
592                 $myrow = $wpdb->get_row($query, ARRAY_A);
593         } else {
594                 $myrow['comment_ID'] = $postc->comment_ID;
595                 $myrow['comment_post_ID'] = $postc->comment_post_ID;
596                 $myrow['comment_author'] = $postc->comment_author;
597                 $myrow['comment_author_email'] = $postc->comment_author_email;
598                 $myrow['comment_author_url'] = $postc->comment_author_url;
599                 $myrow['comment_author_IP'] = $postc->comment_author_IP;
600                 $myrow['comment_date'] = $postc->comment_date;
601                 $myrow['comment_content'] = $postc->comment_content;
602                 $myrow['comment_karma'] = $postc->comment_karma;
603                 $myrow['comment_approved'] = $postc->comment_approved;
604                 $myrow['comment_type'] = $postc->comment_type;
605         }
606         return $myrow;
607 }
608
609 function pingback($content, $post_ID) {
610         global $wp_version, $wpdb;
611         include_once (ABSPATH . WPINC . '/class-IXR.php');
612
613         // original code by Mort (http://mort.mine.nu:8080)
614         $log = debug_fopen(ABSPATH . '/pingback.log', 'a');
615         $post_links = array();
616         debug_fwrite($log, 'BEGIN '.date('YmdHis', time())."\n");
617
618         $pung = get_pung($post_ID);
619
620         // Variables
621         $ltrs = '\w';
622         $gunk = '/#~:.?+=&%@!\-';
623         $punc = '.:?\-';
624         $any = $ltrs . $gunk . $punc;
625
626         // Step 1
627         // Parsing the post, external links (if any) are stored in the $post_links array
628         // This regexp comes straight from phpfreaks.com
629         // http://www.phpfreaks.com/quickcode/Extract_All_URLs_on_a_Page/15.php
630         preg_match_all("{\b http : [$any] +? (?= [$punc] * [^$any] | $)}x", $content, $post_links_temp);
631
632         // Debug
633         debug_fwrite($log, 'Post contents:');
634         debug_fwrite($log, $content."\n");
635         
636         // Step 2.
637         // Walking thru the links array
638         // first we get rid of links pointing to sites, not to specific files
639         // Example:
640         // http://dummy-weblog.org
641         // http://dummy-weblog.org/
642         // http://dummy-weblog.org/post.php
643         // We don't wanna ping first and second types, even if they have a valid <link/>
644
645         foreach($post_links_temp[0] as $link_test) :
646                 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
647                                 && !is_local_attachment($link_test) ) : // Also, let's never ping local attachments.
648                         $test = parse_url($link_test);
649                         if (isset($test['query']))
650                                 $post_links[] = $link_test;
651                         elseif(($test['path'] != '/') && ($test['path'] != ''))
652                                 $post_links[] = $link_test;
653                 endif;
654         endforeach;
655
656         do_action('pre_ping',  array(&$post_links, &$pung));
657
658         foreach ($post_links as $pagelinkedto){
659                 debug_fwrite($log, "Processing -- $pagelinkedto\n");
660                 $pingback_server_url = discover_pingback_server_uri($pagelinkedto, 2048);
661
662                 if ($pingback_server_url) {
663                         @ set_time_limit( 60 ); 
664                          // Now, the RPC call
665                         debug_fwrite($log, "Page Linked To: $pagelinkedto \n");
666                         debug_fwrite($log, 'Page Linked From: ');
667                         $pagelinkedfrom = get_permalink($post_ID);
668                         debug_fwrite($log, $pagelinkedfrom."\n");
669
670                         // using a timeout of 3 seconds should be enough to cover slow servers
671                         $client = new IXR_Client($pingback_server_url);
672                         $client->timeout = 3;
673                         $client->useragent .= ' -- WordPress/' . $wp_version;
674
675                         // when set to true, this outputs debug messages by itself
676                         $client->debug = false;
677                         
678                         if ( $client->query('pingback.ping', $pagelinkedfrom, $pagelinkedto ) )
679                                 add_ping( $post_ID, $pagelinkedto );
680                         else
681                                 debug_fwrite($log, "Error.\n Fault code: ".$client->getErrorCode()." : ".$client->getErrorMessage()."\n");
682                 }
683         }
684
685         debug_fwrite($log, "\nEND: ".time()."\n****************************\n");
686         debug_fclose($log);
687 }
688
689 function discover_pingback_server_uri($url, $timeout_bytes = 2048) {
690         global $wp_version;
691
692         $byte_count = 0;
693         $contents = '';
694         $headers = '';
695         $pingback_str_dquote = 'rel="pingback"';
696         $pingback_str_squote = 'rel=\'pingback\'';
697         $x_pingback_str = 'x-pingback: ';
698         $pingback_href_original_pos = 27;
699
700         extract(parse_url($url));
701
702         if (!isset($host)) {
703                 // Not an URL. This should never happen.
704                 return false;
705         }
706
707         $path  = (!isset($path)) ? '/'        : $path;
708         $path .= (isset($query)) ? '?'.$query : '';
709         $port  = (isset($port))  ? $port      : 80;
710
711         // Try to connect to the server at $host
712         $fp = @fsockopen($host, $port, $errno, $errstr, 2);
713         if (!$fp) {
714                 // Couldn't open a connection to $host;
715                 return false;
716         }
717
718         // Send the GET request
719         $request = "GET $path HTTP/1.1\r\nHost: $host\r\nUser-Agent: WordPress/$wp_version \r\n\r\n";
720 //      ob_end_flush();
721         fputs($fp, $request);
722
723         // Let's check for an X-Pingback header first
724         while (!feof($fp)) {
725                 $line = fgets($fp, 512);
726                 if (trim($line) == '') {
727                         break;
728                 }
729                 $headers .= trim($line)."\n";
730                 $x_pingback_header_offset = strpos(strtolower($headers), $x_pingback_str);
731                 if ($x_pingback_header_offset) {
732                         // We got it!
733                         preg_match('#x-pingback: (.+)#is', $headers, $matches);
734                         $pingback_server_url = trim($matches[1]);
735                         return $pingback_server_url;
736                 }
737                 if(strpos(strtolower($headers), 'content-type: ')) {
738                         preg_match('#content-type: (.+)#is', $headers, $matches);
739                         $content_type = trim($matches[1]);
740                 }
741         }
742
743         if (preg_match('#(image|audio|video|model)/#is', $content_type)) {
744                 // Not an (x)html, sgml, or xml page, no use going further
745                 return false;
746         }
747
748         while (!feof($fp)) {
749                 $line = fgets($fp, 1024);
750                 $contents .= trim($line);
751                 $pingback_link_offset_dquote = strpos($contents, $pingback_str_dquote);
752                 $pingback_link_offset_squote = strpos($contents, $pingback_str_squote);
753                 if ($pingback_link_offset_dquote || $pingback_link_offset_squote) {
754                         $quote = ($pingback_link_offset_dquote) ? '"' : '\'';
755                         $pingback_link_offset = ($quote=='"') ? $pingback_link_offset_dquote : $pingback_link_offset_squote;
756                         $pingback_href_pos = @strpos($contents, 'href=', $pingback_link_offset);
757                         $pingback_href_start = $pingback_href_pos+6;
758                         $pingback_href_end = @strpos($contents, $quote, $pingback_href_start);
759                         $pingback_server_url_len = $pingback_href_end - $pingback_href_start;
760                         $pingback_server_url = substr($contents, $pingback_href_start, $pingback_server_url_len);
761                         // We may find rel="pingback" but an incomplete pingback URI
762                         if ($pingback_server_url_len > 0) {
763                                 // We got it!
764                                 return $pingback_server_url;
765                         }
766                 }
767                 $byte_count += strlen($line);
768                 if ($byte_count > $timeout_bytes) {
769                         // It's no use going further, there probably isn't any pingback
770                         // server to find in this file. (Prevents loading large files.)
771                         return false;
772                 }
773         }
774
775         // We didn't find anything.
776         return false;
777 }
778
779 function is_local_attachment($url) {
780         if ( !strstr($url, get_bloginfo('home') ) )
781                 return false;
782         if ( strstr($url, get_bloginfo('home') . '/?attachment_id=') )
783                 return true;
784         if ( $id = url_to_postid($url) ) {
785                 $post = & get_post($id);
786                 if ( 'attachment' == $post->post_status )
787                         return true;
788         }               
789         return false;
790 }
791
792 function wp_set_comment_status($comment_id, $comment_status) {
793     global $wpdb;
794
795     switch($comment_status) {
796                 case 'hold':
797                         $query = "UPDATE $wpdb->comments SET comment_approved='0' WHERE comment_ID='$comment_id' LIMIT 1";
798                 break;
799                 case 'approve':
800                         $query = "UPDATE $wpdb->comments SET comment_approved='1' WHERE comment_ID='$comment_id' LIMIT 1";
801                 break;
802                 case 'spam':
803                         $query = "UPDATE $wpdb->comments SET comment_approved='spam' WHERE comment_ID='$comment_id' LIMIT 1";
804                 break;
805                 case 'delete':
806                         return wp_delete_comment($comment_id);
807                 break;
808                 default:
809                         return false;
810     }
811     
812     if ($wpdb->query($query)) {
813                 do_action('wp_set_comment_status', $comment_id, $comment_status);
814                 
815                 $comment = get_comment($comment_id);
816                 $comment_post_ID = $comment->comment_post_ID;
817                 $c = $wpdb->get_row( "SELECT count(*) as c FROM {$wpdb->comments} WHERE comment_post_ID = '$comment_post_ID' AND comment_approved = '1'" );
818                 if( is_object( $c ) )
819                         $wpdb->query( "UPDATE $wpdb->posts SET comment_count = '$c->c' WHERE ID = '$comment_post_ID'" );
820                 return true;
821     } else {
822                 return false;
823     }
824 }
825
826 function wp_get_comment_status($comment_id) {
827         global $wpdb;
828         
829         $result = $wpdb->get_var("SELECT comment_approved FROM $wpdb->comments WHERE comment_ID='$comment_id' LIMIT 1");
830         if ($result == NULL) {
831                 return 'deleted';
832         } else if ($result == '1') {
833                 return 'approved';
834         } else if ($result == '0') {
835                 return 'unapproved';
836         } else if ($result == 'spam') {
837                 return 'spam';
838         } else {
839                 return false;
840         }
841 }
842
843 function check_comment($author, $email, $url, $comment, $user_ip, $user_agent, $comment_type) {
844         global $wpdb;
845
846         if (1 == get_settings('comment_moderation')) return false; // If moderation is set to manual
847
848         if ( (count(explode('http:', $comment)) - 1) >= get_settings('comment_max_links') )
849                 return false; // Check # of external links
850
851         $mod_keys = trim( get_settings('moderation_keys') );
852         if ( !empty($mod_keys) ) {
853                 $words = explode("\n", $mod_keys );
854
855                 foreach ($words as $word) {
856                         $word = trim($word);
857
858                         // Skip empty lines
859                         if (empty($word)) { continue; }
860
861                         // Do some escaping magic so that '#' chars in the 
862                         // spam words don't break things:
863                         $word = preg_quote($word, '#');
864                 
865                         $pattern = "#$word#i"; 
866                         if ( preg_match($pattern, $author) ) return false;
867                         if ( preg_match($pattern, $email) ) return false;
868                         if ( preg_match($pattern, $url) ) return false;
869                         if ( preg_match($pattern, $comment) ) return false;
870                         if ( preg_match($pattern, $user_ip) ) return false;
871                         if ( preg_match($pattern, $user_agent) ) return false;
872                 }
873         }
874
875         // Comment whitelisting:
876         if ( 1 == get_settings('comment_whitelist')) {
877                 if ( 'trackback' == $comment_type || 'pingback' == $comment_type ) { // check if domain is in blogroll
878                         $uri = parse_url($url);
879                         $domain = $uri['host'];
880                         $uri = parse_url( get_option('home') );
881                         $home_domain = $uri['host'];
882                         if ( $wpdb->get_var("SELECT link_id FROM $wpdb->links WHERE link_url LIKE ('%$domain%') LIMIT 1") || $domain == $home_domain )
883                                 return true;
884                         else
885                                 return false;
886                 } elseif( $author != '' && $email != '' ) {
887                         $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");
888                         if ( ( 1 == $ok_to_comment ) &&
889                                 ( empty($mod_keys) || false === strpos( $email, $mod_keys) ) )
890                                         return true;
891                         else
892                                 return false;
893                 } else {
894                         return false;
895                 }
896         }
897
898         return true;
899 }
900
901 function get_approved_comments($post_id) {
902         global $wpdb;
903         return $wpdb->get_results("SELECT * FROM $wpdb->comments WHERE comment_post_ID = $post_id AND comment_approved = '1' ORDER BY comment_date");
904 }
905
906 ?>