]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-admin/admin-functions.php
Wordpress 2.0.11-scripts
[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                 chmod($filename, 0777);
1052                 $foundit = false;
1053                 if ($markerdata) {
1054                         $state = true;
1055                         foreach ($markerdata as $markerline) {
1056                                 if (strstr($markerline, "# BEGIN {$marker}"))
1057                                         $state = false;
1058                                 if ($state)
1059                                         fwrite($f, "{$markerline}\n");
1060                                 if (strstr($markerline, "# END {$marker}")) {
1061                                         fwrite($f, "# BEGIN {$marker}\n");
1062                                         if (is_array($insertion))
1063                                                 foreach ($insertion as $insertline)
1064                                                         fwrite($f, "{$insertline}\n");
1065                                         fwrite($f, "# END {$marker}\n");
1066                                         $state = true;
1067                                         $foundit = true;
1068                                 }
1069                         }
1070                 }
1071                 if (!$foundit) {
1072                         fwrite($f, "# BEGIN {$marker}\n");
1073                         foreach ($insertion as $insertline)
1074                                 fwrite($f, "{$insertline}\n");
1075                         fwrite($f, "# END {$marker}\n");
1076                 }
1077                 fclose($f);
1078                 return true;
1079         } else {
1080                 return false;
1081         }
1082 }
1083
1084 // extract_from_markers: Owen Winkler
1085 // Returns an array of strings from a file (.htaccess) from between BEGIN
1086 // and END markers.
1087 function extract_from_markers($filename, $marker) {
1088         $result = array ();
1089
1090         if (!file_exists($filename)) {
1091                 return $result;
1092         }
1093
1094         if ($markerdata = explode("\n", implode('', file($filename))));
1095         {
1096                 $state = false;
1097                 foreach ($markerdata as $markerline) {
1098                         if (strstr($markerline, "# END {$marker}"))
1099                                 $state = false;
1100                         if ($state)
1101                                 $result[] = $markerline;
1102                         if (strstr($markerline, "# BEGIN {$marker}"))
1103                                 $state = true;
1104                 }
1105         }
1106
1107         return $result;
1108 }
1109
1110 function got_mod_rewrite() {
1111         global $is_apache;
1112
1113         // take 3 educated guesses as to whether or not mod_rewrite is available
1114         if ( !$is_apache )
1115                 return false;
1116
1117         if ( function_exists('apache_get_modules') ) {
1118                 if ( !in_array('mod_rewrite', apache_get_modules()) )
1119                         return false;
1120         }
1121
1122         return true;
1123 }
1124
1125 function save_mod_rewrite_rules() {
1126         global $is_apache, $wp_rewrite;
1127         $home_path = get_home_path();
1128
1129         if (!$wp_rewrite->using_mod_rewrite_permalinks())
1130                 return;
1131
1132         if (!((!file_exists($home_path.'.htaccess') && is_writable($home_path)) || is_writable($home_path.'.htaccess')))
1133                 return;
1134
1135         if (! got_mod_rewrite())
1136                 return;
1137
1138         $rules = explode("\n", $wp_rewrite->mod_rewrite_rules());
1139         insert_with_markers($home_path.'.htaccess', 'WordPress', $rules);
1140 }
1141
1142 function the_quicktags() {
1143                 echo '
1144                 <div id="quicktags">
1145                         <script src="../wp-includes/js/quicktags.js" type="text/javascript"></script>
1146                         <script type="text/javascript">if ( typeof tinyMCE == "undefined" || tinyMCE.configs.length < 1 ) edToolbar();</script>
1147                 </div>
1148 ';
1149         echo '
1150 <script type="text/javascript">
1151 function edInsertContent(myField, myValue) {
1152         //IE support
1153         if (document.selection) {
1154                 myField.focus();
1155                 sel = document.selection.createRange();
1156                 sel.text = myValue;
1157                 myField.focus();
1158         }
1159         //MOZILLA/NETSCAPE support
1160         else if (myField.selectionStart || myField.selectionStart == "0") {
1161                 var startPos = myField.selectionStart;
1162                 var endPos = myField.selectionEnd;
1163                 myField.value = myField.value.substring(0, startPos)
1164                               + myValue 
1165                       + myField.value.substring(endPos, myField.value.length);
1166                 myField.focus();
1167                 myField.selectionStart = startPos + myValue.length;
1168                 myField.selectionEnd = startPos + myValue.length;
1169         } else {
1170                 myField.value += myValue;
1171                 myField.focus();
1172         }
1173 }
1174 </script>
1175 ';
1176 }
1177
1178 function validate_current_theme() {
1179         $theme_loc = 'wp-content/themes';
1180         $theme_root = ABSPATH.$theme_loc;
1181
1182         $template = get_settings('template');
1183         $stylesheet = get_settings('stylesheet');
1184
1185         if (($template != 'default') && (!file_exists("$theme_root/$template/index.php"))) {
1186                 update_option('template', 'default');
1187                 update_option('stylesheet', 'default');
1188                 do_action('switch_theme', 'Default');
1189                 return false;
1190         }
1191
1192         if (($stylesheet != 'default') && (!file_exists("$theme_root/$stylesheet/style.css"))) {
1193                 update_option('template', 'default');
1194                 update_option('stylesheet', 'default');
1195                 do_action('switch_theme', 'Default');
1196                 return false;
1197         }
1198
1199         return true;
1200 }
1201
1202 function get_broken_themes() {
1203         global $wp_broken_themes;
1204
1205         get_themes();
1206         return $wp_broken_themes;
1207 }
1208
1209 function get_page_templates() {
1210         $themes = get_themes();
1211         $theme = get_current_theme();
1212         $templates = $themes[$theme]['Template Files'];
1213         $page_templates = array ();
1214
1215         if (is_array($templates)) {
1216                 foreach ($templates as $template) {
1217                         $template_data = implode('', file(ABSPATH.$template));
1218                         preg_match("|Template Name:(.*)|i", $template_data, $name);
1219                         preg_match("|Description:(.*)|i", $template_data, $description);
1220
1221                         $name = $name[1];
1222                         $description = $description[1];
1223
1224                         if (!empty ($name)) {
1225                                 $page_templates[trim($name)] = basename($template);
1226                         }
1227                 }
1228         }
1229
1230         return $page_templates;
1231 }
1232
1233 function page_template_dropdown($default = '') {
1234         $templates = get_page_templates();
1235         foreach (array_keys($templates) as $template)
1236                 : if ($default == $templates[$template])
1237                         $selected = " selected='selected'";
1238                 else
1239                         $selected = '';
1240         echo "\n\t<option value='".$templates[$template]."' $selected>$template</option>";
1241         endforeach;
1242 }
1243
1244 function parent_dropdown($default = 0, $parent = 0, $level = 0) {
1245         global $wpdb, $post_ID;
1246         $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");
1247
1248         if ($items) {
1249                 foreach ($items as $item) {
1250                         // A page cannot be it's own parent.
1251                         if (!empty ($post_ID)) {
1252                                 if ($item->ID == $post_ID) {
1253                                         continue;
1254                                 }
1255                         }
1256                         $pad = str_repeat('&nbsp;', $level * 3);
1257                         if ($item->ID == $default)
1258                                 $current = ' selected="selected"';
1259                         else
1260                                 $current = '';
1261
1262                         echo "\n\t<option value='$item->ID'$current>$pad $item->post_title</option>";
1263                         parent_dropdown($default, $item->ID, $level +1);
1264                 }
1265         } else {
1266                 return false;
1267         }
1268 }
1269
1270 function user_can_access_admin_page() {
1271         global $pagenow;
1272         global $menu;
1273         global $submenu;
1274         global $plugin_page;
1275
1276         $parent = get_admin_page_parent();
1277
1278         foreach ($menu as $menu_array) {
1279                 //echo "parent array: " . $menu_array[2];
1280                 if ($menu_array[2] == $parent) {
1281                         if (!current_user_can($menu_array[1])) {
1282                                 return false;
1283                         } else {
1284                                 break;
1285                         }
1286                 }
1287         }
1288
1289         if (isset ($submenu[$parent])) {
1290                 if ( isset($plugin_page) ) {
1291                         foreach ($submenu[$parent] as $submenu_array) {
1292                                 if ( $submenu_array[2] == $plugin_page ) {
1293                                         if (!current_user_can($submenu_array[1]))
1294                                                 return false;
1295                                 }
1296                         }
1297                 }
1298
1299                 foreach ($submenu[$parent] as $submenu_array) {         
1300                         if ($submenu_array[2] == $pagenow) {
1301                                 if (!current_user_can($submenu_array[1]))
1302                                         return false;
1303                                 else
1304                                         return true;
1305                         }
1306                 }
1307         }
1308
1309         return true;
1310 }
1311
1312 function get_admin_page_title() {
1313         global $title;
1314         global $menu;
1315         global $submenu;
1316         global $pagenow;
1317         global $plugin_page;
1318
1319         if (isset ($title) && !empty ($title)) {
1320                 return $title;
1321         }
1322
1323         $hook = get_plugin_page_hook($plugin_page, $pagenow);
1324
1325         $parent = $parent1 = get_admin_page_parent();
1326         if (empty ($parent)) {
1327                 foreach ($menu as $menu_array) {
1328                         if (isset ($menu_array[3])) {
1329                                 if ($menu_array[2] == $pagenow) {
1330                                         $title = $menu_array[3];
1331                                         return $menu_array[3];
1332                                 } else
1333                                         if (isset ($plugin_page) && ($plugin_page == $menu_array[2]) && ($hook == $menu_array[3])) {
1334                                                 $title = $menu_array[3];
1335                                                 return $menu_array[3];
1336                                         }
1337                         }
1338                 }
1339         } else {
1340                 foreach (array_keys($submenu) as $parent) {
1341                         foreach ($submenu[$parent] as $submenu_array) {
1342                                 if (isset ($submenu_array[3])) {
1343                                         if ($submenu_array[2] == $pagenow) {
1344                                                 $title = $submenu_array[3];
1345                                                 return $submenu_array[3];
1346                                         } else
1347                                                 if (isset ($plugin_page) && ($plugin_page == $submenu_array[2]) && (($parent == $pagenow) || ($parent == $plugin_page) || ($plugin_page == $hook) || (($pagenow == 'admin.php') && ($parent1 != $submenu_array[2])))) {
1348                                                         $title = $submenu_array[3];
1349                                                         return $submenu_array[3];
1350                                                 }
1351                                 }
1352                         }
1353                 }
1354         }
1355
1356         return '';
1357 }
1358
1359 function get_admin_page_parent() {
1360         global $parent_file;
1361         global $menu;
1362         global $submenu;
1363         global $pagenow;
1364         global $plugin_page;
1365
1366         if (isset ($parent_file) && !empty ($parent_file)) {
1367                 return $parent_file;
1368         }
1369
1370         if ($pagenow == 'admin.php' && isset ($plugin_page)) {
1371                 foreach ($menu as $parent_menu) {
1372                         if ($parent_menu[2] == $plugin_page) {
1373                                 $parent_file = $plugin_page;
1374                                 return $plugin_page;
1375                         }
1376                 }
1377         }
1378
1379         foreach (array_keys($submenu) as $parent) {
1380                 foreach ($submenu[$parent] as $submenu_array) {
1381                         if ($submenu_array[2] == $pagenow) {
1382                                 $parent_file = $parent;
1383                                 return $parent;
1384                         } else
1385                                 if (isset ($plugin_page) && ($plugin_page == $submenu_array[2])) {
1386                                         $parent_file = $parent;
1387                                         return $parent;
1388                                 }
1389                 }
1390         }
1391
1392         $parent_file = '';
1393         return '';
1394 }
1395
1396 function add_menu_page($page_title, $menu_title, $access_level, $file, $function = '') {
1397         global $menu, $admin_page_hooks;
1398
1399         $file = plugin_basename($file);
1400
1401         $menu[] = array ($menu_title, $access_level, $file, $page_title);
1402
1403         $admin_page_hooks[$file] = sanitize_title($menu_title);
1404
1405         $hookname = get_plugin_page_hookname($file, '');
1406         if (!empty ($function) && !empty ($hookname))
1407                 add_action($hookname, $function);
1408
1409         return $hookname;
1410 }
1411
1412 function add_submenu_page($parent, $page_title, $menu_title, $access_level, $file, $function = '') {
1413         global $submenu;
1414         global $menu;
1415
1416         $parent = plugin_basename($parent);
1417         $file = plugin_basename($file);
1418
1419         // If the parent doesn't already have a submenu, add a link to the parent
1420         // as the first item in the submenu.  If the submenu file is the same as the
1421         // parent file someone is trying to link back to the parent manually.  In
1422         // this case, don't automatically add a link back to avoid duplication.
1423         if (!isset ($submenu[$parent]) && $file != $parent) {
1424                 foreach ($menu as $parent_menu) {
1425                         if ($parent_menu[2] == $parent) {
1426                                 $submenu[$parent][] = $parent_menu;
1427                         }
1428                 }
1429         }
1430
1431         $submenu[$parent][] = array ($menu_title, $access_level, $file, $page_title);
1432
1433         $hookname = get_plugin_page_hookname($file, $parent);
1434         if (!empty ($function) && !empty ($hookname))
1435                 add_action($hookname, $function);
1436
1437         return $hookname;
1438 }
1439
1440 function add_options_page($page_title, $menu_title, $access_level, $file, $function = '') {
1441         return add_submenu_page('options-general.php', $page_title, $menu_title, $access_level, $file, $function);
1442 }
1443
1444 function add_management_page($page_title, $menu_title, $access_level, $file, $function = '') {
1445         return add_submenu_page('edit.php', $page_title, $menu_title, $access_level, $file, $function);
1446 }
1447
1448 function add_theme_page($page_title, $menu_title, $access_level, $file, $function = '') {
1449         return add_submenu_page('themes.php', $page_title, $menu_title, $access_level, $file, $function);
1450 }
1451
1452 function validate_file($file, $allowed_files = '') {
1453         if (false !== strpos($file, './'))
1454                 return 1;
1455
1456         if (':' == substr($file, 1, 1))
1457                 return 2;
1458
1459         if (!empty ($allowed_files) && (!in_array($file, $allowed_files)))
1460                 return 3;
1461
1462         return 0;
1463 }
1464
1465 function validate_file_to_edit($file, $allowed_files = '') {
1466         $file = stripslashes($file);
1467
1468         $code = validate_file($file, $allowed_files);
1469
1470         if (!$code)
1471                 return $file;
1472
1473         switch ($code) {
1474                 case 1 :
1475                         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.'));
1476
1477                 case 2 :
1478                         die(__('Sorry, can&#8217;t call files with their real path.'));
1479
1480                 case 3 :
1481                         die(__('Sorry, that file cannot be edited.'));
1482         }
1483 }
1484
1485 function get_home_path() {
1486         $home = get_settings('home');
1487         if ($home != '' && $home != get_settings('siteurl')) {
1488                 $home_path = parse_url($home);
1489                 $home_path = $home_path['path'];
1490                 $root = str_replace($_SERVER["PHP_SELF"], '', $_SERVER["SCRIPT_FILENAME"]);
1491                 $home_path = trailingslashit($root.$home_path);
1492         } else {
1493                 $home_path = ABSPATH;
1494         }
1495
1496         return $home_path;
1497 }
1498
1499 function get_real_file_to_edit($file) {
1500         if ('index.php' == $file || '.htaccess' == $file) {
1501                 $real_file = get_home_path().$file;
1502         } else {
1503                 $real_file = ABSPATH.$file;
1504         }
1505
1506         return $real_file;
1507 }
1508
1509 $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)'),
1510         // Deprecated files
1511         'wp-layout.css' => __('Stylesheet'), 'wp-comments.php' => __('Comments Template'), 'wp-comments-popup.php' => __('Popup Comments Template'));
1512
1513 function get_file_description($file) {
1514         global $wp_file_descriptions;
1515
1516         if (isset ($wp_file_descriptions[basename($file)])) {
1517                 return $wp_file_descriptions[basename($file)];
1518         }
1519         elseif (file_exists(ABSPATH.$file)) {
1520                 $template_data = implode('', file(ABSPATH.$file));
1521                 if (preg_match("|Template Name:(.*)|i", $template_data, $name))
1522                         return $name[1];
1523         }
1524
1525         return basename($file);
1526 }
1527
1528 function update_recently_edited($file) {
1529         $oldfiles = (array) get_option('recently_edited');
1530         if ($oldfiles) {
1531                 $oldfiles = array_reverse($oldfiles);
1532                 $oldfiles[] = $file;
1533                 $oldfiles = array_reverse($oldfiles);
1534                 $oldfiles = array_unique($oldfiles);
1535                 if (5 < count($oldfiles))
1536                         array_pop($oldfiles);
1537         } else {
1538                 $oldfiles[] = $file;
1539         }
1540         update_option('recently_edited', $oldfiles);
1541 }
1542
1543 function get_plugin_data($plugin_file) {
1544         $plugin_data = implode('', file($plugin_file));
1545         preg_match("|Plugin Name:(.*)|i", $plugin_data, $plugin_name);
1546         preg_match("|Plugin URI:(.*)|i", $plugin_data, $plugin_uri);
1547         preg_match("|Description:(.*)|i", $plugin_data, $description);
1548         preg_match("|Author:(.*)|i", $plugin_data, $author_name);
1549         preg_match("|Author URI:(.*)|i", $plugin_data, $author_uri);
1550         if (preg_match("|Version:(.*)|i", $plugin_data, $version))
1551                 $version = trim($version[1]);
1552         else
1553                 $version = '';
1554
1555         $description = wptexturize(trim($description[1]));
1556
1557         $name = $plugin_name[1];
1558         $name = trim($name);
1559         $plugin = $name;
1560         if ('' != $plugin_uri[1] && '' != $name) {
1561                 $plugin = '<a href="' . trim($plugin_uri[1]) . '" title="'.__('Visit plugin homepage').'">'.$plugin.'</a>';
1562         }
1563
1564         if ('' == $author_uri[1]) {
1565                 $author = trim($author_name[1]);
1566         } else {
1567                 $author = '<a href="' . trim($author_uri[1]) . '" title="'.__('Visit author homepage').'">' . trim($author_name[1]) . '</a>';
1568         }
1569
1570         return array ('Name' => $name, 'Title' => $plugin, 'Description' => $description, 'Author' => $author, 'Version' => $version, 'Template' => $template[1]);
1571 }
1572
1573 function get_plugins() {
1574         global $wp_plugins;
1575
1576         if (isset ($wp_plugins)) {
1577                 return $wp_plugins;
1578         }
1579
1580         $wp_plugins = array ();
1581         $plugin_loc = 'wp-content/plugins';
1582         $plugin_root = ABSPATH.$plugin_loc;
1583
1584         // Files in wp-content/plugins directory
1585         $plugins_dir = @ dir($plugin_root);
1586         if ($plugins_dir) {
1587                 while (($file = $plugins_dir->read()) !== false) {
1588                         if (preg_match('|^\.+$|', $file))
1589                                 continue;
1590                         if (is_dir($plugin_root.'/'.$file)) {
1591                                 $plugins_subdir = @ dir($plugin_root.'/'.$file);
1592                                 if ($plugins_subdir) {
1593                                         while (($subfile = $plugins_subdir->read()) !== false) {
1594                                                 if (preg_match('|^\.+$|', $subfile))
1595                                                         continue;
1596                                                 if (preg_match('|\.php$|', $subfile))
1597                                                         $plugin_files[] = "$file/$subfile";
1598                                         }
1599                                 }
1600                         } else {
1601                                 if (preg_match('|\.php$|', $file))
1602                                         $plugin_files[] = $file;
1603                         }
1604                 }
1605         }
1606
1607         if ( !$plugins_dir || !$plugin_files )
1608                 return $wp_plugins;
1609
1610         foreach ( $plugin_files as $plugin_file ) {
1611                 if ( !is_readable("$plugin_root/$plugin_file"))
1612                         continue;
1613
1614                 $plugin_data = get_plugin_data("$plugin_root/$plugin_file");
1615
1616                 if ( empty ($plugin_data['Name']) )
1617                         continue;
1618
1619                 $wp_plugins[plugin_basename($plugin_file)] = $plugin_data;
1620         }
1621
1622         uasort($wp_plugins, create_function('$a, $b', 'return strnatcasecmp($a["Name"], $b["Name"]);'));
1623
1624         return $wp_plugins;
1625 }
1626
1627 function get_plugin_page_hookname($plugin_page, $parent_page) {
1628         global $admin_page_hooks;
1629
1630         $parent = get_admin_page_parent();
1631
1632         if (empty ($parent_page) || 'admin.php' == $parent_page) {
1633                 if (isset ($admin_page_hooks[$plugin_page]))
1634                         $page_type = 'toplevel';
1635                 else
1636                         if (isset ($admin_page_hooks[$parent]))
1637                                 $page_type = $admin_page_hooks[$parent];
1638         } else
1639                 if (isset ($admin_page_hooks[$parent_page])) {
1640                         $page_type = $admin_page_hooks[$parent_page];
1641                 } else {
1642                         $page_type = 'admin';
1643                 }
1644
1645         $plugin_name = preg_replace('!\.php!', '', $plugin_page);
1646
1647         return $page_type.'_page_'.$plugin_name;
1648 }
1649
1650 function get_plugin_page_hook($plugin_page, $parent_page) {
1651         global $wp_filter;
1652
1653         $hook = get_plugin_page_hookname($plugin_page, $parent_page);
1654         if (isset ($wp_filter[$hook]))
1655                 return $hook;
1656         else
1657                 return '';
1658 }
1659
1660 function browse_happy() {
1661         $getit = __('WordPress recommends a better browser');
1662         echo '
1663                 <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>
1664                 ';
1665 }
1666 if (strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE'))
1667         add_action('admin_footer', 'browse_happy');
1668
1669 function documentation_link($for) {
1670         return;
1671 }
1672
1673 function register_importer($id, $name, $description, $callback) {
1674         global $wp_importers;
1675
1676         $wp_importers[$id] = array ($name, $description, $callback);
1677 }
1678
1679 function get_importers() {
1680         global $wp_importers;
1681
1682         return $wp_importers;
1683 }
1684
1685 function current_theme_info() {
1686         $themes = get_themes();
1687         $current_theme = get_current_theme();
1688         $ct->name = $current_theme;
1689         $ct->title = $themes[$current_theme]['Title'];
1690         $ct->version = $themes[$current_theme]['Version'];
1691         $ct->parent_theme = $themes[$current_theme]['Parent Theme'];
1692         $ct->template_dir = $themes[$current_theme]['Template Dir'];
1693         $ct->stylesheet_dir = $themes[$current_theme]['Stylesheet Dir'];
1694         $ct->template = $themes[$current_theme]['Template'];
1695         $ct->stylesheet = $themes[$current_theme]['Stylesheet'];
1696         $ct->screenshot = $themes[$current_theme]['Screenshot'];
1697         $ct->description = $themes[$current_theme]['Description'];
1698         $ct->author = $themes[$current_theme]['Author'];
1699         return $ct;
1700 }
1701
1702
1703 // array wp_handle_upload ( array &file [, array overrides] )
1704 // file: reference to a single element of $_FILES. Call the function once for each uploaded file.
1705 // overrides: an associative array of names=>values to override default variables with extract($overrides, EXTR_OVERWRITE).
1706 // On success, returns an associative array of file attributes.
1707 // On failure, returns $overrides['upload_error_handler'](&$file, $message) or array('error'=>$message).
1708 function wp_handle_upload(&$file, $overrides = false) {
1709         // The default error handler.
1710         if (! function_exists('wp_handle_upload_error') ) {
1711                 function wp_handle_upload_error(&$file, $message) {
1712                         return array('error'=>$message);
1713                 }
1714         }
1715
1716         // You may define your own function and pass the name in $overrides['upload_error_handler']
1717         $upload_error_handler = 'wp_handle_upload_error';
1718
1719         // $_POST['action'] must be set and its value must equal $overrides['action'] or this:
1720         $action = 'wp_handle_upload';
1721
1722         // Courtesy of php.net, the strings that describe the error indicated in $_FILES[{form field}]['error'].
1723         $upload_error_strings = array(false,
1724                 __("The uploaded file exceeds the <code>upload_max_filesize</code> directive in <code>php.ini</code>."),
1725                 __("The uploaded file exceeds the <em>MAX_FILE_SIZE</em> directive that was specified in the HTML form."),
1726                 __("The uploaded file was only partially uploaded."),
1727                 __("No file was uploaded."),
1728                 __("Missing a temporary folder."),
1729                 __("Failed to write file to disk."));
1730
1731         // All tests are on by default. Most can be turned off by $override[{test_name}] = false;
1732         $test_form = true;
1733         $test_size = true;
1734
1735         // If you override this, you must provide $ext and $type!!!!
1736         $test_type = true;
1737
1738         // Install user overrides. Did we mention that this voids your warranty?
1739         if ( is_array($overrides) )
1740                 extract($overrides, EXTR_OVERWRITE);
1741
1742         // A correct form post will pass this test.
1743         if ( $test_form && (!isset($_POST['action']) || ($_POST['action'] != $action)) )
1744                 return $upload_error_handler($file, __('Invalid form submission.'));
1745
1746         // A successful upload will pass this test. It makes no sense to override this one.
1747         if ( $file['error'] > 0 )
1748                 return $upload_error_handler($file, $upload_error_strings[$file['error']]);
1749
1750         // A non-empty file will pass this test.
1751         if ( $test_size && !($file['size'] > 0) )
1752                 return $upload_error_handler($file, __('File is empty. Please upload something more substantial.'));
1753
1754         // A properly uploaded file will pass this test. There should be no reason to override this one.
1755         if (! @ is_uploaded_file($file['tmp_name']) )
1756                 return $upload_error_handler($file, __('Specified file failed upload test.'));
1757
1758         // A correct MIME type will pass this test. Override $mimes or use the upload_mimes filter.
1759         if ( $test_type ) {
1760                 $wp_filetype = wp_check_filetype($file['name'], $mimes);
1761
1762                 extract($wp_filetype);
1763
1764                 if ( !$type || !$ext )
1765                         return $upload_error_handler($file, __('File type does not meet security guidelines. Try another.'));
1766         }
1767
1768         // A writable uploads dir will pass this test. Again, there's no point overriding this one.
1769         if ( ! ( ( $uploads = wp_upload_dir() ) && false === $uploads['error'] ) )
1770                 return $upload_error_handler($file, $uploads['error']);
1771
1772         // Increment the file number until we have a unique file to save in $dir. Use $override['unique_filename_callback'] if supplied.
1773         if ( isset($unique_filename_callback) && function_exists($unique_filename_callback) ) {
1774                 $filename = $unique_filename_callback($uploads['path'], $file['name']);
1775         } else {
1776                 $number = '';
1777                 $filename = str_replace('#', '_', $file['name']);
1778                 $filename = str_replace(array('\\', "'"), '', $filename);
1779                 if ( empty($ext) )
1780                         $ext = '';
1781                 else
1782                         $ext = ".$ext";
1783                 while ( file_exists($uploads['path'] . "/$filename") ) {
1784                         if ( '' == "$number$ext" )
1785                                 $filename = $filename . ++$number . $ext;
1786                         else
1787                                 $filename = str_replace("$number$ext", ++$number . $ext, $filename);
1788                 }
1789                 $filename = str_replace($ext, '', $filename);
1790                 $filename = sanitize_title_with_dashes($filename) . $ext;
1791         }
1792
1793         // Move the file to the uploads dir
1794         $new_file = $uploads['path'] . "/$filename";
1795         if ( false === @ move_uploaded_file($file['tmp_name'], $new_file) )
1796                 die(printf(__('The uploaded file could not be moved to %s.'), $file['path']));
1797
1798         // Set correct file permissions
1799         $stat = stat(dirname($new_file));
1800         $perms = $stat['mode'] & 0000666;
1801         @ chmod($new_file, $perms);
1802
1803         // Compute the URL
1804         $url = $uploads['url'] . "/$filename";
1805
1806         return array('file' => $new_file, 'url' => $url, 'type' => $type);
1807 }
1808
1809 function wp_shrink_dimensions($width, $height, $wmax = 128, $hmax = 96) {
1810         if ( $height <= $hmax && $width <= $wmax )
1811                 return array($width, $height);
1812         elseif ( $width / $height > $wmax / $hmax )
1813                 return array($wmax, (int) ($height / $width * $wmax));
1814         else
1815                 return array((int) ($width / $height * $hmax), $hmax);
1816 }
1817
1818 function wp_import_cleanup($id) {
1819         wp_delete_attachment($id);
1820 }
1821
1822 function wp_import_upload_form($action) {
1823 ?>
1824 <script type="text/javascript">
1825 function cancelUpload() {
1826 o = document.getElementById('uploadForm');
1827 o.method = 'GET';
1828 o.action.value = 'view';
1829 o.submit();
1830 }
1831 </script>
1832 <form enctype="multipart/form-data" id="uploadForm" method="post" action="<?php echo attribute_escape($action) ?>">
1833 <?php wp_nonce_field('import-upload'); ?>
1834 <label for="upload"><?php _e('File:'); ?></label><input type="file" id="upload" name="import" />
1835 <input type="hidden" name="action" value="save" />
1836 <div id="buttons">
1837 <input type="submit" value="<?php _e('Import'); ?>" />
1838 <input type="button" value="<?php _e('Cancel'); ?>" onclick="cancelUpload()" />
1839 </div>
1840 </form>
1841 <?php   
1842 }
1843
1844 function wp_import_handle_upload() {
1845         $overrides = array('test_form' => false, 'test_type' => false);
1846         $file = wp_handle_upload($_FILES['import'], $overrides);
1847
1848         if ( isset($file['error']) )
1849                 return $file;
1850
1851         $url = $file['url'];
1852         $file = $file['file'];
1853         $filename = basename($file);
1854
1855         // Construct the object array
1856         $object = array(
1857                 'post_title' => $filename,
1858                 'post_content' => $url,
1859                 'post_mime_type' => 'import',
1860                 'guid' => $url
1861         );
1862
1863         // Save the data
1864         $id = wp_insert_attachment($object, $file);
1865
1866         return array('file' => $file, 'id' => $id);
1867 }
1868
1869 function user_can_richedit() {
1870         if ( 'true' != get_user_option('rich_editing') )
1871                 return false;
1872
1873         if ( preg_match('!opera[ /][2-8]|konqueror|safari!i', $_SERVER['HTTP_USER_AGENT']) )
1874                 return false;
1875
1876         return true; // Best guess
1877 }
1878
1879 function the_attachment_links($id = false) {
1880         $id = (int) $id;
1881         $post = & get_post($id);
1882
1883         if ( $post->post_status != 'attachment' )
1884                 return false;
1885
1886         $icon = get_attachment_icon($post->ID);
1887
1888 ?>
1889 <p><?php _e('Text linked to file') ?><br />
1890 <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>
1891 <p><?php _e('Text linked to subpost') ?><br />
1892 <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>
1893 <?php if ( $icon ) : ?>
1894 <p><?php _e('Thumbnail linked to file') ?><br />
1895 <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>
1896 <p><?php _e('Thumbnail linked to subpost') ?><br />
1897 <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>
1898 <?php endif; ?>
1899 <?php
1900 }
1901
1902 function get_udims($width, $height) {
1903         if ( $height <= 96 && $width <= 128 )
1904                 return array($width, $height);
1905         elseif ( $width / $height > 4 / 3 )
1906                 return array(128, (int) ($height / $width * 128));
1907         else
1908                 return array((int) ($width / $height * 96), 96);
1909 }
1910
1911 ?>