[ Index ]

WordPress Source Cross Reference

title

Body

[close]

/wp-admin/ -> admin-functions.php (source)

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

Your comment here...

Name: Location:
Comments:


List: Classes | Functions | Variables | Constants | Tables

Generated: Sat Jul 15 11:57:04 2006 Courtesy of Taragana