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