]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/functions-post.php
Wordpress 2.0.11
[autoinstalls/wordpress.git] / wp-includes / functions-post.php
1 <?php
2
3 /**** DB Functions ****/
4
5 /*
6  * generic function for inserting data into the posts table.
7  */
8 function wp_insert_post($postarr = array()) {
9         global $wpdb, $wp_rewrite, $allowedtags, $user_ID;
10
11         if ( is_object($postarr) )
12                 $postarr = get_object_vars($postarr);
13
14         // export array as variables
15         extract($postarr);
16
17         // Are we updating or creating?
18         $update = false;
19         if ( !empty($ID) ) {
20                 $update = true;
21                 $post = & get_post($ID);
22                 $previous_status = $post->post_status;
23         }
24
25         // Get the basics.
26         $post_content    = apply_filters('content_save_pre',   $post_content);
27         $post_content_filtered = apply_filters('content_filtered_save_pre',   $post_content_filtered);
28         $post_excerpt    = apply_filters('excerpt_save_pre',   $post_excerpt);
29         $post_title      = apply_filters('title_save_pre',     $post_title);
30         $post_category   = apply_filters('category_save_pre',  $post_category);
31         $post_status     = apply_filters('status_save_pre',    $post_status);
32         $post_name       = apply_filters('name_save_pre',      $post_name);
33         $comment_status  = apply_filters('comment_status_pre', $comment_status);
34         $ping_status     = apply_filters('ping_status_pre',    $ping_status);
35         
36         // Make sure we set a valid category
37         if (0 == count($post_category) || !is_array($post_category)) {
38                 $post_category = array(get_option('default_category'));
39         }
40         $post_cat = $post_category[0];
41
42         if ( empty($post_author) )
43                 $post_author = $user_ID;
44
45         if ( empty($post_status) )
46                 $post_status = 'draft';
47         
48         // Get the post ID.
49         if ( $update )
50                 $post_ID = (int) $ID;
51
52         // Create a valid post name.  Drafts are allowed to have an empty
53         // post name.
54         if ( empty($post_name) ) {
55                 if ( 'draft' != $post_status )
56                         $post_name = sanitize_title($post_title);
57         } else {
58                 $post_name = sanitize_title($post_name);
59         }
60         
61
62         // If the post date is empty (due to having been new or a draft) and status is not 'draft', set date to now
63         if (empty($post_date)) {
64                 if ( 'draft' != $post_status )
65                         $post_date = current_time('mysql');
66         }
67
68         if (empty($post_date_gmt)) {
69                 if ( 'draft' != $post_status )
70                         $post_date_gmt = get_gmt_from_date($post_date);
71         }
72
73         if ( empty($comment_status) ) {
74                 if ( $update )
75                         $comment_status = 'closed';
76                 else
77                         $comment_status = get_settings('default_comment_status');
78         }
79         if ( empty($ping_status) )
80                 $ping_status = get_settings('default_ping_status');
81         if ( empty($post_pingback) )
82                 $post_pingback = get_option('default_pingback_flag');
83
84         if ( isset($to_ping) )
85                 $to_ping = preg_replace('|\s+|', "\n", $to_ping);
86         else
87                 $to_ping = '';
88
89         if ( ! isset($pinged) )
90                 $pinged = '';
91
92         if ( isset($post_parent) )
93                 $post_parent = (int) $post_parent;
94         else
95                 $post_parent = 0;
96
97         if ( isset($menu_order) )
98                 $menu_order = (int) $menu_order;
99         else
100                 $menu_order = 0;
101
102         if ( !isset($post_password) )
103                 $post_password = '';
104
105         if ( ('publish' == $post_status) || ('static' == $post_status) ) {
106                 $post_name_check = ('publish' == $post_status)
107                         ? $wpdb->get_var("SELECT post_name FROM $wpdb->posts WHERE post_name = '$post_name' AND post_status = 'publish' AND ID != '$post_ID' LIMIT 1")
108                         : $wpdb->get_var("SELECT post_name FROM $wpdb->posts WHERE post_name = '$post_name' AND post_status = 'static' AND ID != '$post_ID' AND post_parent = '$post_parent' LIMIT 1");
109
110                 if ($post_name_check) {
111                         $suffix = 2;
112                         while ($post_name_check) {
113                                 $alt_post_name = $post_name . "-$suffix";
114                                 $post_name_check = ('publish' == $post_status)
115                                         ? $wpdb->get_var("SELECT post_name FROM $wpdb->posts WHERE post_name = '$alt_post_name' AND post_status = 'publish' AND ID != '$post_ID' LIMIT 1")
116                                         : $wpdb->get_var("SELECT post_name FROM $wpdb->posts WHERE post_name = '$alt_post_name' AND post_status = 'static' AND ID != '$post_ID' AND post_parent = '$post_parent' LIMIT 1");
117                                 $suffix++;
118                         }
119                         $post_name = $alt_post_name;
120                 }
121         }
122
123         if ($update) {
124                 $wpdb->query(
125                         "UPDATE IGNORE $wpdb->posts SET
126                         post_author = '$post_author',
127                         post_date = '$post_date',
128                         post_date_gmt = '$post_date_gmt',
129                         post_content = '$post_content',
130                         post_content_filtered = '$post_content_filtered',
131                         post_title = '$post_title',
132                         post_excerpt = '$post_excerpt',
133                         post_status = '$post_status',
134                         comment_status = '$comment_status',
135                         ping_status = '$ping_status',
136                         post_password = '$post_password',
137                         post_name = '$post_name',
138                         to_ping = '$to_ping',
139                         pinged = '$pinged',
140                         post_modified = '".current_time('mysql')."',
141                         post_modified_gmt = '".current_time('mysql',1)."',
142                         post_parent = '$post_parent',
143                         menu_order = '$menu_order'
144                         WHERE ID = $post_ID");
145         } else {
146                 $wpdb->query(
147                         "INSERT IGNORE INTO $wpdb->posts
148                         (post_author, post_date, post_date_gmt, post_content, post_content_filtered, post_title, post_excerpt,  post_status, comment_status, ping_status, post_password, post_name, to_ping, pinged, post_modified, post_modified_gmt, post_parent, menu_order, post_mime_type)
149                         VALUES
150                         ('$post_author', '$post_date', '$post_date_gmt', '$post_content', '$post_content_filtered', '$post_title', '$post_excerpt', '$post_status', '$comment_status', '$ping_status', '$post_password', '$post_name', '$to_ping', '$pinged', '$post_date', '$post_date_gmt', '$post_parent', '$menu_order', '$post_mime_type')");
151                         $post_ID = $wpdb->insert_id;                    
152         }
153
154         if ( empty($post_name) && 'draft' != $post_status ) {
155                 $post_name = sanitize_title($post_title, $post_ID);
156                 $wpdb->query( "UPDATE $wpdb->posts SET post_name = '$post_name' WHERE ID = '$post_ID'" );
157         }
158
159         wp_set_post_cats('', $post_ID, $post_category);
160
161         if ( 'static' == $post_status ) {
162                 clean_page_cache($post_ID);
163                 wp_cache_delete($post_ID, 'pages');
164         } else {
165                 clean_post_cache($post_ID);
166         }
167
168         // Set GUID
169         if ( ! $update )
170                 $wpdb->query("UPDATE $wpdb->posts SET guid = '" . get_permalink($post_ID) . "' WHERE ID = '$post_ID'");
171
172         if ( $update) {
173                 if ($previous_status != 'publish' && $post_status == 'publish') {
174                         // Reset GUID if transitioning to publish.
175                         $wpdb->query("UPDATE $wpdb->posts SET guid = '" . get_permalink($post_ID) . "' WHERE ID = '$post_ID'");
176                         do_action('private_to_published', $post_ID);
177                 }
178                 
179                 do_action('edit_post', $post_ID);
180         }
181
182         if ($post_status == 'publish') {
183                 do_action('publish_post', $post_ID);
184
185                 if ( !defined('WP_IMPORTING') ) {
186                         if ( $post_pingback )
187                                 $result = $wpdb->query("
188                                         INSERT INTO $wpdb->postmeta 
189                                         (post_id,meta_key,meta_value) 
190                                         VALUES ('$post_ID','_pingme','1')
191                                 ");
192                         $result = $wpdb->query("
193                                 INSERT INTO $wpdb->postmeta 
194                                 (post_id,meta_key,meta_value) 
195                                 VALUES ('$post_ID','_encloseme','1')
196                         ");
197                         spawn_pinger();
198                 }
199         } else if ($post_status == 'static') {
200                 wp_cache_delete('all_page_ids', 'pages');
201                 $wp_rewrite->flush_rules();
202
203                 if ( !empty($page_template) )
204                         if ( ! update_post_meta($post_ID, '_wp_page_template',  $page_template))
205                                 add_post_meta($post_ID, '_wp_page_template',  $page_template, true);
206         }
207
208         do_action('save_post', $post_ID);
209         do_action('wp_insert_post', $post_ID);
210
211         return $post_ID;
212 }
213
214 function wp_insert_attachment($object, $file = false, $post_parent = 0) {
215         global $wpdb, $user_ID;
216
217         if ( is_object($object) )
218                 $object = get_object_vars($object);
219
220         // Export array as variables
221         extract($object);
222
223         // Get the basics.
224         $post_content    = apply_filters('content_save_pre',   $post_content);
225         $post_content_filtered = apply_filters('content_filtered_save_pre',   $post_content_filtered);
226         $post_excerpt    = apply_filters('excerpt_save_pre',   $post_excerpt);
227         $post_title      = apply_filters('title_save_pre',     $post_title);
228         $post_category   = apply_filters('category_save_pre',  $post_category);
229         $post_name       = apply_filters('name_save_pre',      $post_name);
230         $comment_status  = apply_filters('comment_status_pre', $comment_status);
231         $ping_status     = apply_filters('ping_status_pre',    $ping_status);
232         $post_mime_type  = apply_filters('post_mime_type_pre', $post_mime_type);
233
234         // Make sure we set a valid category
235         if (0 == count($post_category) || !is_array($post_category)) {
236                 $post_category = array(get_option('default_category'));
237         }
238         $post_cat = $post_category[0];
239
240         if ( empty($post_author) )
241                 $post_author = $user_ID;
242
243         $post_status = 'attachment';
244
245         // Are we updating or creating?
246         $update = false;
247         if ( !empty($ID) ) {
248                 $update = true;
249                 $post_ID = $ID; 
250         }
251
252         // Create a valid post name.
253         if ( empty($post_name) )
254                 $post_name = sanitize_title($post_title);
255         else
256                 $post_name = sanitize_title($post_name);
257         
258         if (empty($post_date))
259                 $post_date = current_time('mysql');
260         if (empty($post_date_gmt)) 
261                 $post_date_gmt = current_time('mysql', 1);
262
263         if ( empty($comment_status) ) {
264                 if ( $update )
265                         $comment_status = 'closed';
266                 else
267                         $comment_status = get_settings('default_comment_status');
268         }
269         if ( empty($ping_status) )
270                 $ping_status = get_settings('default_ping_status');
271         if ( empty($post_pingback) )
272                 $post_pingback = get_option('default_pingback_flag');
273
274         if ( isset($to_ping) )
275                 $to_ping = preg_replace('|\s+|', "\n", $to_ping);
276         else
277                 $to_ping = '';
278
279         if ( isset($post_parent) )
280                 $post_parent = (int) $post_parent;
281         else
282                 $post_parent = 0;
283
284         if ( isset($menu_order) )
285                 $menu_order = (int) $menu_order;
286         else
287                 $menu_order = 0;
288
289         if ( !isset($post_password) )
290                 $post_password = '';
291
292         if ( isset($to_ping) )
293                 $to_ping = preg_replace('|\s+|', "\n", $to_ping);
294         else
295                 $to_ping = '';
296
297         if ( ! isset($pinged) )
298                 $pinged = '';
299
300         if ($update) {
301                 $wpdb->query(
302                         "UPDATE $wpdb->posts SET
303                         post_author = '$post_author',
304                         post_date = '$post_date',
305                         post_date_gmt = '$post_date_gmt',
306                         post_content = '$post_content',
307                         post_content_filtered = '$post_content_filtered',
308                         post_title = '$post_title',
309                         post_excerpt = '$post_excerpt',
310                         post_status = '$post_status',
311                         comment_status = '$comment_status',
312                         ping_status = '$ping_status',
313                         post_password = '$post_password',
314                         post_name = '$post_name',
315                         to_ping = '$to_ping',
316                         pinged = '$pinged',
317                         post_modified = '".current_time('mysql')."',
318                         post_modified_gmt = '".current_time('mysql',1)."',
319                         post_parent = '$post_parent',
320                         menu_order = '$menu_order',
321                         post_mime_type = '$post_mime_type',
322                         guid = '$guid'
323                         WHERE ID = $post_ID");
324         } else {
325                 $wpdb->query(
326                         "INSERT INTO $wpdb->posts
327                         (post_author, post_date, post_date_gmt, post_content, post_content_filtered, post_title, post_excerpt,  post_status, comment_status, ping_status, post_password, post_name, to_ping, pinged, post_modified, post_modified_gmt, post_parent, menu_order, post_mime_type, guid)
328                         VALUES
329                         ('$post_author', '$post_date', '$post_date_gmt', '$post_content', '$post_content_filtered', '$post_title', '$post_excerpt', '$post_status', '$comment_status', '$ping_status', '$post_password', '$post_name', '$to_ping', '$pinged', '$post_date', '$post_date_gmt', '$post_parent', '$menu_order', '$post_mime_type', '$guid')");
330                         $post_ID = $wpdb->insert_id;                    
331         }
332         
333         if ( empty($post_name) ) {
334                 $post_name = sanitize_title($post_title, $post_ID);
335                 $wpdb->query( "UPDATE $wpdb->posts SET post_name = '$post_name' WHERE ID = '$post_ID'" );
336         }
337
338         wp_set_post_cats('', $post_ID, $post_category);
339
340         if ( $file )
341                 add_post_meta($post_ID, '_wp_attached_file', $file);
342
343         clean_post_cache($post_ID);
344
345         if ( $update) {
346                 do_action('edit_attachment', $post_ID);
347         } else {
348                 do_action('add_attachment', $post_ID);
349         }
350         
351         return $post_ID;
352 }
353
354 function wp_delete_attachment($postid) {
355         global $wpdb;
356         $postid = (int) $postid;
357
358         if ( !$post = $wpdb->get_row("SELECT * FROM $wpdb->posts WHERE ID = '$postid'") )
359                 return $post;
360
361         if ( 'attachment' != $post->post_status )
362                 return false;
363
364         $meta = get_post_meta($postid, '_wp_attachment_metadata', true);
365         $file = get_post_meta($postid, '_wp_attached_file', true);
366
367         $wpdb->query("DELETE FROM $wpdb->posts WHERE ID = '$postid'");
368
369         $wpdb->query("DELETE FROM $wpdb->comments WHERE comment_post_ID = '$postid'");
370
371         $wpdb->query("DELETE FROM $wpdb->post2cat WHERE post_id = '$postid'");
372
373         $wpdb->query("DELETE FROM $wpdb->postmeta WHERE post_id = '$postid'");
374
375         if ( ! empty($meta['thumb']) ) {
376                 // Don't delete the thumb if another attachment uses it
377                 if (! $foo = $wpdb->get_row("SELECT meta_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attachment_metadata' AND meta_value LIKE '%".$wpdb->escape($meta['thumb'])."%' AND post_id <> '$postid'"))
378                         @ unlink(str_replace(basename($file), $meta['thumb'], $file));
379         }
380
381         if ( ! empty($file) )
382                 @ unlink($file);
383
384         do_action('delete_attachment', $postid);
385
386         return $post;
387 }
388
389 function wp_get_single_post($postid = 0, $mode = OBJECT) {
390         global $wpdb;
391
392         $post = get_post($postid, $mode);
393         
394         // Set categories
395         if($mode == OBJECT) {
396                 $post->post_category = wp_get_post_cats('',$postid);
397         } 
398         else {
399                 $post['post_category'] = wp_get_post_cats('',$postid);
400         }
401
402         return $post;
403 }
404
405 function wp_get_recent_posts($num = 10) {
406         global $wpdb;
407
408         // Set the limit clause, if we got a limit
409         $num = (int) $num;
410         if ($num) {
411                 $limit = "LIMIT $num";
412         }
413
414         $sql = "SELECT * FROM $wpdb->posts WHERE post_status IN ('publish', 'draft', 'private') ORDER BY post_date DESC $limit";
415         $result = $wpdb->get_results($sql,ARRAY_A);
416
417         return $result?$result:array();
418 }
419
420 function wp_update_post($postarr = array()) {
421         global $wpdb;
422
423         if ( is_object($postarr) )
424                 $postarr = get_object_vars($postarr);
425
426         // First, get all of the original fields
427         $post = wp_get_single_post($postarr['ID'], ARRAY_A);    
428
429         // Escape data pulled from DB.
430         $post = add_magic_quotes($post);
431
432         // Passed post category list overwrites existing category list if not empty.
433         if ( isset($postarr['post_category']) && is_array($postarr['post_category'])
434                          && 0 != count($postarr['post_category']) )
435                 $post_cats = $postarr['post_category'];
436         else 
437                 $post_cats = $post['post_category'];
438
439         // Drafts shouldn't be assigned a date unless explicitly done so by the user
440         if ( 'draft' == $post['post_status'] && empty($postarr['edit_date']) && empty($postarr['post_date']) && 
441              ('0000-00-00 00:00:00' == $post['post_date']) )
442                 $clear_date = true;
443         else
444                 $clear_date = false;
445
446         // Merge old and new fields with new fields overwriting old ones.
447         $postarr = array_merge($post, $postarr);
448         $postarr['post_category'] = $post_cats; 
449         if ( $clear_date ) {
450                 $postarr['post_date'] = '';
451                 $postarr['post_date_gmt'] = '';
452         }
453
454         if ($postarr['post_status'] == 'attachment')
455                 return wp_insert_attachment($postarr);
456
457         return wp_insert_post($postarr);
458 }
459
460 function wp_get_post_cats($blogid = '1', $post_ID = 0) {
461         global $wpdb;
462         
463         $post_ID = (int) $post_ID;
464
465         $sql = "SELECT category_id 
466                 FROM $wpdb->post2cat 
467                 WHERE post_id = '$post_ID' 
468                 ORDER BY category_id";
469
470         $result = $wpdb->get_col($sql);
471
472         if ( !$result )
473                 $result = array();
474
475         return array_unique($result);
476 }
477
478 function wp_set_post_cats($blogid = '1', $post_ID = 0, $post_categories = array()) {
479         global $wpdb;
480         
481         $post_ID = (int) $post_ID;
482
483         // If $post_categories isn't already an array, make it one:
484         if (!is_array($post_categories) || 0 == count($post_categories))
485                 $post_categories = array(get_option('default_category'));
486         
487         $post_categories = array_unique($post_categories);
488
489         // First the old categories
490         $old_categories = $wpdb->get_col("
491                 SELECT category_id 
492                 FROM $wpdb->post2cat 
493                 WHERE post_id = '$post_ID'");
494         
495         if (!$old_categories) {
496                 $old_categories = array();
497         } else {
498                 $old_categories = array_unique($old_categories);
499         }
500
501         // Delete any?
502         $delete_cats = array_diff($old_categories,$post_categories);
503
504         if ($delete_cats) {
505                 foreach ($delete_cats as $del) {
506                         $wpdb->query("
507                                 DELETE FROM $wpdb->post2cat 
508                                 WHERE category_id = '$del' 
509                                         AND post_id = '$post_ID' 
510                                 ");
511                 }
512         }
513
514         // Add any?
515         $add_cats = array_diff($post_categories, $old_categories);
516
517         if ($add_cats) {
518                 foreach ($add_cats as $new_cat) {
519                         $new_cat = (int) $new_cat;
520                         if ( !empty($new_cat) )
521                                 $wpdb->query("
522                                         INSERT INTO $wpdb->post2cat (post_id, category_id) 
523                                         VALUES ('$post_ID', '$new_cat')");
524                 }
525         }
526
527         // Update category counts.
528         $all_affected_cats = array_unique(array_merge($post_categories, $old_categories));
529         foreach ( $all_affected_cats as $cat_id ) {
530                 $count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->post2cat, $wpdb->posts WHERE $wpdb->posts.ID=$wpdb->post2cat.post_id AND post_status='publish' AND category_id = '$cat_id'");
531                 $wpdb->query("UPDATE $wpdb->categories SET category_count = '$count' WHERE cat_ID = '$cat_id'");
532                 wp_cache_delete($cat_id, 'category');           
533         }
534 }       // wp_set_post_cats()
535
536 function wp_delete_post($postid = 0) {
537         global $wpdb, $wp_rewrite;
538         $postid = (int) $postid;
539
540         if ( !$post = $wpdb->get_row("SELECT * FROM $wpdb->posts WHERE ID = $postid") )
541                 return $post;
542
543         if ( 'attachment' == $post->post_status )
544                 return wp_delete_attachment($postid);
545
546         do_action('delete_post', $postid);
547
548         if ( 'publish' == $post->post_status) {
549                 $categories = wp_get_post_cats('', $post->ID);
550                 if( is_array( $categories ) ) {
551                         foreach ( $categories as $cat_id ) {
552                                 $wpdb->query("UPDATE $wpdb->categories SET category_count = category_count - 1 WHERE cat_ID = '$cat_id'");
553                                 wp_cache_delete($cat_id, 'category');
554                         }
555                 }
556         }
557
558         if ( 'static' == $post->post_status )
559                 $wpdb->query("UPDATE $wpdb->posts SET post_parent = $post->post_parent WHERE post_parent = $postid AND post_status = 'static'");
560
561         $wpdb->query("UPDATE $wpdb->posts SET post_parent = $post->post_parent WHERE post_parent = $postid AND post_status = 'attachment'");
562
563         $wpdb->query("DELETE FROM $wpdb->posts WHERE ID = $postid");
564         
565         $wpdb->query("DELETE FROM $wpdb->comments WHERE comment_post_ID = $postid");
566
567         $wpdb->query("DELETE FROM $wpdb->post2cat WHERE post_id = $postid");
568
569         $wpdb->query("DELETE FROM $wpdb->postmeta WHERE post_id = $postid");
570
571         if ( 'static' == $post->post_status ) {
572                 wp_cache_delete('all_page_ids', 'pages');
573                 $wp_rewrite->flush_rules();
574         }
575
576         return $post;
577 }
578
579 /**** /DB Functions ****/
580
581 /**** Misc ****/
582
583 // get permalink from post ID
584 function post_permalink($post_id = 0, $mode = '') { // $mode legacy
585         return get_permalink($post_id);
586 }
587
588 // Get the name of a category from its ID
589 function get_cat_name($cat_id) {
590         global $wpdb;
591         
592         $cat_id -= 0;   // force numeric
593         $name = $wpdb->get_var("SELECT cat_name FROM $wpdb->categories WHERE cat_ID=$cat_id");
594         
595         return $name;
596 }
597
598 // Get the ID of a category from its name
599 function get_cat_ID($cat_name='General') {
600         global $wpdb;
601         
602         $cid = $wpdb->get_var("SELECT cat_ID FROM $wpdb->categories WHERE cat_name='$cat_name'");
603
604         return $cid?$cid:1;     // default to cat 1
605 }
606
607 // Get author's preferred display name
608 function get_author_name( $auth_id ) {
609         $authordata = get_userdata( $auth_id );
610
611         return $authordata->display_name;
612 }
613
614 // get extended entry info (<!--more-->)
615 function get_extended($post) {
616         list($main,$extended) = explode('<!--more-->', $post, 2);
617
618         // Strip leading and trailing whitespace
619         $main = preg_replace('/^[\s]*(.*)[\s]*$/','\\1',$main);
620         $extended = preg_replace('/^[\s]*(.*)[\s]*$/','\\1',$extended);
621
622         return array('main' => $main, 'extended' => $extended);
623 }
624
625 // do trackbacks for a list of urls
626 // borrowed from edit.php
627 // accepts a comma-separated list of trackback urls and a post id
628 function trackback_url_list($tb_list, $post_id) {
629         if (!empty($tb_list)) {
630                 // get post data
631                 $postdata = wp_get_single_post($post_id, ARRAY_A);
632
633                 // import postdata as variables
634                 extract($postdata);
635                 
636                 // form an excerpt
637                 $excerpt = strip_tags($post_excerpt?$post_excerpt:$post_content);
638                 
639                 if (strlen($excerpt) > 255) {
640                         $excerpt = substr($excerpt,0,252) . '...';
641                 }
642                 
643                 $trackback_urls = explode(',', $tb_list);
644                 foreach($trackback_urls as $tb_url) {
645                     $tb_url = trim($tb_url);
646                     trackback($tb_url, stripslashes($post_title), $excerpt, $post_id);
647                 }
648     }
649 }
650
651 function wp_blacklist_check($author, $email, $url, $comment, $user_ip, $user_agent) {
652         global $wpdb;
653
654         do_action('wp_blacklist_check', $author, $email, $url, $comment, $user_ip, $user_agent);
655
656         if ( preg_match_all('/&#(\d+);/', $comment . $author . $url, $chars) ) {
657                 foreach ($chars[1] as $char) {
658                         // If it's an encoded char in the normal ASCII set, reject
659                         if ($char < 128)
660                                 return true;
661                 }
662         }
663
664         $mod_keys = trim( get_settings('blacklist_keys') );
665         if ('' == $mod_keys )
666                 return false; // If moderation keys are empty
667         $words = explode("\n", $mod_keys );
668
669         foreach ($words as $word) {
670                 $word = trim($word);
671
672                 // Skip empty lines
673                 if ( empty($word) ) { continue; }
674
675                 // Do some escaping magic so that '#' chars in the 
676                 // spam words don't break things:
677                 $word = preg_quote($word, '#');
678                 
679                 $pattern = "#$word#i"; 
680                 if ( preg_match($pattern, $author    ) ) return true;
681                 if ( preg_match($pattern, $email     ) ) return true;
682                 if ( preg_match($pattern, $url       ) ) return true;
683                 if ( preg_match($pattern, $comment   ) ) return true;
684                 if ( preg_match($pattern, $user_ip   ) ) return true;
685                 if ( preg_match($pattern, $user_agent) ) return true;
686         }
687         
688         if ( isset($_SERVER['REMOTE_ADDR']) ) {
689                 if ( wp_proxy_check($_SERVER['REMOTE_ADDR']) ) return true;
690         }
691
692         return false;
693 }
694
695 function wp_proxy_check($ipnum) {
696         if ( get_option('open_proxy_check') && isset($ipnum) ) {
697                 $ipnum = preg_replace( '/([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}).*/', '$1', $ipnum );
698                 $rev_ip = implode( '.', array_reverse( explode( '.', $ipnum ) ) );
699                 $lookup = $rev_ip . '.sbl-xbl.spamhaus.org.';
700                 if ( $lookup != gethostbyname( $lookup ) )
701                         return true;
702         }
703
704         return false;
705 }
706
707 function do_trackbacks($post_id) {
708         global $wpdb;
709
710         $post = $wpdb->get_row("SELECT * FROM $wpdb->posts WHERE ID = $post_id");
711         $to_ping = get_to_ping($post_id);
712         $pinged  = get_pung($post_id);
713         if ( empty($to_ping) ) {
714                 $wpdb->query("UPDATE $wpdb->posts SET to_ping = '' WHERE ID = '$post_id'");
715                 return;
716         }
717         
718         if (empty($post->post_excerpt))
719                 $excerpt = apply_filters('the_content', $post->post_content);
720         else
721                 $excerpt = apply_filters('the_excerpt', $post->post_excerpt);
722         $excerpt = str_replace(']]>', ']]&gt;', $excerpt);
723         $excerpt = strip_tags($excerpt);
724         if ( function_exists('mb_strcut') ) // For international trackbacks
725         $excerpt = mb_strcut($excerpt, 0, 252, get_settings('blog_charset')) . '...';
726         else
727                 $excerpt = substr($excerpt, 0, 252) . '...';
728
729         $post_title = apply_filters('the_title', $post->post_title);
730         $post_title = strip_tags($post_title);
731
732         if ($to_ping) : foreach ($to_ping as $tb_ping) :
733                 $tb_ping = trim($tb_ping);
734                 if ( !in_array($tb_ping, $pinged) ) {
735                         trackback($tb_ping, $post_title, $excerpt, $post_id);
736                         $pinged[] = $tb_ping;
737                 } else {
738                         $wpdb->query("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, '$tb_ping', '')) WHERE ID = '$post_id'");
739                 }
740         endforeach; endif;
741 }
742
743 function get_pung($post_id) { // Get URIs already pung for a post
744         global $wpdb;
745         $pung = $wpdb->get_var("SELECT pinged FROM $wpdb->posts WHERE ID = $post_id");
746         $pung = trim($pung);
747         $pung = preg_split('/\s/', $pung);
748         $pung = apply_filters('get_pung', $pung);
749         return $pung;
750 }
751
752 function get_enclosed($post_id) { // Get enclosures already enclosed for a post
753         global $wpdb;
754         $custom_fields = get_post_custom( $post_id );
755         $pung = array();
756         if ( !is_array( $custom_fields ) )
757                 return $pung;
758
759         foreach ( $custom_fields as $key => $val ) {
760                 if ( 'enclosure' != $key || !is_array( $val ) )
761                         continue;
762                 foreach( $val as $enc ) {
763                         $enclosure = split( "\n", $enc );
764                         $pung[] = trim( $enclosure[ 0 ] );
765                 }
766         }
767         $pung = apply_filters('get_enclosed', $pung);
768         return $pung;
769 }
770
771 function get_to_ping($post_id) { // Get any URIs in the todo list
772         global $wpdb;
773         $to_ping = $wpdb->get_var("SELECT to_ping FROM $wpdb->posts WHERE ID = $post_id");
774         $to_ping = trim($to_ping);
775         $to_ping = preg_split('/\s/', $to_ping, -1, PREG_SPLIT_NO_EMPTY);
776         $to_ping = apply_filters('get_to_ping',  $to_ping);
777         return $to_ping;
778 }
779
780 function add_ping($post_id, $uri) { // Add a URI to those already pung
781         global $wpdb;
782         $pung = $wpdb->get_var("SELECT pinged FROM $wpdb->posts WHERE ID = $post_id");
783         $pung = trim($pung);
784         $pung = preg_split('/\s/', $pung);
785         $pung[] = $uri;
786         $new = implode("\n", $pung);
787         $new = apply_filters('add_ping', $new);
788         return $wpdb->query("UPDATE $wpdb->posts SET pinged = '$new' WHERE ID = $post_id");
789 }
790
791 //fetches the pages returned as a FLAT list, but arranged in order of their hierarchy, i.e., child parents
792 //immediately follow their parents
793 function get_page_hierarchy($posts, $parent = 0) {
794         $result = array ( );
795         if ($posts) { foreach ($posts as $post) {
796                 if ($post->post_parent == $parent) {
797                         $result[$post->ID] = $post->post_name;
798                         $children = get_page_hierarchy($posts, $post->ID);
799                         $result += $children; //append $children to $result
800                 }
801         } }
802         return $result;
803 }
804
805 function generate_page_rewrite_rules() {
806         global $wpdb;
807         
808         //get pages in order of hierarchy, i.e. children after parents
809         $posts = get_page_hierarchy($wpdb->get_results("SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_status = 'static'"));
810         //now reverse it, because we need parents after children for rewrite rules to work properly
811         $posts = array_reverse($posts, true);
812
813         $page_rewrite_rules = array();
814         $page_attachment_rewrite_rules = array();
815
816         if ($posts) {
817                 
818                 foreach ($posts as $id => $post) {
819
820                         // URI => page name
821                         $uri = get_page_uri($id);
822                         $attachments = $wpdb->get_results("SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_status = 'attachment' AND post_parent = '$id'");
823                         if ( $attachments ) {
824                                 foreach ( $attachments as $attachment ) {
825                                         $attach_uri = get_page_uri($attachment->ID);
826                                         $page_attachment_rewrite_rules[$attach_uri] = $attachment->post_name;
827                                 }
828                         }
829
830                         $page_rewrite_rules[$uri] = $post;
831                 }
832
833                 update_option('page_uris', $page_rewrite_rules);
834                 
835                 if ( $page_attachment_rewrite_rules )
836                         update_option('page_attachment_uris', $page_attachment_rewrite_rules);
837         }
838 }
839
840 function get_post_status($ID = '') {
841         $post = get_post($ID);
842
843         if ( is_object($post) ) {
844                 if ( ('attachment' == $post->post_status) && $post->post_parent && ($post->ID != $post->post_parent) )
845                         return get_post_status($post->post_parent);
846                 else
847                         return $post->post_status;
848         }
849
850         return false;
851 }
852
853 // Takes a post ID, returns its mime type.
854 function get_post_mime_type($ID = '') {
855         $post = & get_post($ID);
856
857         if ( is_object($post) )
858                 return $post->post_mime_type;
859
860         return false;
861 }
862
863 function get_attached_file($attachment_id) {
864         return get_post_meta($attachment_id, '_wp_attached_file', true);
865 }
866
867 function wp_mkdir_p($target) {
868         // from php.net/mkdir user contributed notes
869         if (file_exists($target)) {
870                 if (! @ is_dir($target))
871                         return false;
872                 else
873                         return true;
874         }
875
876         // Attempting to create the directory may clutter up our display.
877         if (@ mkdir($target)) {
878                 $stat = @ stat(dirname($target));
879                 $dir_perms = $stat['mode'] & 0007777;  // Get the permission bits.
880                 @ chmod($target, $dir_perms);
881                 return true;
882         } else {
883                 if ( is_dir(dirname($target)) )
884                         return false;   
885         }
886
887         // If the above failed, attempt to create the parent node, then try again.
888         if (wp_mkdir_p(dirname($target)))
889                 return wp_mkdir_p($target);
890
891         return false;
892 }
893
894 // Returns an array containing the current upload directory's path and url, or an error message.
895 function wp_upload_dir() {
896         $siteurl = get_settings('siteurl');
897         //prepend ABSPATH to $dir and $siteurl to $url if they're not already there
898         $path = str_replace(ABSPATH, '', trim(get_settings('upload_path')));
899         $dir = ABSPATH . $path;
900         $url = trailingslashit($siteurl) . $path;
901
902         if ( $dir == ABSPATH ) { //the option was empty
903                 $dir = ABSPATH . 'wp-content/uploads';
904         }
905
906         if ( defined('UPLOADS') ) {
907                 $dir = ABSPATH . UPLOADS;
908                 $url = trailingslashit($siteurl) . UPLOADS;
909         }
910
911         if ( get_settings('uploads_use_yearmonth_folders')) {
912                 // Generate the yearly and monthly dirs
913                 $time = current_time( 'mysql' );
914                 $y = substr( $time, 0, 4 );
915                 $m = substr( $time, 5, 2 );
916                 $dir = $dir . "/$y/$m";
917                 $url = $url . "/$y/$m";
918         }
919
920         // Make sure we have an uploads dir
921         if ( ! wp_mkdir_p( $dir ) ) {
922                 $message = sprintf(__('Unable to create directory %s. Is its parent directory writable by the server?'), $dir);
923                 return array('error' => $message);
924         }
925
926     $uploads = array('path' => $dir, 'url' => $url, 'error' => false);
927         return apply_filters('upload_dir', $uploads);
928 }
929
930 function wp_upload_bits($name, $type, $bits) {
931         if ( empty($name) )
932                 return array('error' => __("Empty filename"));
933
934         $wp_filetype = wp_check_filetype($name);
935         if ( !$wp_filetype['ext'] )
936                 return array('error' => __("Invalid file type"));
937
938         $upload = wp_upload_dir();
939         
940         if ( $upload['error'] !== false )
941                 return $upload;
942
943         $number = '';
944         $filename = $name;
945         $path_parts = pathinfo($filename);
946         $ext = $path_parts['extension'];
947         if ( empty($ext) )
948                 $ext = '';
949         else
950                 $ext = ".$ext";
951         while ( file_exists($upload['path'] . "/$filename") ) {
952                 if ( '' == "$number$ext" )
953                         $filename = $filename . ++$number . $ext;
954                 else
955                         $filename = str_replace("$number$ext", ++$number . $ext, $filename);
956         }
957                 
958         $new_file = $upload['path'] . "/$filename";
959         if ( ! wp_mkdir_p( dirname($new_file) ) ) {
960                 $message = sprintf(__('Unable to create directory %s. Is its parent directory writable by the server?'), dirname($new_file));
961                 return array('error' => $message);
962         }
963
964         $ifp = @ fopen($new_file, 'wb');
965         if ( ! $ifp )
966                 return array('error' => "Could not write file $new_file.");
967                 
968         $success = @ fwrite($ifp, $bits);
969         fclose($ifp);
970         // Set correct file permissions
971         $stat = @ stat(dirname($new_file));
972         $perms = $stat['mode'] & 0007777;
973         $perms = $perms & 0000666;
974         @ chmod($new_file, $perms);
975
976         // Compute the URL
977         $url = $upload['url'] . "/$filename";
978
979         return array('file' => $new_file, 'url' => $url, 'error' => false);
980 }
981
982 function wp_check_filetype($filename, $mimes = null) {
983         // Accepted MIME types are set here as PCRE unless provided.
984         $mimes = is_array($mimes) ? $mimes : apply_filters('upload_mimes', array (
985                 'jpg|jpeg|jpe' => 'image/jpeg',
986                 'gif' => 'image/gif',
987                 'png' => 'image/png',
988                 'bmp' => 'image/bmp',
989                 'tif|tiff' => 'image/tiff',
990                 'ico' => 'image/x-icon',
991                 'asf|asx|wax|wmv|wmx' => 'video/asf',
992                 'avi' => 'video/avi',
993                 'mov|qt' => 'video/quicktime',
994                 'mpeg|mpg|mpe' => 'video/mpeg',
995                 'txt|c|cc|h' => 'text/plain',
996                 'rtx' => 'text/richtext',
997                 'css' => 'text/css',
998                 'htm|html' => 'text/html',
999                 'mp3|mp4' => 'audio/mpeg',
1000                 'ra|ram' => 'audio/x-realaudio',
1001                 'wav' => 'audio/wav',
1002                 'ogg' => 'audio/ogg',
1003                 'mid|midi' => 'audio/midi',
1004                 'wma' => 'audio/wma',
1005                 'rtf' => 'application/rtf',
1006                 'js' => 'application/javascript',
1007                 'pdf' => 'application/pdf',
1008                 'doc' => 'application/msword',
1009                 'pot|pps|ppt' => 'application/vnd.ms-powerpoint',
1010                 'wri' => 'application/vnd.ms-write',
1011                 'xla|xls|xlt|xlw' => 'application/vnd.ms-excel',
1012                 'mdb' => 'application/vnd.ms-access',
1013                 'mpp' => 'application/vnd.ms-project',
1014                 'swf' => 'application/x-shockwave-flash',
1015                 'class' => 'application/java',
1016                 'tar' => 'application/x-tar',
1017                 'zip' => 'application/zip',
1018                 'gz|gzip' => 'application/x-gzip',
1019                 'exe' => 'application/x-msdownload'
1020         ));
1021
1022         $type = false;
1023         $ext = false;
1024
1025         foreach ($mimes as $ext_preg => $mime_match) {
1026                 $ext_preg = '!\.(' . $ext_preg . ')$!i';
1027                 if ( preg_match($ext_preg, $filename, $ext_matches) ) {
1028                         $type = $mime_match;
1029                         $ext = $ext_matches[1];
1030                         break;
1031                 }
1032         }
1033
1034         return compact('ext', 'type');
1035 }
1036
1037 ?>