[ Index ]
 

Code source de WordPress 2.1.2

Accédez au Source d'autres logiciels libresSoutenez Angelica Josefina !

title

Body

[fermer]

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

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


Généré le : Fri Mar 30 19:41:27 2007 par Balluche grâce à PHPXref 0.7