]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-admin/admin-functions.php
Wordpress 2.0.11
[autoinstalls/wordpress.git] / wp-admin / admin-functions.php
1 <?php
2
3 // Creates a new post from the "Write Post" form using $_POST information.
4 function write_post() {
5         global $user_ID;
6
7         if (!current_user_can('edit_posts'))
8                 die(__('You are not allowed to create posts or drafts on this blog.'));
9
10         // Rename.
11         $_POST['post_content'] = $_POST['content'];
12         $_POST['post_excerpt'] = $_POST['excerpt'];
13         $_POST['post_parent'] = $_POST['parent_id'];
14         $_POST['to_ping'] = $_POST['trackback_url'];
15
16         if (!empty ($_POST['post_author_override'])) {
17                 $_POST['post_author'] = (int) $_POST['post_author_override'];
18         } else
19                 if (!empty ($_POST['post_author'])) {
20                         $_POST['post_author'] = (int) $_POST['post_author'];
21                 } else {
22                         $_POST['post_author'] = (int) $_POST['user_ID'];
23                 }
24
25         if (($_POST['post_author'] != $_POST['user_ID']) && !current_user_can('edit_others_posts'))
26                 die(__('You cannot post as this user.'));
27
28         // What to do based on which button they pressed
29         if ('' != $_POST['saveasdraft'])
30                 $_POST['post_status'] = 'draft';
31         if ('' != $_POST['saveasprivate'])
32                 $_POST['post_status'] = 'private';
33         if ('' != $_POST['publish'])
34                 $_POST['post_status'] = 'publish';
35         if ('' != $_POST['advanced'])
36                 $_POST['post_status'] = 'draft';
37         if ('' != $_POST['savepage'])
38                 $_POST['post_status'] = 'static';
39
40         if ('publish' == $_POST['post_status'] && !current_user_can('publish_posts'))
41                 $_POST['post_status'] = 'draft';
42
43         if ('static' == $_POST['post_status'] && !current_user_can('edit_pages'))
44                 die(__('This user cannot edit pages.'));
45
46         if (!isset ($_POST['comment_status']))
47                 $_POST['comment_status'] = 'closed';
48
49         if (!isset ($_POST['ping_status']))
50                 $_POST['ping_status'] = 'closed';
51
52         if (!empty ($_POST['edit_date'])) {
53                 $aa = $_POST['aa'];
54                 $mm = $_POST['mm'];
55                 $jj = $_POST['jj'];
56                 $hh = $_POST['hh'];
57                 $mn = $_POST['mn'];
58                 $ss = $_POST['ss'];
59                 $jj = ($jj > 31) ? 31 : $jj;
60                 $hh = ($hh > 23) ? $hh -24 : $hh;
61                 $mn = ($mn > 59) ? $mn -60 : $mn;
62                 $ss = ($ss > 59) ? $ss -60 : $ss;
63                 $_POST['post_date'] = "$aa-$mm-$jj $hh:$mn:$ss";
64                 $_POST['post_date_gmt'] = get_gmt_from_date("$aa-$mm-$jj $hh:$mn:$ss");
65         }
66
67         // Create the post.
68         $post_ID = wp_insert_post($_POST);
69         add_meta($post_ID);
70
71         // Reunite any orphaned attachments with their parent
72         if ( $_POST['temp_ID'] )
73                 relocate_children($_POST['temp_ID'], $post_ID);
74
75         // Now that we have an ID we can fix any attachment anchor hrefs
76         fix_attachment_links($post_ID);
77
78         return $post_ID;
79 }
80
81 // Move child posts to a new parent
82 function relocate_children($old_ID, $new_ID) {
83         global $wpdb;
84         $old_ID = (int) $old_ID;
85         $new_ID = (int) $new_ID;
86         return $wpdb->query("UPDATE $wpdb->posts SET post_parent = $new_ID WHERE post_parent = $old_ID");
87 }
88
89 // Replace hrefs of attachment anchors with up-to-date permalinks.
90 function fix_attachment_links($post_ID) {
91         global $wp_rewrite;
92
93         $post = & get_post($post_ID, ARRAY_A);
94
95         $search = "#<a[^>]+rel=('|\")[^'\"]*attachment[^>]*>#ie";
96
97         // See if we have any rel="attachment" links
98         if ( 0 == preg_match_all($search, $post['post_content'], $anchor_matches, PREG_PATTERN_ORDER) )
99                 return;
100
101         $i = 0;
102         $search = "# id=(\"|')p(\d+)\\1#i";
103         foreach ( $anchor_matches[0] as $anchor ) {
104                 if ( 0 == preg_match($search, $anchor, $id_matches) )
105                         continue;
106
107                 $id = $id_matches[2];
108
109                 // While we have the attachment ID, let's adopt any orphans.
110                 $attachment = & get_post($id, ARRAY_A);
111                 if ( ! empty($attachment) && ! is_object(get_post($attachment['post_parent'])) ) {
112                         $attachment['post_parent'] = $post_ID;
113                         // Escape data pulled from DB.
114                         $attachment = add_magic_quotes($attachment);
115                         wp_update_post($attachment);
116                 }
117
118                 $post_search[$i] = $anchor;
119                 $post_replace[$i] = preg_replace("#href=(\"|')[^'\"]*\\1#e", "stripslashes('href=\\1').get_attachment_link($id).stripslashes('\\1')", $anchor);
120                 ++$i;
121         }
122
123         $post['post_content'] = str_replace($post_search, $post_replace, $post['post_content']);
124
125         // Escape data pulled from DB.
126         $post = add_magic_quotes($post);
127
128         return wp_update_post($post);
129 }
130
131 // Update an existing post with values provided in $_POST.
132 function edit_post() {
133         global $user_ID;
134
135         $post_ID = (int) $_POST['post_ID'];
136
137         if (!current_user_can('edit_post', $post_ID))
138                 die(__('You are not allowed to edit this post.'));
139
140         // Rename.
141         $_POST['ID'] = (int) $_POST['post_ID'];
142         $_POST['post_content'] = $_POST['content'];
143         $_POST['post_excerpt'] = $_POST['excerpt'];
144         $_POST['post_parent'] = $_POST['parent_id'];
145         $_POST['to_ping'] = $_POST['trackback_url'];
146
147         if (!empty ($_POST['post_author_override'])) {
148                 $_POST['post_author'] = (int) $_POST['post_author_override'];
149         } else
150                 if (!empty ($_POST['post_author'])) {
151                         $_POST['post_author'] = (int) $_POST['post_author'];
152                 } else {
153                         $_POST['post_author'] = (int) $_POST['user_ID'];
154                 }
155
156         if (($_POST['post_author'] != $_POST['user_ID']) && !current_user_can('edit_others_posts'))
157                 die(__('You cannot post as this user.'));
158
159         // What to do based on which button they pressed
160         if ('' != $_POST['saveasdraft'])
161                 $_POST['post_status'] = 'draft';
162         if ('' != $_POST['saveasprivate'])
163                 $_POST['post_status'] = 'private';
164         if ('' != $_POST['publish'])
165                 $_POST['post_status'] = 'publish';
166         if ('' != $_POST['advanced'])
167                 $_POST['post_status'] = 'draft';
168         if ('' != $_POST['savepage'])
169                 $_POST['post_status'] = 'static';
170
171         if ('publish' == $_POST['post_status'] && !current_user_can('publish_posts'))
172                 $_POST['post_status'] = 'draft';
173
174         if ('static' == $_POST['post_status'] && !current_user_can('edit_pages'))
175                 die(__('This user cannot edit pages.'));
176
177         if (!isset ($_POST['comment_status']))
178                 $_POST['comment_status'] = 'closed';
179
180         if (!isset ($_POST['ping_status']))
181                 $_POST['ping_status'] = 'closed';
182
183         if (!empty ($_POST['edit_date'])) {
184                 $aa = $_POST['aa'];
185                 $mm = $_POST['mm'];
186                 $jj = $_POST['jj'];
187                 $hh = $_POST['hh'];
188                 $mn = $_POST['mn'];
189                 $ss = $_POST['ss'];
190                 $jj = ($jj > 31) ? 31 : $jj;
191                 $hh = ($hh > 23) ? $hh -24 : $hh;
192                 $mn = ($mn > 59) ? $mn -60 : $mn;
193                 $ss = ($ss > 59) ? $ss -60 : $ss;
194                 $_POST['post_date'] = "$aa-$mm-$jj $hh:$mn:$ss";
195                 $_POST['post_date_gmt'] = get_gmt_from_date("$aa-$mm-$jj $hh:$mn:$ss");
196         }
197
198         // Meta Stuff
199         if ($_POST['meta']) {
200                 foreach ($_POST['meta'] as $key => $value)
201                         update_meta($key, $value['key'], $value['value']);
202         }
203         
204         if ($_POST['deletemeta']) {
205                 foreach ($_POST['deletemeta'] as $key => $value)
206                         delete_meta($key);
207         }
208
209         add_meta($post_ID);
210
211         wp_update_post($_POST);
212
213         // Now that we have an ID we can fix any attachment anchor hrefs
214         fix_attachment_links($post_ID);
215
216         return $post_ID;
217 }
218
219 function edit_comment() {
220         global $user_ID;
221
222         $comment_ID = (int) $_POST['comment_ID'];
223         $comment_post_ID = (int) $_POST['comment_post_ID'];
224
225         if (!current_user_can('edit_post', $comment_post_ID))
226                 die(__('You are not allowed to edit comments on this post, so you cannot edit this comment.'));
227
228         $_POST['comment_author'] = $_POST['newcomment_author'];
229         $_POST['comment_author_email'] = $_POST['newcomment_author_email'];
230         $_POST['comment_author_url'] = $_POST['newcomment_author_url'];
231         $_POST['comment_approved'] = $_POST['comment_status'];
232         $_POST['comment_content'] = $_POST['content'];
233         $_POST['comment_ID'] = (int) $_POST['comment_ID'];
234
235         if (!empty ($_POST['edit_date'])) {
236                 $aa = $_POST['aa'];
237                 $mm = $_POST['mm'];
238                 $jj = $_POST['jj'];
239                 $hh = $_POST['hh'];
240                 $mn = $_POST['mn'];
241                 $ss = $_POST['ss'];
242                 $jj = ($jj > 31) ? 31 : $jj;
243                 $hh = ($hh > 23) ? $hh -24 : $hh;
244                 $mn = ($mn > 59) ? $mn -60 : $mn;
245                 $ss = ($ss > 59) ? $ss -60 : $ss;
246                 $_POST['comment_date'] = "$aa-$mm-$jj $hh:$mn:$ss";
247         }
248
249         wp_update_comment($_POST);
250 }
251
252 // Get an existing post and format it for editing.
253 function get_post_to_edit($id) {
254         global $richedit;
255         $richedit = ( 'true' == get_user_option('rich_editing') ) ? true : false;
256
257         $post = get_post($id);
258
259         $post->post_content = format_to_edit($post->post_content, $richedit);
260         $post->post_content = apply_filters('content_edit_pre', $post->post_content);
261
262         $post->post_excerpt = format_to_edit($post->post_excerpt);
263         $post->post_excerpt = apply_filters('excerpt_edit_pre', $post->post_excerpt);
264
265         $post->post_title = format_to_edit($post->post_title);
266         $post->post_title = apply_filters('title_edit_pre', $post->post_title);
267
268     $post->post_password = format_to_edit($post->post_password); 
269
270         if ($post->post_status == 'static')
271                 $post->page_template = get_post_meta($id, '_wp_page_template', true);
272
273         return $post;
274 }
275
276 // Default post information to use when populating the "Write Post" form.
277 function get_default_post_to_edit() {
278         if ( !empty($_REQUEST['post_title']) )
279                 $post_title = wp_specialchars(stripslashes($_REQUEST['post_title']));
280         else if ( !empty($_REQUEST['popuptitle']) ) {
281                 $post_title = wp_specialchars(stripslashes($_REQUEST['popuptitle']));
282                 $post_title = funky_javascript_fix($post_title);
283         } else {
284                 $post_title = '';
285         }
286
287         if ( !empty($_REQUEST['content']) )
288                 $post_content = wp_specialchars(stripslashes($_REQUEST['content']));
289         else if ( !empty($post_title) ) {
290                 $text       = wp_specialchars(stripslashes(urldecode($_REQUEST['text'])));
291                 $text       = funky_javascript_fix($text);
292                 $popupurl   = clean_url(stripslashes($_REQUEST['popupurl']));
293         $post_content = '<a href="'.$popupurl.'">'.$post_title.'</a>'."\n$text";
294     }
295
296         if ( !empty($_REQUEST['excerpt']) )
297                 $post_excerpt = wp_specialchars(stripslashes($_REQUEST['excerpt']));
298         else
299                 $post_excerpt = '';
300
301         $post->post_status = 'draft';
302         $post->comment_status = get_settings('default_comment_status');
303         $post->ping_status = get_settings('default_ping_status');
304         $post->post_pingback = get_settings('default_pingback_flag');
305         $post->post_category = get_settings('default_category');
306         $post->post_content = apply_filters('default_content', $post_content);
307         $post->post_title = apply_filters('default_title', $post_title);
308         $post->post_excerpt = apply_filters('default_excerpt', $post_excerpt);
309         $post->page_template = 'default';
310         $post->post_parent = 0;
311         $post->menu_order = 0;
312
313         return $post;
314 }
315
316 function get_comment_to_edit($id) {
317         global $richedit;
318         $richedit = ( 'true' == get_user_option('rich_editing') ) ? true : false;
319
320         $comment = get_comment($id);
321
322         $comment->comment_ID = (int) $comment->comment_ID;
323         $comment->comment_post_ID = (int) $comment->comment_post_ID;
324
325         $comment->comment_content = format_to_edit($comment->comment_content);
326         $comment->comment_content = apply_filters('comment_edit_pre', $comment->comment_content);
327
328         $comment->comment_author = format_to_edit($comment->comment_author);
329         $comment->comment_author_email = format_to_edit($comment->comment_author_email);
330         $comment->comment_author_url = clean_url($comment->comment_author_url);
331         $comment->comment_author_url = format_to_edit($comment->comment_author_url);
332
333         return $comment;
334 }
335
336 function get_category_to_edit($id) {
337         $category = get_category($id);
338
339         return $category;
340 }
341
342 function get_user_to_edit($user_id) {
343         $user = new WP_User($user_id);
344         $user->user_login   = attribute_escape($user->user_login);
345         $user->user_email   = attribute_escape($user->user_email);
346         $user->user_url     = clean_url($user->user_url);
347         $user->first_name   = attribute_escape($user->first_name);
348         $user->last_name    = attribute_escape($user->last_name);
349         $user->display_name = attribute_escape($user->display_name);
350         $user->nickname     = attribute_escape($user->nickname);
351         $user->aim          = attribute_escape($user->aim);
352         $user->yim          = attribute_escape($user->yim);
353         $user->jabber       = attribute_escape($user->jabber);
354         $user->description  =  wp_specialchars($user->description);
355
356         return $user;
357 }
358
359 // Creates a new user from the "Users" form using $_POST information.
360
361 function add_user() {
362         return edit_user();
363 }
364
365 function edit_user($user_id = 0) {
366         global $current_user, $wp_roles, $wpdb;
367
368         if ($user_id != 0) {
369                 $update = true;
370                 $user->ID = (int) $user_id;
371                 $userdata = get_userdata($user_id);
372                 $user->user_login = $wpdb->escape($userdata->user_login);
373         } else {
374                 $update = false;
375                 $user = '';
376         }
377
378         if (isset ($_POST['user_login']))
379                 $user->user_login = wp_specialchars(trim($_POST['user_login']));
380
381         $pass1 = $pass2 = '';
382         if (isset ($_POST['pass1']))
383                 $pass1 = $_POST['pass1'];
384         if (isset ($_POST['pass2']))
385                 $pass2 = $_POST['pass2'];
386
387         if (isset ($_POST['role']) && current_user_can('edit_users')) {
388                 if($user_id != $current_user->id || $wp_roles->role_objects[$_POST['role']]->has_cap('edit_users'))
389                         $user->role = $_POST['role'];
390         }
391
392         if (isset ($_POST['email']))
393                 $user->user_email = wp_specialchars(trim($_POST['email']));
394         if (isset ($_POST['url'])) {
395                 $user->user_url = clean_url(trim($_POST['url']));
396                 $user->user_url = preg_match('/^(https?|ftps?|mailto|news|gopher):/is', $user->user_url) ? $user->user_url : 'http://'.$user->user_url;
397         }
398         if (isset ($_POST['first_name']))
399                 $user->first_name = wp_specialchars(trim($_POST['first_name']));
400         if (isset ($_POST['last_name']))
401                 $user->last_name = wp_specialchars(trim($_POST['last_name']));
402         if (isset ($_POST['nickname']))
403                 $user->nickname = wp_specialchars(trim($_POST['nickname']));
404         if (isset ($_POST['display_name']))
405                 $user->display_name = wp_specialchars(trim($_POST['display_name']));
406         if (isset ($_POST['description']))
407                 $user->description = trim($_POST['description']);
408         if (isset ($_POST['jabber']))
409                 $user->jabber = wp_specialchars(trim($_POST['jabber']));
410         if (isset ($_POST['aim']))
411                 $user->aim = wp_specialchars(trim($_POST['aim']));
412         if (isset ($_POST['yim']))
413                 $user->yim = wp_specialchars(trim($_POST['yim']));
414
415         $errors = array ();
416
417         /* checking that username has been typed */
418         if ($user->user_login == '')
419                 $errors['user_login'] = __('<strong>ERROR</strong>: Please enter a username.');
420
421         /* checking the password has been typed twice */
422         do_action('check_passwords', array ($user->user_login, & $pass1, & $pass2));
423
424         if (!$update) {
425                 if ($pass1 == '' || $pass2 == '')
426                         $errors['pass'] = __('<strong>ERROR</strong>: Please enter your password twice.');
427         } else {
428                 if ((empty ($pass1) && !empty ($pass2)) || (empty ($pass2) && !empty ($pass1)))
429                         $errors['pass'] = __("<strong>ERROR</strong>: you typed your new password only once.");
430         }
431
432         /* Check for "\" in password */
433         if( strpos( " ".$pass1, "\\" ) )
434                 $errors['pass'] = __('<strong>ERROR</strong>: Passwords may not contain the character "\\".');
435
436         /* checking the password has been typed twice the same */
437         if ($pass1 != $pass2)
438                 $errors['pass'] = __('<strong>ERROR</strong>: Please type the same password in the two password fields.');
439
440         if (!empty ($pass1))
441                 $user->user_pass = $pass1;
442
443         if ( !validate_username($user->user_login) )
444                 $errors['user_login'] = __('<strong>ERROR</strong>: This username is invalid.  Please enter a valid username.');
445
446         if (!$update && username_exists($user->user_login))
447                 $errors['user_login'] = __('<strong>ERROR</strong>: This username is already registered, please choose another one.');
448
449         /* checking e-mail address */
450         if (empty ($user->user_email)) {
451                 $errors['user_email'] = __("<strong>ERROR</strong>: please type an e-mail address");
452         } else
453                 if (!is_email($user->user_email)) {
454                         $errors['user_email'] = __("<strong>ERROR</strong>: the email address isn't correct");
455                 }
456
457         if (count($errors) != 0)
458                 return $errors;
459
460         if ($update) {
461                 $user_id = wp_update_user(get_object_vars($user));
462         } else {
463                 $user_id = wp_insert_user(get_object_vars($user));
464                 wp_new_user_notification($user_id);
465         }
466
467         return $errors;
468 }
469
470
471 function get_link_to_edit($link_id) {
472         $link = get_link($link_id);
473
474         $link->link_url         =        clean_url($link->link_url);
475         $link->link_name        = attribute_escape($link->link_name);
476         $link->link_image       = attribute_escape($link->link_image);
477         $link->link_description = attribute_escape($link->link_description);
478         $link->link_rss         =        clean_url($link->link_rss);
479         $link->link_rel         = attribute_escape($link->link_rel);
480         $link->link_notes       =  wp_specialchars($link->link_notes);
481         $link->post_category    = $link->link_category;
482
483         return $link;
484 }
485
486 function get_default_link_to_edit() {
487         if ( isset($_GET['linkurl']) )
488                 $link->link_url = clean_url($_GET['linkurl']);
489         else
490                 $link->link_url = '';
491         
492         if ( isset($_GET['name']) )
493                 $link->link_name = attribute_escape($_GET['name']);
494         else
495                 $link->link_name = '';
496                 
497         return $link;
498 }
499
500 function add_link() {
501         return edit_link();     
502 }
503
504 function edit_link($link_id = '') {
505         if (!current_user_can('manage_links'))
506                 die(__("Cheatin' uh ?"));
507
508         $_POST['link_url'] = wp_specialchars($_POST['link_url']);
509         $_POST['link_url'] = clean_url($_POST['link_url']);
510         $_POST['link_name'] = wp_specialchars($_POST['link_name']);
511         $_POST['link_image'] = wp_specialchars($_POST['link_image']);
512         $_POST['link_rss'] = clean_url($_POST['link_rss']);
513         $auto_toggle = get_autotoggle($_POST['link_category']);
514         
515         // if we are in an auto toggle category and this one is visible then we
516         // need to make the others invisible before we add this new one.
517         // FIXME Add category toggle func.
518         //if (($auto_toggle == 'Y') && ($link_visible == 'Y')) {
519         //      $wpdb->query("UPDATE $wpdb->links set link_visible = 'N' WHERE link_category = $link_category");
520         //}
521
522         if ( !empty($link_id) ) {
523                 $_POST['link_id'] = $link_id;
524                 return wp_update_link($_POST);
525         } else {
526                 return wp_insert_link($_POST);
527         }
528 }
529
530 function url_shorten($url) {
531         $short_url = str_replace('http://', '', stripslashes($url));
532         $short_url = str_replace('www.', '', $short_url);
533         if ('/' == substr($short_url, -1))
534                 $short_url = substr($short_url, 0, -1);
535         if (strlen($short_url) > 35)
536                 $short_url = substr($short_url, 0, 32).'...';
537         return $short_url;
538 }
539
540 function selected($selected, $current) {
541         if ($selected == $current)
542                 echo ' selected="selected"';
543 }
544
545 function checked($checked, $current) {
546         if ($checked == $current)
547                 echo ' checked="checked"';
548 }
549
550 function return_categories_list($parent = 0) {
551         global $wpdb;
552         return $wpdb->get_col("SELECT cat_ID FROM $wpdb->categories WHERE category_parent = $parent ORDER BY category_count DESC");
553 }
554
555 function sort_cats($cat1, $cat2) {
556         return strcasecmp($cat1['cat_name'], $cat2['cat_name']);
557 }
558
559 function get_nested_categories($default = 0, $parent = 0) {
560         global $post_ID, $mode, $wpdb;
561
562         if ($post_ID) {
563                 $checked_categories = $wpdb->get_col("
564                      SELECT category_id
565                      FROM $wpdb->categories, $wpdb->post2cat
566                      WHERE $wpdb->post2cat.category_id = cat_ID AND $wpdb->post2cat.post_id = '$post_ID'
567                      ");
568
569                 if (count($checked_categories) == 0) {
570                         // No selected categories, strange
571                         $checked_categories[] = $default;
572                 }
573
574         } else {
575                 $checked_categories[] = $default;
576         }
577
578         $cats = return_categories_list($parent);
579         $result = array ();
580
581         if (is_array($cats)) {
582                 foreach ($cats as $cat) {
583                         $result[$cat]['children'] = get_nested_categories($default, $cat);
584                         $result[$cat]['cat_ID'] = $cat;
585                         $result[$cat]['checked'] = in_array($cat, $checked_categories);
586                         $result[$cat]['cat_name'] = get_the_category_by_ID($cat);
587                 }
588         }
589         
590         usort($result, 'sort_cats');
591
592         return $result;
593 }
594
595 function write_nested_categories($categories) {
596         foreach ($categories as $category) {
597                 echo '<label for="category-', $category['cat_ID'], '" class="selectit"><input value="', $category['cat_ID'], '" type="checkbox" name="post_category[]" id="category-', $category['cat_ID'], '"', ($category['checked'] ? ' checked="checked"' : ""), '/> ', wp_specialchars($category['cat_name']), "</label>\n";
598
599                 if (isset ($category['children'])) {
600                         echo "\n<span class='cat-nest'>\n";
601                         write_nested_categories($category['children']);
602                         echo "</span>\n";
603                 }
604         }
605 }
606
607 function dropdown_categories($default = 0) {
608         write_nested_categories(get_nested_categories($default));
609 }
610
611 // Dandy new recursive multiple category stuff.
612 function cat_rows($parent = 0, $level = 0, $categories = 0) {
613         global $wpdb, $class;
614
615         if (!$categories)
616                 $categories = $wpdb->get_results("SELECT * FROM $wpdb->categories ORDER BY cat_name");
617
618         if ($categories) {
619                 foreach ($categories as $category) {
620                         if ($category->category_parent == $parent) {
621                                 $category->cat_name = wp_specialchars($category->cat_name);
622                                 $pad = str_repeat('&#8212; ', $level);
623                                 if ( current_user_can('manage_categories') ) {
624                                         $edit = "<a href='categories.php?action=edit&amp;cat_ID=$category->cat_ID' class='edit'>".__('Edit')."</a></td>";
625                                         $default_cat_id = get_option('default_category');
626
627                                         if ($category->cat_ID != $default_cat_id)
628                                                 $edit .= "<td><a href='" . wp_nonce_url("categories.php?action=delete&amp;cat_ID=$category->cat_ID", 'delete-category_' . $category->cat_ID ) . "' onclick=\"return deleteSomething( 'cat', $category->cat_ID, '" . sprintf(__("You are about to delete the category &quot;%s&quot;.  All of its posts will go to the default category.\\n&quot;OK&quot; to delete, &quot;Cancel&quot; to stop."), js_escape($category->cat_name))."' );\" class='delete'>".__('Delete')."</a>";
629                                         else
630                                                 $edit .= "<td style='text-align:center'>".__("Default");
631                                 }
632                                 else
633                                         $edit = '';
634
635                                 $class = ('alternate' == $class) ? '' : 'alternate';
636                                 echo "<tr id='cat-$category->cat_ID' class='$class'><th scope='row'>$category->cat_ID</th><td>$pad $category->cat_name</td>
637                                                                 <td>$category->category_description</td>
638                                                                 <td>$category->category_count</td>
639                                                                 <td>$edit</td>
640                                                                 </tr>";
641                                 cat_rows($category->cat_ID, $level +1, $categories);
642                         }
643                 }
644         } else {
645                 return false;
646         }
647 }
648
649 function page_rows($parent = 0, $level = 0, $pages = 0) {
650         global $wpdb, $class, $post;
651         if (!$pages)
652                 $pages = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE post_status = 'static' ORDER BY menu_order");
653
654         if ($pages) {
655                 foreach ($pages as $post) {
656                         start_wp();
657                         if ($post->post_parent == $parent) {
658                                 $post->post_title = wp_specialchars($post->post_title);
659                                 $pad = str_repeat('&#8212; ', $level);
660                                 $id = $post->ID;
661                                 $class = ('alternate' == $class) ? '' : 'alternate';
662 ?>
663   <tr id='page-<?php echo $id; ?>' class='<?php echo $class; ?>'> 
664     <th scope="row"><?php echo $post->ID; ?></th> 
665     <td>
666       <?php echo $pad; ?><?php the_title() ?> 
667     </td> 
668     <td><?php the_author() ?></td>
669     <td><?php echo mysql2date('Y-m-d g:i a', $post->post_modified); ?></td> 
670         <td><a href="<?php the_permalink(); ?>" rel="permalink" class="edit"><?php _e('View'); ?></a></td>
671     <td><?php if ( current_user_can('edit_pages') ) { echo "<a href='post.php?action=edit&amp;post=$id' class='edit'>" . __('Edit') . "</a>"; } ?></td> 
672     <td><?php if ( current_user_can('edit_pages') ) { echo "<a href='" . wp_nonce_url("post.php?action=delete&amp;post=$id", 'delete-post_' . $id) .  "' class='delete' onclick=\"return deleteSomething( 'page', " . $id . ", '" . sprintf(__("You are about to delete the &quot;%s&quot; page.\\n&quot;OK&quot; to delete, &quot;Cancel&quot; to stop."), js_escape(get_the_title()) ) . "' );\">" . __('Delete') . "</a>"; } ?></td> 
673   </tr> 
674
675 <?php
676
677                                 page_rows($id, $level +1, $pages);
678                         }
679                 }
680         } else {
681                 return false;
682         }
683 }
684
685 function wp_dropdown_cats($currentcat = 0, $currentparent = 0, $parent = 0, $level = 0, $categories = 0) {
686         global $wpdb, $bgcolor;
687         if (!$categories) {
688                 $categories = $wpdb->get_results("SELECT * FROM $wpdb->categories ORDER BY cat_name");
689         }
690         if ($categories) {
691                 foreach ($categories as $category) {
692                         if ($currentcat != $category->cat_ID && $parent == $category->category_parent) {
693                                 $count = $wpdb->get_var("SELECT COUNT(post_id) FROM $wpdb->post2cat WHERE category_id = $category->cat_ID");
694                                 $pad = str_repeat('&#8211; ', $level);
695                                 $category->cat_name = wp_specialchars($category->cat_name);
696                                 echo "\n\t<option value='$category->cat_ID'";
697                                 if ($currentparent == $category->cat_ID)
698                                         echo " selected='selected'";
699                                 echo ">$pad$category->cat_name</option>";
700                                 wp_dropdown_cats($currentcat, $currentparent, $category->cat_ID, $level +1, $categories);
701                         }
702                 }
703         } else {
704                 return false;
705         }
706 }
707
708 function link_category_dropdown($fieldname, $selected = 0) {
709         global $wpdb;
710         
711         $results = $wpdb->get_results("SELECT cat_id, cat_name, auto_toggle FROM $wpdb->linkcategories ORDER BY cat_id");
712         echo "\n<select name='$fieldname' size='1'>\n";
713         foreach ($results as $row) {
714                 echo "\n\t<option value='$row->cat_id'";
715                 if ($row->cat_id == $selected)
716                         echo " selected='selected'";
717                 echo ">$row->cat_id : " . wp_specialchars($row->cat_name);
718                 if ($row->auto_toggle == 'Y')
719                         echo ' (auto toggle)';
720                 echo "</option>";
721         }
722         echo "\n</select>\n";
723 }
724
725 function wp_create_thumbnail($file, $max_side, $effect = '') {
726
727                 // 1 = GIF, 2 = JPEG, 3 = PNG
728
729         if (file_exists($file)) {
730                 $type = getimagesize($file);
731
732                 // if the associated function doesn't exist - then it's not
733                 // handle. duh. i hope.
734
735                 if (!function_exists('imagegif') && $type[2] == 1) {
736                         $error = __('Filetype not supported. Thumbnail not created.');
737                 }
738                 elseif (!function_exists('imagejpeg') && $type[2] == 2) {
739                         $error = __('Filetype not supported. Thumbnail not created.');
740                 }
741                 elseif (!function_exists('imagepng') && $type[2] == 3) {
742                         $error = __('Filetype not supported. Thumbnail not created.');
743                 } else {
744
745                         // create the initial copy from the original file
746                         if ($type[2] == 1) {
747                                 $image = imagecreatefromgif($file);
748                         }
749                         elseif ($type[2] == 2) {
750                                 $image = imagecreatefromjpeg($file);
751                         }
752                         elseif ($type[2] == 3) {
753                                 $image = imagecreatefrompng($file);
754                         }
755
756                         if (function_exists('imageantialias'))
757                                 imageantialias($image, TRUE);
758
759                         $image_attr = getimagesize($file);
760
761                         // figure out the longest side
762
763                         if ($image_attr[0] > $image_attr[1]) {
764                                 $image_width = $image_attr[0];
765                                 $image_height = $image_attr[1];
766                                 $image_new_width = $max_side;
767
768                                 $image_ratio = $image_width / $image_new_width;
769                                 $image_new_height = $image_height / $image_ratio;
770                                 //width is > height
771                         } else {
772                                 $image_width = $image_attr[0];
773                                 $image_height = $image_attr[1];
774                                 $image_new_height = $max_side;
775
776                                 $image_ratio = $image_height / $image_new_height;
777                                 $image_new_width = $image_width / $image_ratio;
778                                 //height > width
779                         }
780
781                         $thumbnail = imagecreatetruecolor($image_new_width, $image_new_height);
782                         @ imagecopyresampled($thumbnail, $image, 0, 0, 0, 0, $image_new_width, $image_new_height, $image_attr[0], $image_attr[1]);
783
784                         // If no filters change the filename, we'll do a default transformation.
785                         if ( basename($file) == $thumb = apply_filters('thumbnail_filename', basename($file)) )
786                                 $thumb = preg_replace('!(\.[^.]+)?$!', __('.thumbnail').'$1', basename($file), 1);
787
788                         $thumbpath = str_replace(basename($file), $thumb, $file);
789
790                         // move the thumbnail to it's final destination
791                         if ($type[2] == 1) {
792                                 if (!imagegif($thumbnail, $thumbpath)) {
793                                         $error = __("Thumbnail path invalid");
794                                 }
795                         }
796                         elseif ($type[2] == 2) {
797                                 if (!imagejpeg($thumbnail, $thumbpath)) {
798                                         $error = __("Thumbnail path invalid");
799                                 }
800                         }
801                         elseif ($type[2] == 3) {
802                                 if (!imagepng($thumbnail, $thumbpath)) {
803                                         $error = __("Thumbnail path invalid");
804                                 }
805                         }
806
807                 }
808         } else {
809                 $error = __('File not found');
810         }
811
812         if (!empty ($error)) {
813                 return $error;
814         } else {
815                 return $thumbpath;
816         }
817 }
818
819 // Some postmeta stuff
820 function has_meta($postid) {
821         global $wpdb;
822
823         return $wpdb->get_results("
824                         SELECT meta_key, meta_value, meta_id, post_id
825                         FROM $wpdb->postmeta
826                         WHERE post_id = '$postid'
827                         ORDER BY meta_key,meta_id", ARRAY_A);
828
829 }
830
831 function list_meta($meta) {
832         global $post_ID;
833         // Exit if no meta
834         if (!$meta)
835                 return;
836         $count = 0;
837 ?>
838 <table id='meta-list' cellpadding="3">
839         <tr>
840                 <th><?php _e('Key') ?></th>
841                 <th><?php _e('Value') ?></th>
842                 <th colspan='2'><?php _e('Action') ?></th>
843         </tr>
844 <?php
845
846
847         foreach ($meta as $entry) {
848                 ++ $count;
849                 if ($count % 2)
850                         $style = 'alternate';
851                 else
852                         $style = '';
853                 if ('_' == $entry['meta_key'] { 0 })
854                         $style .= ' hidden';
855
856                 if ( is_serialized($entry['meta_value']) ) {
857                         if ( is_serialized_string($entry['meta_value']) ) {
858                                 // this is a serialized string, so we should display it
859                                 $entry['meta_value'] = maybe_unserialize($entry['meta_value']);
860                         } else {
861                                 // this is a serialized array/object so we should NOT display it
862                                 --$count;
863                                 continue;
864                         }
865                 }
866
867                 $entry['meta_key'] = attribute_escape( $entry['meta_key']);
868                 $entry['meta_value'] = attribute_escape( $entry['meta_value']);
869                 $entry['meta_id'] = (int) $entry['meta_id'];
870                 echo "
871                         <tr class='$style'>
872                                 <td valign='top'><input name='meta[{$entry['meta_id']}][key]' tabindex='6' type='text' size='20' value='{$entry['meta_key']}' /></td>
873                                 <td><textarea name='meta[{$entry['meta_id']}][value]' tabindex='6' rows='2' cols='30'>{$entry['meta_value']}</textarea></td>
874                                 <td align='center'><input name='updatemeta' type='submit' class='updatemeta' tabindex='6' value='".attribute_escape(__('Update'))."' /><br />
875                                 <input name='deletemeta[{$entry['meta_id']}]' type='submit' class='deletemeta' tabindex='6' value='".attribute_escape(__('Delete'))."' /></td>
876                         </tr>
877                 ";
878         }
879         echo "
880                 </table>
881         ";
882 }
883
884 // Get a list of previously defined keys
885 function get_meta_keys() {
886         global $wpdb;
887
888         $keys = $wpdb->get_col("
889                         SELECT meta_key
890                         FROM $wpdb->postmeta
891                         GROUP BY meta_key
892                         ORDER BY meta_key");
893
894         return $keys;
895 }
896
897 function meta_form() {
898         global $wpdb;
899         $keys = $wpdb->get_col("
900                         SELECT meta_key
901                         FROM $wpdb->postmeta
902                         GROUP BY meta_key
903                         ORDER BY meta_id DESC
904                         LIMIT 10");
905 ?>
906 <h3><?php _e('Add a new custom field:') ?></h3>
907 <table cellspacing="3" cellpadding="3">
908         <tr>
909 <th colspan="2"><?php _e('Key') ?></th>
910 <th><?php _e('Value') ?></th>
911 </tr>
912         <tr valign="top">
913                 <td align="right" width="18%">
914 <?php if ($keys) : ?>
915 <select id="metakeyselect" name="metakeyselect" tabindex="7">
916 <option value="#NONE#"><?php _e('- Select -'); ?></option>
917 <?php
918
919         foreach ($keys as $key) {
920                 $key = attribute_escape($key);
921                 echo "\n\t<option value='$key'>$key</option>";
922         }
923 ?>
924 </select> <?php _e('or'); ?>
925 <?php endif; ?>
926 </td>
927 <td><input type="text" id="metakeyinput" name="metakeyinput" tabindex="7" /></td>
928                 <td><textarea id="metavalue" name="metavalue" rows="3" cols="25" tabindex="8"></textarea></td>
929         </tr>
930
931 </table>
932 <p class="submit"><input type="submit" name="updatemeta" tabindex="9" value="<?php _e('Add Custom Field &raquo;') ?>" /></p>
933 <?php
934
935 }
936
937 function add_meta($post_ID) {
938         global $wpdb;
939         $post_ID = (int) $post_ID;
940
941         $protected = array( '_wp_attached_file', '_wp_attachment_metadata', '_wp_old_slug', '_wp_page_template' );
942
943         $metakeyselect = $wpdb->escape(stripslashes(trim($_POST['metakeyselect'])));
944         $metakeyinput = $wpdb->escape(stripslashes(trim($_POST['metakeyinput'])));
945         $metavalue = maybe_serialize(stripslashes((trim($_POST['metavalue']))));
946         $metavalue = $wpdb->escape($metavalue);
947
948         if ( ('0' === $metavalue || !empty ($metavalue)) && ((('#NONE#' != $metakeyselect) && !empty ($metakeyselect)) || !empty ($metakeyinput)) ) {
949                 // We have a key/value pair. If both the select and the 
950                 // input for the key have data, the input takes precedence:
951
952                 if ('#NONE#' != $metakeyselect)
953                         $metakey = $metakeyselect;
954
955                 if ($metakeyinput)
956                         $metakey = $metakeyinput; // default
957
958                 if ( in_array($metakey, $protected) )
959                         return false;
960
961                 $result = $wpdb->query("
962                                                 INSERT INTO $wpdb->postmeta 
963                                                 (post_id,meta_key,meta_value) 
964                                                 VALUES ('$post_ID','$metakey','$metavalue')
965                                         ");
966         }
967 } // add_meta
968
969 function delete_meta($mid) {
970         global $wpdb;
971         $mid = (int) $mid;
972
973         $result = $wpdb->query("DELETE FROM $wpdb->postmeta WHERE meta_id = '$mid'");
974 }
975
976 function update_meta($mid, $mkey, $mvalue) {
977         global $wpdb;
978
979         $protected = array( '_wp_attached_file', '_wp_attachment_metadata', '_wp_old_slug', '_wp_page_template' );
980
981         if ( in_array($mkey, $protected) )
982                 return false;
983
984         $mvalue = maybe_serialize(stripslashes($mvalue));
985         $mvalue = $wpdb->escape($mvalue);
986         $mid = (int) $mid;
987         return $wpdb->query("UPDATE $wpdb->postmeta SET meta_key = '$mkey', meta_value = '$mvalue' WHERE meta_id = '$mid'");
988 }
989
990 function touch_time($edit = 1, $for_post = 1) {
991         global $month, $post, $comment;
992
993         if ( $for_post )
994                 $edit = ( ('draft' == $post->post_status) && (!$post->post_date || '0000-00-00 00:00:00' == $post->post_date) ) ? false : true;
995  
996         echo '<fieldset><legend><input type="checkbox" class="checkbox" name="edit_date" value="1" id="timestamp" /> <label for="timestamp">'.__('Edit timestamp').'</label></legend>';
997
998         $time_adj = time() + (get_settings('gmt_offset') * 3600);
999         $post_date = ($for_post) ? $post->post_date : $comment->comment_date;
1000         $jj = ($edit) ? mysql2date('d', $post_date) : gmdate('d', $time_adj);
1001         $mm = ($edit) ? mysql2date('m', $post_date) : gmdate('m', $time_adj);
1002         $aa = ($edit) ? mysql2date('Y', $post_date) : gmdate('Y', $time_adj);
1003         $hh = ($edit) ? mysql2date('H', $post_date) : gmdate('H', $time_adj);
1004         $mn = ($edit) ? mysql2date('i', $post_date) : gmdate('i', $time_adj);
1005         $ss = ($edit) ? mysql2date('s', $post_date) : gmdate('s', $time_adj);
1006
1007         echo "<select name=\"mm\">\n";
1008         for ($i = 1; $i < 13; $i = $i +1) {
1009                 echo "\t\t\t<option value=\"$i\"";
1010                 if ($i == $mm)
1011                         echo " selected='selected'";
1012                 if ($i < 10) {
1013                         $ii = "0".$i;
1014                 } else {
1015                         $ii = "$i";
1016                 }
1017                 echo ">".$month["$ii"]."</option>\n";
1018         }
1019 ?>
1020 </select>
1021 <input type="text" id="jj" name="jj" value="<?php echo $jj; ?>" size="2" maxlength="2" />
1022 <input type="text" id="aa" name="aa" value="<?php echo $aa ?>" size="4" maxlength="5" /> @ 
1023 <input type="text" id="hh" name="hh" value="<?php echo $hh ?>" size="2" maxlength="2" /> : 
1024 <input type="text" id="mn" name="mn" value="<?php echo $mn ?>" size="2" maxlength="2" /> 
1025 <input type="hidden" id="ss" name="ss" value="<?php echo $ss ?>" size="2" maxlength="2" /> 
1026 <?php
1027         if ( $edit ) {
1028                 _e('Existing timestamp');
1029                 echo ": {$month[$mm]} $jj, $aa @ $hh:$mn";
1030         }
1031 ?>
1032 </fieldset>
1033         <?php
1034
1035 }
1036
1037 // insert_with_markers: Owen Winkler, fixed by Eric Anderson
1038 // Inserts an array of strings into a file (.htaccess), placing it between
1039 // BEGIN and END markers.  Replaces existing marked info.  Retains surrounding
1040 // data.  Creates file if none exists.
1041 // Returns true on write success, false on failure.
1042 function insert_with_markers($filename, $marker, $insertion) {
1043         if (!file_exists($filename) || is_writeable($filename)) {
1044                 if (!file_exists($filename)) {
1045                         $markerdata = '';
1046                 } else {
1047                         $markerdata = explode("\n", implode('', file($filename)));
1048                 }
1049
1050                 $f = fopen($filename, 'w');
1051                 $foundit = false;
1052                 if ($markerdata) {
1053                         $state = true;
1054                         foreach ($markerdata as $markerline) {
1055                                 if (strstr($markerline, "# BEGIN {$marker}"))
1056                                         $state = false;
1057                                 if ($state)
1058                                         fwrite($f, "{$markerline}\n");
1059                                 if (strstr($markerline, "# END {$marker}")) {
1060                                         fwrite($f, "# BEGIN {$marker}\n");
1061                                         if (is_array($insertion))
1062                                                 foreach ($insertion as $insertline)
1063                                                         fwrite($f, "{$insertline}\n");
1064                                         fwrite($f, "# END {$marker}\n");
1065                                         $state = true;
1066                                         $foundit = true;
1067                                 }
1068                         }
1069                 }
1070                 if (!$foundit) {
1071                         fwrite($f, "# BEGIN {$marker}\n");
1072                         foreach ($insertion as $insertline)
1073                                 fwrite($f, "{$insertline}\n");
1074                         fwrite($f, "# END {$marker}\n");
1075                 }
1076                 fclose($f);
1077                 return true;
1078         } else {
1079                 return false;
1080         }
1081 }
1082
1083 // extract_from_markers: Owen Winkler
1084 // Returns an array of strings from a file (.htaccess) from between BEGIN
1085 // and END markers.
1086 function extract_from_markers($filename, $marker) {
1087         $result = array ();
1088
1089         if (!file_exists($filename)) {
1090                 return $result;
1091         }
1092
1093         if ($markerdata = explode("\n", implode('', file($filename))));
1094         {
1095                 $state = false;
1096                 foreach ($markerdata as $markerline) {
1097                         if (strstr($markerline, "# END {$marker}"))
1098                                 $state = false;
1099                         if ($state)
1100                                 $result[] = $markerline;
1101                         if (strstr($markerline, "# BEGIN {$marker}"))
1102                                 $state = true;
1103                 }
1104         }
1105
1106         return $result;
1107 }
1108
1109 function got_mod_rewrite() {
1110         global $is_apache;
1111
1112         // take 3 educated guesses as to whether or not mod_rewrite is available
1113         if ( !$is_apache )
1114                 return false;
1115
1116         if ( function_exists('apache_get_modules') ) {
1117                 if ( !in_array('mod_rewrite', apache_get_modules()) )
1118                         return false;
1119         }
1120
1121         return true;
1122 }
1123
1124 function save_mod_rewrite_rules() {
1125         global $is_apache, $wp_rewrite;
1126         $home_path = get_home_path();
1127
1128         if (!$wp_rewrite->using_mod_rewrite_permalinks())
1129                 return;
1130
1131         if (!((!file_exists($home_path.'.htaccess') && is_writable($home_path)) || is_writable($home_path.'.htaccess')))
1132                 return;
1133
1134         if (! got_mod_rewrite())
1135                 return;
1136
1137         $rules = explode("\n", $wp_rewrite->mod_rewrite_rules());
1138         insert_with_markers($home_path.'.htaccess', 'WordPress', $rules);
1139 }
1140
1141 function the_quicktags() {
1142                 echo '
1143                 <div id="quicktags">
1144                         <script src="../wp-includes/js/quicktags.js" type="text/javascript"></script>
1145                         <script type="text/javascript">if ( typeof tinyMCE == "undefined" || tinyMCE.configs.length < 1 ) edToolbar();</script>
1146                 </div>
1147 ';
1148         echo '
1149 <script type="text/javascript">
1150 function edInsertContent(myField, myValue) {
1151         //IE support
1152         if (document.selection) {
1153                 myField.focus();
1154                 sel = document.selection.createRange();
1155                 sel.text = myValue;
1156                 myField.focus();
1157         }
1158         //MOZILLA/NETSCAPE support
1159         else if (myField.selectionStart || myField.selectionStart == "0") {
1160                 var startPos = myField.selectionStart;
1161                 var endPos = myField.selectionEnd;
1162                 myField.value = myField.value.substring(0, startPos)
1163                               + myValue 
1164                       + myField.value.substring(endPos, myField.value.length);
1165                 myField.focus();
1166                 myField.selectionStart = startPos + myValue.length;
1167                 myField.selectionEnd = startPos + myValue.length;
1168         } else {
1169                 myField.value += myValue;
1170                 myField.focus();
1171         }
1172 }
1173 </script>
1174 ';
1175 }
1176
1177 function validate_current_theme() {
1178         $theme_loc = 'wp-content/themes';
1179         $theme_root = ABSPATH.$theme_loc;
1180
1181         $template = get_settings('template');
1182         $stylesheet = get_settings('stylesheet');
1183
1184         if (($template != 'default') && (!file_exists("$theme_root/$template/index.php"))) {
1185                 update_option('template', 'default');
1186                 update_option('stylesheet', 'default');
1187                 do_action('switch_theme', 'Default');
1188                 return false;
1189         }
1190
1191         if (($stylesheet != 'default') && (!file_exists("$theme_root/$stylesheet/style.css"))) {
1192                 update_option('template', 'default');
1193                 update_option('stylesheet', 'default');
1194                 do_action('switch_theme', 'Default');
1195                 return false;
1196         }
1197
1198         return true;
1199 }
1200
1201 function get_broken_themes() {
1202         global $wp_broken_themes;
1203
1204         get_themes();
1205         return $wp_broken_themes;
1206 }
1207
1208 function get_page_templates() {
1209         $themes = get_themes();
1210         $theme = get_current_theme();
1211         $templates = $themes[$theme]['Template Files'];
1212         $page_templates = array ();
1213
1214         if (is_array($templates)) {
1215                 foreach ($templates as $template) {
1216                         $template_data = implode('', file(ABSPATH.$template));
1217                         preg_match("|Template Name:(.*)|i", $template_data, $name);
1218                         preg_match("|Description:(.*)|i", $template_data, $description);
1219
1220                         $name = $name[1];
1221                         $description = $description[1];
1222
1223                         if (!empty ($name)) {
1224                                 $page_templates[trim($name)] = basename($template);
1225                         }
1226                 }
1227         }
1228
1229         return $page_templates;
1230 }
1231
1232 function page_template_dropdown($default = '') {
1233         $templates = get_page_templates();
1234         foreach (array_keys($templates) as $template)
1235                 : if ($default == $templates[$template])
1236                         $selected = " selected='selected'";
1237                 else
1238                         $selected = '';
1239         echo "\n\t<option value='".$templates[$template]."' $selected>$template</option>";
1240         endforeach;
1241 }
1242
1243 function parent_dropdown($default = 0, $parent = 0, $level = 0) {
1244         global $wpdb, $post_ID;
1245         $items = $wpdb->get_results("SELECT ID, post_parent, post_title FROM $wpdb->posts WHERE post_parent = $parent AND post_status = 'static' ORDER BY menu_order");
1246
1247         if ($items) {
1248                 foreach ($items as $item) {
1249                         // A page cannot be it's own parent.
1250                         if (!empty ($post_ID)) {
1251                                 if ($item->ID == $post_ID) {
1252                                         continue;
1253                                 }
1254                         }
1255                         $pad = str_repeat('&nbsp;', $level * 3);
1256                         if ($item->ID == $default)
1257                                 $current = ' selected="selected"';
1258                         else
1259                                 $current = '';
1260
1261                         echo "\n\t<option value='$item->ID'$current>$pad $item->post_title</option>";
1262                         parent_dropdown($default, $item->ID, $level +1);
1263                 }
1264         } else {
1265                 return false;
1266         }
1267 }
1268
1269 function user_can_access_admin_page() {
1270         global $pagenow;
1271         global $menu;
1272         global $submenu;
1273         global $plugin_page;
1274
1275         $parent = get_admin_page_parent();
1276
1277         foreach ($menu as $menu_array) {
1278                 //echo "parent array: " . $menu_array[2];
1279                 if ($menu_array[2] == $parent) {
1280                         if (!current_user_can($menu_array[1])) {
1281                                 return false;
1282                         } else {
1283                                 break;
1284                         }
1285                 }
1286         }
1287
1288         if (isset ($submenu[$parent])) {
1289                 if ( isset($plugin_page) ) {
1290                         foreach ($submenu[$parent] as $submenu_array) {
1291                                 if ( $submenu_array[2] == $plugin_page ) {
1292                                         if (!current_user_can($submenu_array[1]))
1293                                                 return false;
1294                                 }
1295                         }
1296                 }
1297
1298                 foreach ($submenu[$parent] as $submenu_array) {         
1299                         if ($submenu_array[2] == $pagenow) {
1300                                 if (!current_user_can($submenu_array[1]))
1301                                         return false;
1302                                 else
1303                                         return true;
1304                         }
1305                 }
1306         }
1307
1308         return true;
1309 }
1310
1311 function get_admin_page_title() {
1312         global $title;
1313         global $menu;
1314         global $submenu;
1315         global $pagenow;
1316         global $plugin_page;
1317
1318         if (isset ($title) && !empty ($title)) {
1319                 return $title;
1320         }
1321
1322         $hook = get_plugin_page_hook($plugin_page, $pagenow);
1323
1324         $parent = $parent1 = get_admin_page_parent();
1325         if (empty ($parent)) {
1326                 foreach ($menu as $menu_array) {
1327                         if (isset ($menu_array[3])) {
1328                                 if ($menu_array[2] == $pagenow) {
1329                                         $title = $menu_array[3];
1330                                         return $menu_array[3];
1331                                 } else
1332                                         if (isset ($plugin_page) && ($plugin_page == $menu_array[2]) && ($hook == $menu_array[3])) {
1333                                                 $title = $menu_array[3];
1334                                                 return $menu_array[3];
1335                                         }
1336                         }
1337                 }
1338         } else {
1339                 foreach (array_keys($submenu) as $parent) {
1340                         foreach ($submenu[$parent] as $submenu_array) {
1341                                 if (isset ($submenu_array[3])) {
1342                                         if ($submenu_array[2] == $pagenow) {
1343                                                 $title = $submenu_array[3];
1344                                                 return $submenu_array[3];
1345                                         } else
1346                                                 if (isset ($plugin_page) && ($plugin_page == $submenu_array[2]) && (($parent == $pagenow) || ($parent == $plugin_page) || ($plugin_page == $hook) || (($pagenow == 'admin.php') && ($parent1 != $submenu_array[2])))) {
1347                                                         $title = $submenu_array[3];
1348                                                         return $submenu_array[3];
1349                                                 }
1350                                 }
1351                         }
1352                 }
1353         }
1354
1355         return '';
1356 }
1357
1358 function get_admin_page_parent() {
1359         global $parent_file;
1360         global $menu;
1361         global $submenu;
1362         global $pagenow;
1363         global $plugin_page;
1364
1365         if (isset ($parent_file) && !empty ($parent_file)) {
1366                 return $parent_file;
1367         }
1368
1369         if ($pagenow == 'admin.php' && isset ($plugin_page)) {
1370                 foreach ($menu as $parent_menu) {
1371                         if ($parent_menu[2] == $plugin_page) {
1372                                 $parent_file = $plugin_page;
1373                                 return $plugin_page;
1374                         }
1375                 }
1376         }
1377
1378         foreach (array_keys($submenu) as $parent) {
1379                 foreach ($submenu[$parent] as $submenu_array) {
1380                         if ($submenu_array[2] == $pagenow) {
1381                                 $parent_file = $parent;
1382                                 return $parent;
1383                         } else
1384                                 if (isset ($plugin_page) && ($plugin_page == $submenu_array[2])) {
1385                                         $parent_file = $parent;
1386                                         return $parent;
1387                                 }
1388                 }
1389         }
1390
1391         $parent_file = '';
1392         return '';
1393 }
1394
1395 function add_menu_page($page_title, $menu_title, $access_level, $file, $function = '') {
1396         global $menu, $admin_page_hooks;
1397
1398         $file = plugin_basename($file);
1399
1400         $menu[] = array ($menu_title, $access_level, $file, $page_title);
1401
1402         $admin_page_hooks[$file] = sanitize_title($menu_title);
1403
1404         $hookname = get_plugin_page_hookname($file, '');
1405         if (!empty ($function) && !empty ($hookname))
1406                 add_action($hookname, $function);
1407
1408         return $hookname;
1409 }
1410
1411 function add_submenu_page($parent, $page_title, $menu_title, $access_level, $file, $function = '') {
1412         global $submenu;
1413         global $menu;
1414
1415         $parent = plugin_basename($parent);
1416         $file = plugin_basename($file);
1417
1418         // If the parent doesn't already have a submenu, add a link to the parent
1419         // as the first item in the submenu.  If the submenu file is the same as the
1420         // parent file someone is trying to link back to the parent manually.  In
1421         // this case, don't automatically add a link back to avoid duplication.
1422         if (!isset ($submenu[$parent]) && $file != $parent) {
1423                 foreach ($menu as $parent_menu) {
1424                         if ($parent_menu[2] == $parent) {
1425                                 $submenu[$parent][] = $parent_menu;
1426                         }
1427                 }
1428         }
1429
1430         $submenu[$parent][] = array ($menu_title, $access_level, $file, $page_title);
1431
1432         $hookname = get_plugin_page_hookname($file, $parent);
1433         if (!empty ($function) && !empty ($hookname))
1434                 add_action($hookname, $function);
1435
1436         return $hookname;
1437 }
1438
1439 function add_options_page($page_title, $menu_title, $access_level, $file, $function = '') {
1440         return add_submenu_page('options-general.php', $page_title, $menu_title, $access_level, $file, $function);
1441 }
1442
1443 function add_management_page($page_title, $menu_title, $access_level, $file, $function = '') {
1444         return add_submenu_page('edit.php', $page_title, $menu_title, $access_level, $file, $function);
1445 }
1446
1447 function add_theme_page($page_title, $menu_title, $access_level, $file, $function = '') {
1448         return add_submenu_page('themes.php', $page_title, $menu_title, $access_level, $file, $function);
1449 }
1450
1451 function validate_file($file, $allowed_files = '') {
1452         if (false !== strpos($file, './'))
1453                 return 1;
1454
1455         if (':' == substr($file, 1, 1))
1456                 return 2;
1457
1458         if (!empty ($allowed_files) && (!in_array($file, $allowed_files)))
1459                 return 3;
1460
1461         return 0;
1462 }
1463
1464 function validate_file_to_edit($file, $allowed_files = '') {
1465         $file = stripslashes($file);
1466
1467         $code = validate_file($file, $allowed_files);
1468
1469         if (!$code)
1470                 return $file;
1471
1472         switch ($code) {
1473                 case 1 :
1474                         die(__('Sorry, can&#8217;t edit files with ".." in the name. If you are trying to edit a file in your WordPress home directory, you can just type the name of the file in.'));
1475
1476                 case 2 :
1477                         die(__('Sorry, can&#8217;t call files with their real path.'));
1478
1479                 case 3 :
1480                         die(__('Sorry, that file cannot be edited.'));
1481         }
1482 }
1483
1484 function get_home_path() {
1485         $home = get_settings('home');
1486         if ($home != '' && $home != get_settings('siteurl')) {
1487                 $home_path = parse_url($home);
1488                 $home_path = $home_path['path'];
1489                 $root = str_replace($_SERVER["PHP_SELF"], '', $_SERVER["SCRIPT_FILENAME"]);
1490                 $home_path = trailingslashit($root.$home_path);
1491         } else {
1492                 $home_path = ABSPATH;
1493         }
1494
1495         return $home_path;
1496 }
1497
1498 function get_real_file_to_edit($file) {
1499         if ('index.php' == $file || '.htaccess' == $file) {
1500                 $real_file = get_home_path().$file;
1501         } else {
1502                 $real_file = ABSPATH.$file;
1503         }
1504
1505         return $real_file;
1506 }
1507
1508 $wp_file_descriptions = array ('index.php' => __('Main Index Template'), 'style.css' => __('Stylesheet'), 'comments.php' => __('Comments'), 'comments-popup.php' => __('Popup Comments'), 'footer.php' => __('Footer'), 'header.php' => __('Header'), 'sidebar.php' => __('Sidebar'), 'archive.php' => __('Archives'), 'category.php' => __('Category Template'), 'page.php' => __('Page Template'), 'search.php' => __('Search Results'), 'single.php' => __('Single Post'), '404.php' => __('404 Template'), 'my-hacks.php' => __('my-hacks.php (legacy hacks support)'), '.htaccess' => __('.htaccess (for rewrite rules)'),
1509         // Deprecated files
1510         'wp-layout.css' => __('Stylesheet'), 'wp-comments.php' => __('Comments Template'), 'wp-comments-popup.php' => __('Popup Comments Template'));
1511
1512 function get_file_description($file) {
1513         global $wp_file_descriptions;
1514
1515         if (isset ($wp_file_descriptions[basename($file)])) {
1516                 return $wp_file_descriptions[basename($file)];
1517         }
1518         elseif (file_exists(ABSPATH.$file)) {
1519                 $template_data = implode('', file(ABSPATH.$file));
1520                 if (preg_match("|Template Name:(.*)|i", $template_data, $name))
1521                         return $name[1];
1522         }
1523
1524         return basename($file);
1525 }
1526
1527 function update_recently_edited($file) {
1528         $oldfiles = (array) get_option('recently_edited');
1529         if ($oldfiles) {
1530                 $oldfiles = array_reverse($oldfiles);
1531                 $oldfiles[] = $file;
1532                 $oldfiles = array_reverse($oldfiles);
1533                 $oldfiles = array_unique($oldfiles);
1534                 if (5 < count($oldfiles))
1535                         array_pop($oldfiles);
1536         } else {
1537                 $oldfiles[] = $file;
1538         }
1539         update_option('recently_edited', $oldfiles);
1540 }
1541
1542 function get_plugin_data($plugin_file) {
1543         $plugin_data = implode('', file($plugin_file));
1544         preg_match("|Plugin Name:(.*)|i", $plugin_data, $plugin_name);
1545         preg_match("|Plugin URI:(.*)|i", $plugin_data, $plugin_uri);
1546         preg_match("|Description:(.*)|i", $plugin_data, $description);
1547         preg_match("|Author:(.*)|i", $plugin_data, $author_name);
1548         preg_match("|Author URI:(.*)|i", $plugin_data, $author_uri);
1549         if (preg_match("|Version:(.*)|i", $plugin_data, $version))
1550                 $version = trim($version[1]);
1551         else
1552                 $version = '';
1553
1554         $description = wptexturize(trim($description[1]));
1555
1556         $name = $plugin_name[1];
1557         $name = trim($name);
1558         $plugin = $name;
1559         if ('' != $plugin_uri[1] && '' != $name) {
1560                 $plugin = '<a href="' . trim($plugin_uri[1]) . '" title="'.__('Visit plugin homepage').'">'.$plugin.'</a>';
1561         }
1562
1563         if ('' == $author_uri[1]) {
1564                 $author = trim($author_name[1]);
1565         } else {
1566                 $author = '<a href="' . trim($author_uri[1]) . '" title="'.__('Visit author homepage').'">' . trim($author_name[1]) . '</a>';
1567         }
1568
1569         return array ('Name' => $name, 'Title' => $plugin, 'Description' => $description, 'Author' => $author, 'Version' => $version, 'Template' => $template[1]);
1570 }
1571
1572 function get_plugins() {
1573         global $wp_plugins;
1574
1575         if (isset ($wp_plugins)) {
1576                 return $wp_plugins;
1577         }
1578
1579         $wp_plugins = array ();
1580         $plugin_loc = 'wp-content/plugins';
1581         $plugin_root = ABSPATH.$plugin_loc;
1582
1583         // Files in wp-content/plugins directory
1584         $plugins_dir = @ dir($plugin_root);
1585         if ($plugins_dir) {
1586                 while (($file = $plugins_dir->read()) !== false) {
1587                         if (preg_match('|^\.+$|', $file))
1588                                 continue;
1589                         if (is_dir($plugin_root.'/'.$file)) {
1590                                 $plugins_subdir = @ dir($plugin_root.'/'.$file);
1591                                 if ($plugins_subdir) {
1592                                         while (($subfile = $plugins_subdir->read()) !== false) {
1593                                                 if (preg_match('|^\.+$|', $subfile))
1594                                                         continue;
1595                                                 if (preg_match('|\.php$|', $subfile))
1596                                                         $plugin_files[] = "$file/$subfile";
1597                                         }
1598                                 }
1599                         } else {
1600                                 if (preg_match('|\.php$|', $file))
1601                                         $plugin_files[] = $file;
1602                         }
1603                 }
1604         }
1605
1606         if ( !$plugins_dir || !$plugin_files )
1607                 return $wp_plugins;
1608
1609         foreach ( $plugin_files as $plugin_file ) {
1610                 if ( !is_readable("$plugin_root/$plugin_file"))
1611                         continue;
1612
1613                 $plugin_data = get_plugin_data("$plugin_root/$plugin_file");
1614
1615                 if ( empty ($plugin_data['Name']) )
1616                         continue;
1617
1618                 $wp_plugins[plugin_basename($plugin_file)] = $plugin_data;
1619         }
1620
1621         uasort($wp_plugins, create_function('$a, $b', 'return strnatcasecmp($a["Name"], $b["Name"]);'));
1622
1623         return $wp_plugins;
1624 }
1625
1626 function get_plugin_page_hookname($plugin_page, $parent_page) {
1627         global $admin_page_hooks;
1628
1629         $parent = get_admin_page_parent();
1630
1631         if (empty ($parent_page) || 'admin.php' == $parent_page) {
1632                 if (isset ($admin_page_hooks[$plugin_page]))
1633                         $page_type = 'toplevel';
1634                 else
1635                         if (isset ($admin_page_hooks[$parent]))
1636                                 $page_type = $admin_page_hooks[$parent];
1637         } else
1638                 if (isset ($admin_page_hooks[$parent_page])) {
1639                         $page_type = $admin_page_hooks[$parent_page];
1640                 } else {
1641                         $page_type = 'admin';
1642                 }
1643
1644         $plugin_name = preg_replace('!\.php!', '', $plugin_page);
1645
1646         return $page_type.'_page_'.$plugin_name;
1647 }
1648
1649 function get_plugin_page_hook($plugin_page, $parent_page) {
1650         global $wp_filter;
1651
1652         $hook = get_plugin_page_hookname($plugin_page, $parent_page);
1653         if (isset ($wp_filter[$hook]))
1654                 return $hook;
1655         else
1656                 return '';
1657 }
1658
1659 function browse_happy() {
1660         $getit = __('WordPress recommends a better browser');
1661         echo '
1662                 <p id="bh" style="text-align: center;"><a href="http://browsehappy.com/" title="'.$getit.'"><img src="images/browse-happy.gif" alt="Browse Happy" /></a></p>
1663                 ';
1664 }
1665 if (strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE'))
1666         add_action('admin_footer', 'browse_happy');
1667
1668 function documentation_link($for) {
1669         return;
1670 }
1671
1672 function register_importer($id, $name, $description, $callback) {
1673         global $wp_importers;
1674
1675         $wp_importers[$id] = array ($name, $description, $callback);
1676 }
1677
1678 function get_importers() {
1679         global $wp_importers;
1680
1681         return $wp_importers;
1682 }
1683
1684 function current_theme_info() {
1685         $themes = get_themes();
1686         $current_theme = get_current_theme();
1687         $ct->name = $current_theme;
1688         $ct->title = $themes[$current_theme]['Title'];
1689         $ct->version = $themes[$current_theme]['Version'];
1690         $ct->parent_theme = $themes[$current_theme]['Parent Theme'];
1691         $ct->template_dir = $themes[$current_theme]['Template Dir'];
1692         $ct->stylesheet_dir = $themes[$current_theme]['Stylesheet Dir'];
1693         $ct->template = $themes[$current_theme]['Template'];
1694         $ct->stylesheet = $themes[$current_theme]['Stylesheet'];
1695         $ct->screenshot = $themes[$current_theme]['Screenshot'];
1696         $ct->description = $themes[$current_theme]['Description'];
1697         $ct->author = $themes[$current_theme]['Author'];
1698         return $ct;
1699 }
1700
1701
1702 // array wp_handle_upload ( array &file [, array overrides] )
1703 // file: reference to a single element of $_FILES. Call the function once for each uploaded file.
1704 // overrides: an associative array of names=>values to override default variables with extract($overrides, EXTR_OVERWRITE).
1705 // On success, returns an associative array of file attributes.
1706 // On failure, returns $overrides['upload_error_handler'](&$file, $message) or array('error'=>$message).
1707 function wp_handle_upload(&$file, $overrides = false) {
1708         // The default error handler.
1709         if (! function_exists('wp_handle_upload_error') ) {
1710                 function wp_handle_upload_error(&$file, $message) {
1711                         return array('error'=>$message);
1712                 }
1713         }
1714
1715         // You may define your own function and pass the name in $overrides['upload_error_handler']
1716         $upload_error_handler = 'wp_handle_upload_error';
1717
1718         // $_POST['action'] must be set and its value must equal $overrides['action'] or this:
1719         $action = 'wp_handle_upload';
1720
1721         // Courtesy of php.net, the strings that describe the error indicated in $_FILES[{form field}]['error'].
1722         $upload_error_strings = array(false,
1723                 __("The uploaded file exceeds the <code>upload_max_filesize</code> directive in <code>php.ini</code>."),
1724                 __("The uploaded file exceeds the <em>MAX_FILE_SIZE</em> directive that was specified in the HTML form."),
1725                 __("The uploaded file was only partially uploaded."),
1726                 __("No file was uploaded."),
1727                 __("Missing a temporary folder."),
1728                 __("Failed to write file to disk."));
1729
1730         // All tests are on by default. Most can be turned off by $override[{test_name}] = false;
1731         $test_form = true;
1732         $test_size = true;
1733
1734         // If you override this, you must provide $ext and $type!!!!
1735         $test_type = true;
1736
1737         // Install user overrides. Did we mention that this voids your warranty?
1738         if ( is_array($overrides) )
1739                 extract($overrides, EXTR_OVERWRITE);
1740
1741         // A correct form post will pass this test.
1742         if ( $test_form && (!isset($_POST['action']) || ($_POST['action'] != $action)) )
1743                 return $upload_error_handler($file, __('Invalid form submission.'));
1744
1745         // A successful upload will pass this test. It makes no sense to override this one.
1746         if ( $file['error'] > 0 )
1747                 return $upload_error_handler($file, $upload_error_strings[$file['error']]);
1748
1749         // A non-empty file will pass this test.
1750         if ( $test_size && !($file['size'] > 0) )
1751                 return $upload_error_handler($file, __('File is empty. Please upload something more substantial.'));
1752
1753         // A properly uploaded file will pass this test. There should be no reason to override this one.
1754         if (! @ is_uploaded_file($file['tmp_name']) )
1755                 return $upload_error_handler($file, __('Specified file failed upload test.'));
1756
1757         // A correct MIME type will pass this test. Override $mimes or use the upload_mimes filter.
1758         if ( $test_type ) {
1759                 $wp_filetype = wp_check_filetype($file['name'], $mimes);
1760
1761                 extract($wp_filetype);
1762
1763                 if ( !$type || !$ext )
1764                         return $upload_error_handler($file, __('File type does not meet security guidelines. Try another.'));
1765         }
1766
1767         // A writable uploads dir will pass this test. Again, there's no point overriding this one.
1768         if ( ! ( ( $uploads = wp_upload_dir() ) && false === $uploads['error'] ) )
1769                 return $upload_error_handler($file, $uploads['error']);
1770
1771         // Increment the file number until we have a unique file to save in $dir. Use $override['unique_filename_callback'] if supplied.
1772         if ( isset($unique_filename_callback) && function_exists($unique_filename_callback) ) {
1773                 $filename = $unique_filename_callback($uploads['path'], $file['name']);
1774         } else {
1775                 $number = '';
1776                 $filename = str_replace('#', '_', $file['name']);
1777                 $filename = str_replace(array('\\', "'"), '', $filename);
1778                 if ( empty($ext) )
1779                         $ext = '';
1780                 else
1781                         $ext = ".$ext";
1782                 while ( file_exists($uploads['path'] . "/$filename") ) {
1783                         if ( '' == "$number$ext" )
1784                                 $filename = $filename . ++$number . $ext;
1785                         else
1786                                 $filename = str_replace("$number$ext", ++$number . $ext, $filename);
1787                 }
1788                 $filename = str_replace($ext, '', $filename);
1789                 $filename = sanitize_title_with_dashes($filename) . $ext;
1790         }
1791
1792         // Move the file to the uploads dir
1793         $new_file = $uploads['path'] . "/$filename";
1794         if ( false === @ move_uploaded_file($file['tmp_name'], $new_file) )
1795                 die(printf(__('The uploaded file could not be moved to %s.'), $file['path']));
1796
1797         // Set correct file permissions
1798         $stat = stat(dirname($new_file));
1799         $perms = $stat['mode'] & 0000666;
1800         @ chmod($new_file, $perms);
1801
1802         // Compute the URL
1803         $url = $uploads['url'] . "/$filename";
1804
1805         return array('file' => $new_file, 'url' => $url, 'type' => $type);
1806 }
1807
1808 function wp_shrink_dimensions($width, $height, $wmax = 128, $hmax = 96) {
1809         if ( $height <= $hmax && $width <= $wmax )
1810                 return array($width, $height);
1811         elseif ( $width / $height > $wmax / $hmax )
1812                 return array($wmax, (int) ($height / $width * $wmax));
1813         else
1814                 return array((int) ($width / $height * $hmax), $hmax);
1815 }
1816
1817 function wp_import_cleanup($id) {
1818         wp_delete_attachment($id);
1819 }
1820
1821 function wp_import_upload_form($action) {
1822 ?>
1823 <script type="text/javascript">
1824 function cancelUpload() {
1825 o = document.getElementById('uploadForm');
1826 o.method = 'GET';
1827 o.action.value = 'view';
1828 o.submit();
1829 }
1830 </script>
1831 <form enctype="multipart/form-data" id="uploadForm" method="post" action="<?php echo attribute_escape($action) ?>">
1832 <?php wp_nonce_field('import-upload'); ?>
1833 <label for="upload"><?php _e('File:'); ?></label><input type="file" id="upload" name="import" />
1834 <input type="hidden" name="action" value="save" />
1835 <div id="buttons">
1836 <input type="submit" value="<?php _e('Import'); ?>" />
1837 <input type="button" value="<?php _e('Cancel'); ?>" onclick="cancelUpload()" />
1838 </div>
1839 </form>
1840 <?php   
1841 }
1842
1843 function wp_import_handle_upload() {
1844         $overrides = array('test_form' => false, 'test_type' => false);
1845         $file = wp_handle_upload($_FILES['import'], $overrides);
1846
1847         if ( isset($file['error']) )
1848                 return $file;
1849
1850         $url = $file['url'];
1851         $file = $file['file'];
1852         $filename = basename($file);
1853
1854         // Construct the object array
1855         $object = array(
1856                 'post_title' => $filename,
1857                 'post_content' => $url,
1858                 'post_mime_type' => 'import',
1859                 'guid' => $url
1860         );
1861
1862         // Save the data
1863         $id = wp_insert_attachment($object, $file);
1864
1865         return array('file' => $file, 'id' => $id);
1866 }
1867
1868 function user_can_richedit() {
1869         if ( 'true' != get_user_option('rich_editing') )
1870                 return false;
1871
1872         if ( preg_match('!opera[ /][2-8]|konqueror|safari!i', $_SERVER['HTTP_USER_AGENT']) )
1873                 return false;
1874
1875         return true; // Best guess
1876 }
1877
1878 function the_attachment_links($id = false) {
1879         $id = (int) $id;
1880         $post = & get_post($id);
1881
1882         if ( $post->post_status != 'attachment' )
1883                 return false;
1884
1885         $icon = get_attachment_icon($post->ID);
1886
1887 ?>
1888 <p><?php _e('Text linked to file') ?><br />
1889 <textarea rows="1" cols="40" type="text" class="attachmentlinks" readonly="readonly"><a href="<?php echo $post->guid ?>" class="attachmentlink"><?php echo basename($post->guid) ?></a></textarea></p>
1890 <p><?php _e('Text linked to subpost') ?><br />
1891 <textarea rows="1" cols="40" type="text" class="attachmentlinks" readonly="readonly"><a href="<?php echo get_attachment_link($post->ID) ?>" rel="attachment" id="<?php echo $post->ID ?>"><?php echo $post->post_title ?></a></textarea></p>
1892 <?php if ( $icon ) : ?>
1893 <p><?php _e('Thumbnail linked to file') ?><br />
1894 <textarea rows="1" cols="40" type="text" class="attachmentlinks" readonly="readonly"><a href="<?php echo $post->guid ?>" class="attachmentlink"><?php echo $icon ?></a></textarea></p>
1895 <p><?php _e('Thumbnail linked to subpost') ?><br />
1896 <textarea rows="1" cols="40" type="text" class="attachmentlinks" readonly="readonly"><a href="<?php echo get_attachment_link($post->ID) ?>" rel="attachment" id="<?php echo $post->ID ?>"><?php echo $icon ?></a></textarea></p>
1897 <?php endif; ?>
1898 <?php
1899 }
1900
1901 function get_udims($width, $height) {
1902         if ( $height <= 96 && $width <= 128 )
1903                 return array($width, $height);
1904         elseif ( $width / $height > 4 / 3 )
1905                 return array(128, (int) ($height / $width * 128));
1906         else
1907                 return array((int) ($width / $height * 96), 96);
1908 }
1909
1910 ?>