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