diff options
author | donncha <donncha@7be80a69-a1ef-0310-a953-fb0f7c49ff36> | 2006-06-13 11:18:16 +0000 |
---|---|---|
committer | donncha <donncha@7be80a69-a1ef-0310-a953-fb0f7c49ff36> | 2006-06-13 11:18:16 +0000 |
commit | 19b51f30bd324ecb36f99d159947b75c22b6fecf (patch) | |
tree | 9423e53c5fddbfca6e4cd05f43c4e1e11bc508b4 | |
parent | 242d432d82cefdf3aab7135b5298c2db02c9114c (diff) | |
download | wordpress-mu-19b51f30bd324ecb36f99d159947b75c22b6fecf.tar.gz wordpress-mu-19b51f30bd324ecb36f99d159947b75c22b6fecf.tar.xz wordpress-mu-19b51f30bd324ecb36f99d159947b75c22b6fecf.zip |
WP Merge
git-svn-id: http://svn.automattic.com/wordpress-mu/trunk@559 7be80a69-a1ef-0310-a953-fb0f7c49ff36
58 files changed, 7438 insertions, 2144 deletions
diff --git a/wp-inst/wp-admin/admin-ajax.php b/wp-inst/wp-admin/admin-ajax.php index 7f7db0b..088ce31 100644 --- a/wp-inst/wp-admin/admin-ajax.php +++ b/wp-inst/wp-admin/admin-ajax.php @@ -212,7 +212,7 @@ case 'update-meta' : case 'add-user' : if ( !current_user_can('edit_users') ) die('-1'); - require_once( ABSPATH . WPINC . '/registration-functions.php'); + require_once(ABSPATH . WPINC . '/registration.php'); $user_id = add_user(); if ( is_wp_error( $user_id ) ) { foreach( $user_id->get_error_messages() as $message ) diff --git a/wp-inst/wp-admin/admin-functions.php b/wp-inst/wp-admin/admin-functions.php index bf25871..866a3db 100644 --- a/wp-inst/wp-admin/admin-functions.php +++ b/wp-inst/wp-admin/admin-functions.php @@ -731,7 +731,7 @@ function user_row( $user_object, $style = '' ) { if ( !(is_object($user_object) && is_a($user_object, 'WP_User')) ) $user_object = new WP_User( (int) $user_object ); $email = $user_object->user_email; - if( $current_user->ID != $user_object->ID || is_site_admin() == false ) + if( $current_user->ID != $user_object->ID && is_site_admin() == false ) $email = "N/A"; $url = $user_object->user_url; $short_url = str_replace('http://', '', $url); @@ -748,10 +748,15 @@ function user_row( $user_object, $style = '' ) { <td><label for='user_{$user_object->ID}'>$user_object->first_name $user_object->last_name</label></td> <td><a href='mailto:$email' title='" . sprintf(__('e-mail: %s'), $email) . "'>$email</a></td> <td><a href='$url' title='website: $url'>$short_url</a></td>"; - $r .= "\n\t\t<td align='center'>$numposts</td>"; - $r .= "\n\t\t<td>"; + $r .= "\n\t\t<td align='center'>"; + if ($numposts > 0) { + $r .= "<a href='edit.php?author=$user_object->ID' title='" . __('View posts by this author') . "' class='edit'>"; + $r .= sprintf(__('View %1$s %2$s'), $numposts, __ngettext('post', 'posts', $numposts)); + } + $r .= "</td>\n\t\t<td>"; + $edit_link = add_query_arg('wp_http_referer', wp_specialchars(urlencode(stripslashes($_SERVER['REQUEST_URI']))), "user-edit.php?user_id=$user_object->ID"); if ( ( is_site_admin() || $current_user->ID == $user_object->ID ) && current_user_can('edit_user', $user_object->ID) ) - $r .= "<a href='user-edit.php?user_id=$user_object->ID' class='edit'>".__('Edit')."</a>"; + $r .= "<a href='$edit_link' class='edit'>".__('Edit')."</a>"; $r .= "</td>\n\t</tr>"; return $r; } @@ -1889,7 +1894,8 @@ function wp_handle_upload(&$file, $overrides = false) { else $filename = str_replace("$number$ext", ++$number . $ext, $filename); } - $filename = preg_replace('#\.(?![^.]+$)#', '-', $filename); + $filename = str_replace($ext, '', $filename); + $filename = sanitize_title($filename) . $ext; } // Move the file to the uploads dir diff --git a/wp-inst/wp-admin/admin.php b/wp-inst/wp-admin/admin.php index dda460b..9cd20c4 100644 --- a/wp-inst/wp-admin/admin.php +++ b/wp-inst/wp-admin/admin.php @@ -9,7 +9,7 @@ if ( get_option('db_version') != $wp_db_version ) require_once(ABSPATH . 'wp-admin/admin-functions.php'); require_once(ABSPATH . 'wp-admin/admin-db.php'); -require_once(ABSPATH . WPINC . '/registration-functions.php'); +require_once(ABSPATH . WPINC . '/registration.php'); auth_redirect(); diff --git a/wp-inst/wp-admin/edit-comments.js b/wp-inst/wp-admin/edit-comments.js index 2cd40af..4dfe755 100644 --- a/wp-inst/wp-admin/edit-comments.js +++ b/wp-inst/wp-admin/edit-comments.js @@ -21,4 +21,3 @@ addLoadEvent(function() { } }); - diff --git a/wp-inst/wp-admin/import/mt.php b/wp-inst/wp-admin/import/mt.php index 0bdfd6d..59259ea 100644 --- a/wp-inst/wp-admin/import/mt.php +++ b/wp-inst/wp-admin/import/mt.php @@ -50,25 +50,8 @@ class MT_Import { function checkauthor($author) { global $wpdb; //mtnames is an array with the names in the mt import file - $pass = 'changeme'; - if (!(in_array($author, $this->mtnames))) { //a new mt author name is found - ++ $this->j; - $this->mtnames[$this->j] = $author; //add that new mt author name to an array - $user_id = username_exists($this->newauthornames[$this->j]); //check if the new author name defined by the user is a pre-existing wp user - if (!$user_id) { //banging my head against the desk now. - if ($newauthornames[$this->j] == 'left_blank') { //check if the user does not want to change the authorname - $user_id = wp_create_user($author, $pass); - $this->newauthornames[$this->j] = $author; //now we have a name, in the place of left_blank. - } else { - $user_id = wp_create_user($this->newauthornames[$this->j], $pass); - } - } else { - return $user_id; // return pre-existing wp username if it exists - } - } else { - $key = array_search($author, $this->mtnames); //find the array key for $author in the $mtnames array - $user_id = username_exists($this->newauthornames[$key]); //use that key to get the value of the author's name from $newauthornames - } + $key = array_search($author, $this->mtnames); //find the array key for $author in the $mtnames array + $user_id = username_exists($this->newauthornames[$key]); //use that key to get the value of the author's name from $newauthornames return $user_id; } @@ -110,13 +93,6 @@ class MT_Import { $formnames = array (); $selectnames = array (); - foreach ($_POST['user'] as $key => $line) { - $newname = trim(stripslashes($line)); - if ($newname == '') - $newname = 'left_blank'; //passing author names from step 1 to step 2 is accomplished by using POST. left_blank denotes an empty entry in the form. - array_push($formnames, "$newname"); - } // $formnames is the array with the form entered names - foreach ($_POST['userselect'] as $user => $key) { $selected = trim(stripslashes($key)); array_push($selectnames, "$selected"); diff --git a/wp-inst/wp-admin/import/wordpress.php b/wp-inst/wp-admin/import/wordpress.php index 11c9f3e..997628b 100644 --- a/wp-inst/wp-admin/import/wordpress.php +++ b/wp-inst/wp-admin/import/wordpress.php @@ -37,7 +37,7 @@ class WP_Import { function users_form($n) {
global $wpdb, $testing;
- $users = $wpdb->get_results("SELECT * FROM $wpdb->users ORDER BY ID");
+ $users = get_users_of_blog($wpdb->blogid);
?><select name="userselect[<?php echo $n; ?>]">
<option value="#NONE#">- Select -</option>
<?php
@@ -54,24 +54,8 @@ class WP_Import { global $wpdb;
//mtnames is an array with the names in the mt import file
$pass = 'changeme';
- if (!(in_array($author, $this->mtnames))) { //a new mt author name is found
- ++ $this->j;
- $this->mtnames[$this->j] = $author; //add that new mt author name to an array
- $user_id = username_exists($this->newauthornames[$this->j]); //check if the new author name defined by the user is a pre-existing wp user
- if (!$user_id) { //banging my head against the desk now.
- if ($newauthornames[$this->j] == 'left_blank') { //check if the user does not want to change the authorname
- $user_id = wp_create_user($author, $pass);
- $this->newauthornames[$this->j] = $author; //now we have a name, in the place of left_blank.
- } else {
- $user_id = wp_create_user($this->newauthornames[$this->j], $pass);
- }
- } else {
- return $user_id; // return pre-existing wp username if it exists
- }
- } else {
- $key = array_search($author, $this->mtnames); //find the array key for $author in the $mtnames array
- $user_id = username_exists($this->newauthornames[$key]); //use that key to get the value of the author's name from $newauthornames
- }
+ $key = array_search($author, $this->mtnames); //find the array key for $author in the $mtnames array
+ $user_id = username_exists($this->newauthornames[$key]); //use that key to get the value of the author's name from $newauthornames
return $user_id;
}
@@ -112,13 +96,6 @@ class WP_Import { $formnames = array ();
$selectnames = array ();
- foreach ($_POST['user'] as $key => $line) {
- $newname = trim(stripslashes($line));
- if ($newname == '')
- $newname = 'left_blank'; //passing author names from step 1 to step 2 is accomplished by using POST. left_blank denotes an empty entry in the form.
- array_push($formnames, "$newname");
- } // $formnames is the array with the form entered names
-
foreach ($_POST['userselect'] as $user => $key) {
$selected = trim(stripslashes($key));
array_push($selectnames, "$selected");
@@ -148,7 +125,7 @@ class WP_Import { $j = -1;
foreach ($authors as $author) {
++ $j;
- echo '<li>Current author: <strong>'.$author.'</strong><br />'.'Create user <input type="text" value="'.$author.'" name="'.'user[]'.'" maxlength="30"> <br /> or map to existing ';
+ echo '<li>Current author: <strong>'.$author.'</strong><br />'.'Map to existing: ';
$this->users_form($j);
echo '</li>';
}
diff --git a/wp-inst/wp-admin/link-categories.php b/wp-inst/wp-admin/link-categories.php deleted file mode 100644 index 10fb227..0000000 --- a/wp-inst/wp-admin/link-categories.php +++ /dev/null @@ -1,455 +0,0 @@ -<?php -// Links -// Copyright (C) 2002, 2003 Mike Little -- mike@zed1.com -require_once('admin.php'); -$title = __('Link Categories'); -$this_file='link-categories.php'; -$parent_file = 'link-manager.php'; -$list_js = true; - -$wpvarstoreset = array('action', 'cat', 'auto_toggle'); -for ($i=0; $i<count($wpvarstoreset); $i += 1) { - $wpvar = $wpvarstoreset[$i]; - if (!isset($$wpvar)) { - if (empty($_POST["$wpvar"])) { - if (empty($_GET["$wpvar"])) { - $$wpvar = ''; - } else { - $$wpvar = $_GET["$wpvar"]; - } - } else { - $$wpvar = $_POST["$wpvar"]; - } - } -} - -switch ($action) { - case 'addcat': - { - if ( !current_user_can('manage_links') ) - die (__("Cheatin' uh ?")); - - $cat_name = wp_specialchars($_POST['cat_name']); - $auto_toggle = $_POST['auto_toggle']; - if ($auto_toggle != 'Y') { - $auto_toggle = 'N'; - } - - $show_images = $_POST['show_images']; - if ($show_images != 'Y') { - $show_images = 'N'; - } - - $show_description = $_POST['show_description']; - if ($show_description != 'Y') { - $show_description = 'N'; - } - - $show_rating = $_POST['show_rating']; - if ($show_rating != 'Y') { - $show_rating = 'N'; - } - - $show_updated = $_POST['show_updated']; - if ($show_updated != 'Y') { - $show_updated = 'N'; - } - - $sort_order = $_POST['sort_order']; - - $sort_desc = $_POST['sort_desc']; - if ($sort_desc != 'Y') { - $sort_desc = 'N'; - } - $text_before_link = $_POST['text_before_link']; - $text_after_link = $_POST['text_after_link']; - $text_after_all = $_POST['text_after_all']; - - $list_limit = $_POST['list_limit']; - if ($list_limit == '') - $list_limit = -1; - - $wpdb->query("INSERT INTO $wpdb->linkcategories (cat_id, cat_name, auto_toggle, show_images, show_description, \n" . - " show_rating, show_updated, sort_order, sort_desc, text_before_link, text_after_link, text_after_all, list_limit) \n" . - " VALUES ('0', '$cat_name', '$auto_toggle', '$show_images', '$show_description', \n" . - " '$show_rating', '$show_updated', '$sort_order', '$sort_desc', '$text_before_link', '$text_after_link', \n" . - " '$text_after_all', $list_limit)"); - - header('Location: link-categories.php'); - break; - } // end addcat - case 'Delete': - { - $cat_id = (int) $_GET['cat_id']; - $cat_name=get_linkcatname($cat_id); - - if ($cat_id=="1") - die(sprintf(__("Can't delete the <strong>%s</strong> link category: this is the default one"), $cat_name)); - - if ( !current_user_can('manage_links') ) - die (__("Cheatin' uh ?")); - - $wpdb->query("DELETE FROM $wpdb->linkcategories WHERE cat_id='$cat_id'"); - $wpdb->query("UPDATE $wpdb->links SET link_category=1 WHERE link_category='$cat_id'"); - - header('Location: link-categories.php'); - break; - } // end delete - case 'Edit': - { - include_once ('admin-header.php'); - $cat_id = (int) $_GET['cat_id']; - $row = $wpdb->get_row("SELECT cat_id, cat_name, auto_toggle, show_images, show_description, " - . " show_rating, show_updated, sort_order, sort_desc, text_before_link, text_after_link, " - . " text_after_all, list_limit FROM $wpdb->linkcategories WHERE cat_id=$cat_id"); - if ($row) { - if ($row->list_limit == -1) { - $row->list_limit = ''; - } -?> - -<div class="wrap"> - <h2><?php printf(__('Edit “%s” Category'), wp_specialchars($row->cat_name)); ?></h2> - - <form name="editcat" method="post"> - <input type="hidden" name="action" value="editedcat" /> - <input type="hidden" name="cat_id" value="<?php echo $row->cat_id ?>" /> -<fieldset class="options"> -<legend><?php _e('Category Options') ?></legend> -<table class="editform" width="100%" cellspacing="2" cellpadding="5"> -<tr> - <th width="33%" scope="row"><?php _e('Name:') ?></th> - <td width="67%"><input name="cat_name" type="text" value="<?php echo wp_specialchars($row->cat_name)?>" size="30" /></td> -</tr> -<tr> - <th scope="row"><?php _e('Show:') ?></th> - <td> - <label> - <input type="checkbox" name="show_images" value="Y" <?php checked('Y', $row->show_images); ?> /> - <?php _e('Image') ?></label> <br /> - <label> - <input type="checkbox" name="show_description" value="Y" <?php checked('Y', $row->show_description); ?> /> - <?php _e('Description') ?></label> - <?php _e('(shown in <code>title</code> regardless)') ?><br /> - <label> - <input type="checkbox" name="show_rating" value="Y" <?php checked('Y', $row->show_rating); ?> /> - <?php _e('Rating') ?></label> <br /> - <label> - <input type="checkbox" name="show_updated" value="Y" <?php checked('Y', $row->show_updated); ?> /> - <?php _e('Updated') ?></label> -<?php _e('(shown in <code>title</code> regardless)') ?></td> -</tr> -<tr> - <th scope="row"><?php _e('Sort order:') ?></th> - <td> - <select name="sort_order" size="1"> - <option value="name" <?php echo ($row->sort_order == 'name') ? 'selected="selected"' : ''?>><?php _e('Name') ?></option> - <option value="id" <?php echo ($row->sort_order == 'id') ? 'selected' : ''?>><?php _e('Id') ?></option> - <option value="url" <?php echo ($row->sort_order == 'url') ? 'selected' : ''?>><?php _e('URL') ?></option> - <option value="rating" <?php echo ($row->sort_order == 'rating') ? 'selected' : ''?>><?php _e('Rating') ?></option> - <option value="updated" <?php echo ($row->sort_order == 'updated') ? 'selected' : ''?>><?php _e('Updated') ?></option> - <option value="rand" <?php echo ($row->sort_order == 'rand') ? 'selected' : ''?>><?php _e('Random') ?></option> - <option value="length" <?php echo ($row->sort_order == 'length') ? 'selected' : ''?>><?php _e('Name Length') ?></option> - </select> - <label> - <input type="checkbox" name="sort_desc" value="Y" <?php checked('Y', $row->sort_desc); ?> /> - <?php _e('Descending') ?></label> - </td> -</tr> -<tr> - <th scope="row"><?php _e('Limit:') ?></th> - <td> - <input type="text" name="list_limit" size="5" value="<?php echo $row->list_limit ?>" /> - <?php _e('(Leave empty for no limit to number of links shown)') ?> - </td> -</tr> -<tr> - <th scope="row"><?php _e('Toggle:') ?></th> - <td><label> - <input type="checkbox" name="auto_toggle" value="Y" <?php checked('Y', $row->auto_toggle); ?> /> - <?php _e('When new link is added toggle all others to be invisible') ?></label></td> -</tr> - -</table> -</fieldset> -<fieldset class="options"> -<legend><?php _e('Formatting') ?></legend> -<table class="editform" width="100%" cellspacing="2" cellpadding="5"> -<tr> - <th width="33%" scope="row"><?php _e('Before Link:') ?></th> - <td width="67%"><input type="text" name="text_before_link" size="45" value="<?php echo wp_specialchars($row->text_before_link)?>" /></td> -</tr> -<tr> -<th scope="row"><?php _e('Between Link and Description:') ?></th> -<td><input type="text" name="text_after_link" size="45" value="<?php echo wp_specialchars($row->text_after_link)?>" /></td> -</tr> -<tr> -<th scope="row"><?php _e('After Link:') ?></th> -<td><input type="text" name="text_after_all" size="45" value="<?php echo wp_specialchars($row->text_after_all)?>"/></td> -</tr> -</table> -</fieldset> -<p class="submit"><input type="submit" name="submit" value="<?php _e('Save Category Settings »') ?>" /></p> -</form> - -</div> -<?php - } // end if row - break; - } // end Edit - case "editedcat": - { - if ( !current_user_can('manage_links') ) - die (__("Cheatin' uh ?")); - - $submit=$_POST["submit"]; - if (isset($submit)) { - - $cat_id = (int)$_POST["cat_id"]; - - $cat_name= wp_specialchars($_POST["cat_name"]); - $auto_toggle = $_POST["auto_toggle"]; - if ($auto_toggle != 'Y') { - $auto_toggle = 'N'; - } - - $show_images = $_POST["show_images"]; - if ($show_images != 'Y') { - $show_images = 'N'; - } - - $show_description = $_POST["show_description"]; - if ($show_description != 'Y') { - $show_description = 'N'; - } - - $show_rating = $_POST["show_rating"]; - if ($show_rating != 'Y') { - $show_rating = 'N'; - } - - $show_updated = $_POST["show_updated"]; - if ($show_updated != 'Y') { - $show_updated = 'N'; - } - - $sort_order = $_POST["sort_order"]; - - $sort_desc = $_POST["sort_desc"]; - if ($sort_desc != 'Y') { - $sort_desc = 'N'; - } - $text_before_link = $_POST["text_before_link"]; - $text_after_link = $_POST["text_after_link"]; - $text_after_all = $_POST["text_after_all"]; - - $list_limit = $_POST["list_limit"]; - if ($list_limit == '') - $list_limit = -1; - - $wpdb->query("UPDATE $wpdb->linkcategories set - cat_name='$cat_name', - auto_toggle='$auto_toggle', - show_images='$show_images', - show_description='$show_description', - show_rating='$show_rating', - show_updated='$show_updated', - sort_order='$sort_order', - sort_desc='$sort_desc', - text_before_link='$text_before_link', - text_after_link='$text_after_link', - text_after_all='$text_after_all', - list_limit=$list_limit - WHERE cat_id=$cat_id - "); - } // end if save - - - header("Location: link-categories.php"); - break; - } // end editcat - default: - { - include_once ("admin-header.php"); - if ( !current_user_can('manage_links') ) - die(__("You have do not have sufficient permissions to edit the link categories for this blog. :)")); -?> - -<div class="wrap"> - <h2><?php _e('Link Categories:') ?></h2> - <table id="the-list" width="100%" cellpadding="5" cellspacing="0" border="0"> - <tr> - <th rowspan="2" valign="bottom"><?php _e('Name') ?></th> - <th rowspan="2" valign="bottom"><?php _e('ID') ?></th> - <th rowspan="2" valign="bottom"><?php _e('Toggle?') ?></th> - <th colspan="4" valign="bottom" class="alternate"><?php _e('Show') ?></th> - <th rowspan="2" valign="bottom"><?php _e('Sort Order') ?></th> - <th rowspan="2" valign="bottom"><?php _e('Desc?') ?></th> - <th colspan="3" valign="bottom" class="alternate"><?php _e('Formatting') ?></th> - <th rowspan="2" valign="bottom"><?php _e('Limit') ?></th> - <th rowspan="2" colspan="2"> </th> - </tr> - <tr> - <th valign="top"><?php _e('Images') ?></th> - <th valign="top"><?php _e('Description') ?></th> - <th valign="top"><?php _e('Rating') ?></th> - <th valign="top"><?php _e('Updated') ?></th> - <th valign="top"><?php _e('Before') ?></th> - <th valign="top"><?php _e('Between') ?></th> - <th valign="top"><?php _e('After') ?></th> - </tr> -<?php -$results = $wpdb->get_results("SELECT cat_id, cat_name, auto_toggle, show_images, show_description, " - . " show_rating, show_updated, sort_order, sort_desc, text_before_link, text_after_link, " - . " text_after_all, list_limit FROM $wpdb->linkcategories ORDER BY cat_id"); -$i = 1; -foreach ($results as $row) { - if ($row->list_limit == -1) { - $row->list_limit = __('none'); - } - $style = ($i % 2) ? ' class="alternate"' : ''; - /* - Manually internationalize every sort order option. - */ - switch ($row->sort_order) { - case 'name': - $row->sort_order = __('name'); - break; - case 'id': - $row->sort_order = __('id'); - break; - case 'url': - $row->sort_order = __('url'); - break; - case 'rating': - $row->sort_order = __('rating'); - break; - case 'updated': - $row->sort_order = __('updated'); - break; - case 'rand': - $row->sort_order = __('rand'); - break; - case 'length': - $row->sort_order = __('length'); - break; - } -?> - <tr id="link-category-<?php echo $row->cat_id; ?>" valign="middle" align="center" <?php echo $style ?> style="border-bottom: 1px dotted #9C9A9C;"> - <td><?php echo wp_specialchars($row->cat_name)?></td> - <td ><?php echo $row->cat_id?></td> - <td><?php echo $row->auto_toggle == 'Y' ? __('Yes') : __('No') ?></td> - <td><?php echo $row->show_images == 'Y' ? __('Yes') : __('No') ?></td> - <td><?php echo $row->show_description == 'Y' ? __('Yes') : __('No') ?></td> - <td><?php echo $row->show_rating == 'Y' ? __('Yes') : __('No') ?></td> - <td><?php echo $row->show_updated == 'Y' ? __('Yes') : __('No') ?></td> - <td><?php echo $row->sort_order ?></td> - <td><?php echo $row->sort_desc == 'Y' ? __('Yes') : __('No') ?></td> - <td nowrap="nowrap"><?php echo htmlentities($row->text_before_link)?> </td> - <td nowrap="nowrap"><?php echo htmlentities($row->text_after_link)?> </td> - <td nowrap="nowrap"><?php echo htmlentities($row->text_after_all)?></td> - <td><?php echo $row->list_limit ?></td> - <td><a href="link-categories.php?cat_id=<?php echo $row->cat_id?>&action=Edit" class="edit"><?php _e('Edit') ?></a></td> - <td><a href="link-categories.php?cat_id=<?php echo $row->cat_id?>&action=Delete" onclick="return deleteSomething( 'link category', <?php echo $row->cat_id . ", '" . sprintf(__("You are about to delete the "%s" link category.\\n"Cancel" to stop, "OK" to delete."), wp_specialchars($row->cat_name,1)); ?>' );" class="delete"><?php _e('Delete') ?></a></td> - </tr> -<?php - ++$i; - } -?> - </table> -<p><?php _e('These are the defaults for when you call a link category with no additional arguments. All of these settings may be overwritten.') ?></p> - -<div id="ajax-response"></div> - -</div> - -<div class="wrap"> - <form name="addcat" method="post"> - <input type="hidden" name="action" value="addcat" /> - <h2><?php _e('Add a Link Category:') ?></h2> -<fieldset class="options"> -<legend><?php _e('Category Options') ?></legend> -<table class="editform" width="100%" cellspacing="2" cellpadding="5"> -<tr> - <th width="33%" scope="row"><?php _e('Name:') ?></th> - <td width="67%"><input type="text" name="cat_name" size="30" /></td> -</tr> -<tr> - <th scope="row"><?php _e('Show:') ?></th> - <td> - <label> - <input type="checkbox" name="show_images" value="Y" /> - <?php _e('Image') ?></label> <br /> - <label> - <input type="checkbox" name="show_description" value="Y" /> - <?php _e('Description') ?></label> - <?php _e('(shown in <code>title</code> regardless)') ?><br /> - <label> - <input type="checkbox" name="show_rating" value="Y" /> - <?php _e('Rating') ?></label> <br /> - <label> - <input type="checkbox" name="show_updated" value="Y" /> - <?php _e('Updated') ?></label> -<?php _e('(shown in <code>title</code> regardless)') ?></td> -</tr> -<tr> - <th scope="row"><?php _e('Sort order:') ?></th> - <td> - <select name="sort_order" size="1"> - <option value="name"><?php _e('Name') ?></option> - <option value="id"><?php _e('Id') ?></option> - <option value="url"><?php _e('URL') ?></option> - <option value="rating"><?php _e('Rating') ?></option> - <option value="updated"><?php _e('Updated') ?></option> - <option value="rand"><?php _e('Random') ?></option> - </select> - <label> - <input type="checkbox" name="sort_desc" value="Y" /> - <?php _e('Descending') ?></label> - </td> -</tr> -<tr> - <th scope="row"><?php _e('Limit:') ?></th> - <td> - <input type="text" name="list_limit" size="5" value="" /> <?php _e('(Leave empty for no limit to number of links shown)') ?> - </td> -</tr> -<tr> - <th scope="row"><?php _e('Toggle:') ?></th> - <td><label> - <input type="checkbox" name="auto_toggle" value="Y" /> - <?php _e('When new link is added toggle all others to be invisible') ?></label></td> -</tr> - -</table> -</fieldset> -<fieldset class="options"> -<legend><?php _e('Formatting') ?></legend> -<table class="editform" width="100%" cellspacing="2" cellpadding="5"> -<tr> - <th width="33%" scope="row"><?php _e('Before Link:') ?></th> - <td width="67%"><input type="text" name="text_before_link" size="45" value="<li>" /></td> -</tr> -<tr> -<th scope="row"><?php _e('Between Link and Description:') ?></th> -<td><input type="text" name="text_after_link" size="45" value="<br />" /></td> -</tr> -<tr> -<th scope="row"><?php _e('After Link:') ?></th> -<td><input type="text" name="text_after_all" size="45" value="</li>"/></td> -</tr> -</table> -</fieldset> -<p class="submit"><input type="submit" name="submit" value="<?php _e('Add Category »') ?>" /></p> - </form> -</div> -<div class="wrap"> - <h3><?php _e('Note:') ?></h3> - <p><?php printf(__('Deleting a link category does not delete links from that category.<br />It will just set them back to the default category <strong>%s</strong>.'), get_linkcatname(1)) ?></p> -</div> -<?php - break; - } // end default -} // end case -?> -<?php include('admin-footer.php'); ?> diff --git a/wp-inst/wp-admin/menu.php b/wp-inst/wp-admin/menu.php index 5482431..f363a76 100644 --- a/wp-inst/wp-admin/menu.php +++ b/wp-inst/wp-admin/menu.php @@ -17,11 +17,12 @@ $menu[25] = array(__('Presentation'), 'switch_themes', 'themes.php'); if( $menu_perms[ 'plugins' ] == 1 ) $menu[30] = array(__('Plugins'), 'activate_plugins', 'plugins.php'); if ( current_user_can('edit_users') ) - $menu[35] = array(__('Users'), 'read', 'profile.php'); + $menu[35] = array(__('Users'), 'edit_users', 'users.php'); else $menu[35] = array(__('Profile'), 'read', 'profile.php'); $menu[40] = array(__('Options'), 'manage_options', 'options-general.php'); + $submenu['post-new.php'][5] = array(__('Write Post'), 'edit_posts', 'post-new.php'); $submenu['post-new.php'][10] = array(__('Write Page'), 'edit_pages', 'page-new.php'); @@ -31,26 +32,36 @@ $submenu['edit.php'][15] = array(__('Categories'), 'manage_categories', 'categor $submenu['edit.php'][20] = array(__('Comments'), 'edit_posts', 'edit-comments.php'); $awaiting_mod = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = '0'"); $submenu['edit.php'][25] = array(sprintf(__("Awaiting Moderation (%s)"), "<span id='awaitmod'>$awaiting_mod</span>"), 'edit_posts', 'moderation.php'); -#$submenu['edit.php'][30] = array(__('Files'), 'edit_files', 'templates.php'); +//$submenu['edit.php'][30] = array(__('Files'), 'edit_files', 'templates.php'); $submenu['edit.php'][35] = array(__('Import'), 'import', 'import.php'); -/* -$invites_left = get_usermeta( $user_ID, 'invites_left' ); -$submenu['edit.php'][35] = array(sprintf(__("Invites (%s)"), $invites_left ), 'edit_posts', 'invites.php'); // TODO: put somewhere else. -*/ +$submenu['edit.php'][40] = array(__('Export'), 'import', 'export.php'); +//$invites_left = get_usermeta( $user_ID, 'invites_left' ); +//$submenu['edit.php'][45] = array(sprintf(__("Invites (%s)"), $invites_left ), 'edit_posts', 'invites.php'); // TODO: put somewhere else. $submenu['link-manager.php'][5] = array(__('Manage Bookmarks'), 'manage_links', 'link-manager.php'); $submenu['link-manager.php'][10] = array(__('Add Bookmark'), 'manage_links', 'link-add.php'); $submenu['link-manager.php'][20] = array(__('Import Bookmarks'), 'manage_links', 'link-import.php'); -$submenu['profile.php'][5] = array(__('Your Profile'), 'read', 'profile.php'); -$submenu['profile.php'][10] = array(__('Authors & Users'), 'edit_users', 'users.php'); +if ( current_user_can('edit_users') ) { + $submenu['users.php'][5] = array(__('Authors & Users'), 'edit_users', 'users.php'); + $submenu['users.php'][10] = array(__('Your Profile'), 'read', 'profile.php'); +} else { + $submenu['profile.php'][5] = array(__('Your Profile'), 'read', 'profile.php'); +} $submenu['options-general.php'][10] = array(__('General'), 'manage_options', 'options-general.php'); $submenu['options-general.php'][15] = array(__('Writing'), 'manage_options', 'options-writing.php'); $submenu['options-general.php'][20] = array(__('Reading'), 'manage_options', 'options-reading.php'); $submenu['options-general.php'][25] = array(__('Discussion'), 'manage_options', 'options-discussion.php'); +//$submenu['options-general.php'][30] = array(__('Privacy'), 'manage_options', 'options-privacy.php'); +//$submenu['options-general.php'][35] = array(__('Permalinks'), 'manage_options', 'options-permalink.php'); +//$submenu['options-general.php'][40] = array(__('Miscellaneous'), 'manage_options', 'options-misc.php'); + +//$submenu['plugins.php'][5] = array(__('Plugins'), 'activate_plugins', 'plugins.php'); +//$submenu['plugins.php'][10] = array(__('Plugin Editor'), 'edit_plugins', 'plugin-editor.php'); $submenu['themes.php'][5] = array(__('Themes'), 'switch_themes', 'themes.php'); +//$submenu['themes.php'][10] = array(__('Theme Editor'), 'edit_themes', 'theme-editor.php'); // Create list of page plugin hook names. foreach ($menu as $menu_page) { @@ -120,9 +131,10 @@ if (! user_can_access_admin_page()) { global $wpdb; // find the blog of this user first $primary_blog = $wpdb->get_var( "SELECT meta_value FROM {$wpdb->usermeta} WHERE user_id = '$user_ID' AND meta_key = 'primary_blog'" ); - $url = $wpdb->get_row("SELECT domain, path FROM $wpdb->blogs WHERE blog_id = $primary_blog"); - header( 'Location: http://' . $url->domain . $url->path . 'wp-admin/' ); - exit; + if( $primary_blog ) { + header( "Location: " . get_blog_option( $primary_blog, "siteurl" ) . "/wp-admin/" ); + exit; + } die( __('You do not have sufficient permissions to access this page.') ); } diff --git a/wp-inst/wp-admin/options-misc.php b/wp-inst/wp-admin/options-misc.php index c4f544e..3dd1120 100644 --- a/wp-inst/wp-admin/options-misc.php +++ b/wp-inst/wp-admin/options-misc.php @@ -1,11 +1,11 @@ <?php +die(); require_once('admin.php'); $title = __('Miscellaneous Options'); $parent_file = 'options-general.php'; include('admin-header.php'); -return; ?> diff --git a/wp-inst/wp-admin/options-permalink.php b/wp-inst/wp-admin/options-permalink.php index 180a43a..73a610b 100644 --- a/wp-inst/wp-admin/options-permalink.php +++ b/wp-inst/wp-admin/options-permalink.php @@ -1,5 +1,5 @@ <?php -return; +die(); require_once('admin.php'); $title = __('Permalink Options'); diff --git a/wp-inst/wp-admin/options-reading.php b/wp-inst/wp-admin/options-reading.php index 96abcdf..aa806c9 100644 --- a/wp-inst/wp-admin/options-reading.php +++ b/wp-inst/wp-admin/options-reading.php @@ -29,8 +29,8 @@ include('admin-header.php'); <?php printf(__('A static <a href="%s">page</a> (select below)'), 'edit-pages.php'); ?> </label> <ul> - <li><?php printf(__('Show this page on the front page: %s'), wp_dropdown_pages("name=page_on_front&echo=0&selected=" . get_option('page_on_front'))); ?></li> - <li><?php printf(__('Show the latest posts on this page: %s'), wp_dropdown_pages("name=page_for_posts&echo=0&selected=" . get_option('page_for_posts'))); ?></li> + <li><?php printf(__('Show this page on the front page: %s'), wp_dropdown_pages("name=page_on_front&echo=0&show_option_none=".__('- Select -')."&selected=" . get_option('page_on_front'))); ?></li> + <li><?php printf(__('Show the latest posts on this page: %s'), wp_dropdown_pages("name=page_for_posts&echo=0&show_option_none=".__('- Select -')."&selected=" . get_option('page_for_posts'))); ?></li> </ul> <?php if ( 'page' == get_option('show_on_front') && get_option('page_for_posts') == get_option('page_on_front') ) : ?> <div id="front-page-warning" class="updated fade-ff0000"> diff --git a/wp-inst/wp-admin/plugin-editor.php b/wp-inst/wp-admin/plugin-editor.php index 885fb94..56bab5a 100644 --- a/wp-inst/wp-admin/plugin-editor.php +++ b/wp-inst/wp-admin/plugin-editor.php @@ -1,5 +1,5 @@ <?php -return; +die(); require_once('admin.php'); $title = __("Edit Plugins"); diff --git a/wp-inst/wp-admin/profile.php b/wp-inst/wp-admin/profile.php index 04f2fc4..eb66e07 100644 --- a/wp-inst/wp-admin/profile.php +++ b/wp-inst/wp-admin/profile.php @@ -3,7 +3,10 @@ require_once('admin.php'); $title = __('Profile'); -$parent_file = 'profile.php'; +if ( current_user_can('edit_users') ) + $parent_file = 'users.php'; +else + $parent_file = 'profile.php'; include_once('admin-header.php'); $profileuser = new WP_User($user_ID); diff --git a/wp-inst/wp-admin/setup-config.php b/wp-inst/wp-admin/setup-config.php index 51c69e0..d25c58b 100644 --- a/wp-inst/wp-admin/setup-config.php +++ b/wp-inst/wp-admin/setup-config.php @@ -1,5 +1,5 @@ <?php -return; +die(); define('WP_INSTALLING', true); if (!file_exists('../wp-config-sample.php')) diff --git a/wp-inst/wp-admin/templates.php b/wp-inst/wp-admin/templates.php index 97c87ba..c22d56a 100644 --- a/wp-inst/wp-admin/templates.php +++ b/wp-inst/wp-admin/templates.php @@ -1,5 +1,5 @@ <?php -return; +die(); require_once('admin.php'); $title = __('Template & File Editing'); $parent_file = 'edit.php'; diff --git a/wp-inst/wp-admin/theme-editor.php b/wp-inst/wp-admin/theme-editor.php index dfea183..10fb8fc 100644 --- a/wp-inst/wp-admin/theme-editor.php +++ b/wp-inst/wp-admin/theme-editor.php @@ -1,5 +1,5 @@ <?php -return; +die(); require_once('admin.php'); $title = __("Edit Themes"); diff --git a/wp-inst/wp-admin/upgrade-functions.php b/wp-inst/wp-admin/upgrade-functions.php index 7f92a42..e1c1e02 100644 --- a/wp-inst/wp-admin/upgrade-functions.php +++ b/wp-inst/wp-admin/upgrade-functions.php @@ -5,7 +5,7 @@ if ( file_exists(ABSPATH . 'wp-content/install.php') ) require_once(ABSPATH . '/wp-admin/admin-functions.php'); require_once(ABSPATH . '/wp-admin/admin-db.php'); require_once(ABSPATH . '/wp-admin/upgrade-schema.php'); -require_once(ABSPATH . '/wp-includes/registration-functions.php'); +require_once(ABSPATH . WPINC . '/registration.php'); if ( !function_exists('wp_install') ) : function wp_install($blog_title, $user_name, $user_email, $public, $meta='') { diff --git a/wp-inst/wp-admin/upgrade-schema.php b/wp-inst/wp-admin/upgrade-schema.php index 71106bb..ed8c537 100644 --- a/wp-inst/wp-admin/upgrade-schema.php +++ b/wp-inst/wp-admin/upgrade-schema.php @@ -15,7 +15,7 @@ $wp_queries="CREATE TABLE $wpdb->categories ( links_private tinyint(1) NOT NULL default '0', PRIMARY KEY (cat_ID), KEY category_nicename (category_nicename) -); +) TYPE=MyISAM; CREATE TABLE $wpdb->comments ( comment_ID bigint(20) unsigned NOT NULL auto_increment, comment_post_ID int(11) NOT NULL default '0', @@ -35,14 +35,14 @@ CREATE TABLE $wpdb->comments ( PRIMARY KEY (comment_ID), KEY comment_approved (comment_approved), KEY comment_post_ID (comment_post_ID) -); +) TYPE=MyISAM; CREATE TABLE $wpdb->link2cat ( rel_id bigint(20) NOT NULL auto_increment, link_id bigint(20) NOT NULL default '0', category_id bigint(20) NOT NULL default '0', PRIMARY KEY (rel_id), KEY link_id (link_id,category_id) -); +) TYPE=MyISAM; CREATE TABLE $wpdb->links ( link_id bigint(20) NOT NULL auto_increment, link_url varchar(255) NOT NULL default '', @@ -61,7 +61,7 @@ CREATE TABLE $wpdb->links ( PRIMARY KEY (link_id), KEY link_category (link_category), KEY link_visible (link_visible) -); +) TYPE=MyISAM; CREATE TABLE $wpdb->options ( option_id bigint(20) NOT NULL auto_increment, blog_id int(11) NOT NULL default '0', @@ -76,14 +76,14 @@ CREATE TABLE $wpdb->options ( autoload enum('yes','no') NOT NULL default 'yes', PRIMARY KEY (option_id,blog_id,option_name), KEY option_name (option_name) -); +) TYPE=MyISAM; CREATE TABLE $wpdb->post2cat ( rel_id bigint(20) NOT NULL auto_increment, post_id bigint(20) NOT NULL default '0', category_id bigint(20) NOT NULL default '0', PRIMARY KEY (rel_id), KEY post_id (post_id,category_id) -); +) TYPE=MyISAM; CREATE TABLE $wpdb->postmeta ( meta_id bigint(20) NOT NULL auto_increment, post_id bigint(20) NOT NULL default '0', @@ -92,7 +92,7 @@ CREATE TABLE $wpdb->postmeta ( PRIMARY KEY (meta_id), KEY post_id (post_id), KEY meta_key (meta_key) -); +) TYPE=MyISAM; CREATE TABLE $wpdb->posts ( ID bigint(20) unsigned NOT NULL auto_increment, post_author bigint(20) NOT NULL default '0', @@ -121,7 +121,7 @@ CREATE TABLE $wpdb->posts ( PRIMARY KEY (ID), KEY post_name (post_name), KEY type_status_date (post_type, post_status, post_date, ID) -); +) TYPE=MyISAM;"; CREATE TABLE $wpdb->users ( ID bigint(20) unsigned NOT NULL auto_increment, user_login varchar(60) NOT NULL default '', diff --git a/wp-inst/wp-admin/upgrade.php b/wp-inst/wp-admin/upgrade.php index cbc9699..66f3fec 100644 --- a/wp-inst/wp-admin/upgrade.php +++ b/wp-inst/wp-admin/upgrade.php @@ -76,10 +76,10 @@ switch($step) { case 1: wp_upgrade(); - if( $wpdb->get_row( "SELECT * FROM wp_blogs WHERE blog_id = '{$wpdb->blogid}'" ) ) { - $wpdb->query( "UPDATE wp_blogs SET db_version = '{$wp_db_version}' WHERE blog_id = '{$wpdb->blogid}'" ); + if( $wpdb->get_row( "SELECT blog_id FROM wp_blog_versions WHERE blog_id = '{$wpdb->blogid}'" ) ) { + $wpdb->query( "UPDATE wp_blog_versions SET db_version = '{$wp_db_version}' WHERE blog_id = '{$wpdb->blogid}'" ); } else { - $wpdb->query( "INSERT INTO `wp_blogs` ( `blog_id` , `db_version` , `last_updated` ) VALUES ( '{$wpdb->blogid}', '{$wp_db_version}', NOW());" ); + $wpdb->query( "INSERT INTO wp_blog_versions ( `blog_id` , `db_version` , `last_updated` ) VALUES ( '{$wpdb->blogid}', '{$wp_db_version}', NOW());" ); } if ( empty( $_GET['backto'] ) ) diff --git a/wp-inst/wp-admin/user-edit.php b/wp-inst/wp-admin/user-edit.php index 3d394a4..0aff941 100644 --- a/wp-inst/wp-admin/user-edit.php +++ b/wp-inst/wp-admin/user-edit.php @@ -2,10 +2,13 @@ require_once('admin.php'); $title = __('Edit User'); -$parent_file = 'profile.php'; +if ( current_user_can('edit_users') ) + $parent_file = 'users.php'; +else + $parent_file = 'profile.php'; $submenu_file = 'users.php'; -$wpvarstoreset = array('action', 'redirect', 'profile', 'user_id'); +$wpvarstoreset = array('action', 'redirect', 'profile', 'user_id', 'wp_http_referer'); for ($i=0; $i<count($wpvarstoreset); $i += 1) { $wpvar = $wpvarstoreset[$i]; if (!isset($$wpvar)) { @@ -21,6 +24,7 @@ for ($i=0; $i<count($wpvarstoreset); $i += 1) { } } +$wp_http_referer = remove_query_arg(array('update', 'delete_count'), stripslashes($wp_http_referer)); $errors = array(); // Only allow site admins to edit every user. @@ -48,7 +52,9 @@ else if( !is_wp_error( $errors ) ) { if( is_site_admin() ) update_usermeta( $user_id, 'invites_left', intval( $_POST[ 'invites_left' ] ) ); - header("Location: user-edit.php?user_id=$user_id&updated=true"); + $redirect = "user-edit.php?user_id=$user_id&updated=true"; + $redirect = add_query_arg('wp_http_referer', urlencode($wp_http_referer), $redirect); + header("Location: $redirect"); exit; } @@ -65,6 +71,9 @@ if ( !current_user_can('edit_user', $user_id) ) <?php if ( isset($_GET['updated']) ) : ?> <div id="message" class="updated fade"> <p><strong><?php _e('User updated.') ?></strong></p> + <?php if ( $wp_http_referer ) : ?> + <p><a href="<?php echo wp_specialchars($wp_http_referer); ?>"><?php _e('« Back to Authors and Users'); ?></a></p> + <?php endif; ?> </div> <?php endif; ?> <?php if ( is_wp_error( $errors ) ) { ?> @@ -83,6 +92,9 @@ if ( !current_user_can('edit_user', $user_id) ) <form name="profile" id="your-profile" action="user-edit.php" method="post"> <?php wp_nonce_field('update-user_' . $user_id) ?> +<?php if ( $wp_http_referer ) : ?> + <input type="hidden" name="wp_http_referer" value="<?php echo wp_specialchars($wp_http_referer); ?>" /> +<?php endif; ?> <p> <input type="hidden" name="from" value="profile" /> <input type="hidden" name="checkuser_id" value="<?php echo $user_ID ?>" /> @@ -99,6 +111,29 @@ if ( !current_user_can('edit_user', $user_id) ) <?php } // is_site_admin ?> + +<p><label><?php _e('Role:') ?><br /> +<?php +// print_r($profileuser); +echo '<select name="role">'; +$role_list = ''; +$user_has_role = false; +foreach($wp_roles->role_names as $role => $name) { + if ( $profileuser->has_cap($role) ) { + $selected = ' selected="selected"'; + $user_has_role = true; + } else { + $selected = ''; + } + $role_list .= "<option value=\"{$role}\"{$selected}>{$name}</option>"; +} +if ( $user_has_role ) + $role_list .= '<option value="">' . __('— No role for this blog —') . '</option>'; +else + $role_list .= '<option value="" selected="selected">' . __('— No role for this blog —') . '</option>'; +echo $role_list . '</select>'; +?></label></p> + <p><label><?php _e('First name:') ?><br /> <input type="text" name="first_name" value="<?php echo $profileuser->first_name ?>" /></label></p> diff --git a/wp-inst/wp-admin/users.php b/wp-inst/wp-admin/users.php index 6dfc57a..2ed85bf 100644 --- a/wp-inst/wp-admin/users.php +++ b/wp-inst/wp-admin/users.php @@ -1,41 +1,151 @@ <?php require_once('admin.php'); -require_once( ABSPATH . WPINC . '/registration-functions.php'); +require_once( ABSPATH . WPINC . '/registration.php'); $title = __('Users'); -$parent_file = 'profile.php'; +if ( current_user_can('edit_users') ) + $parent_file = 'users.php'; +else + $parent_file = 'profile.php'; $action = $_REQUEST['action']; $update = ''; +if ( empty($_POST) ) { + $referer = '<input type="hidden" name="wp_http_referer" value="'. wp_specialchars(stripslashes($_SERVER['REQUEST_URI'])) . '" />'; +} elseif ( isset($_POST['wp_http_referer']) ) { + $redirect = remove_query_arg(array('wp_http_referer', 'updated', 'delete_count'), urlencode(stripslashes($_POST['wp_http_referer']))); + $referer = '<input type="hidden" name="wp_http_referer" value="' . wp_specialchars($redirect) . '" />'; +} else { + $redirect = 'users.php'; +} + + +// WP_User_Search class +// by Mark Jaquith + + +class WP_User_Search { + var $results; + var $search_term; + var $page; + var $raw_page; + var $users_per_page = 50; + var $first_user; + var $last_user; + var $query_limit; + var $query_from_where; + var $total_users_for_query = 0; + var $too_many_total_users = false; + var $search_errors; + + function WP_User_Search ($search_term = '', $page = '') { // constructor + $this->search_term = $search_term; + $this->raw_page = ( '' == $page ) ? false : (int) $page; + $this->page = (int) ( '' == $page ) ? 1 : $page; + + $this->prepare_query(); + $this->query(); + $this->prepare_vars_for_template_usage(); + $this->do_paging(); + } + + function prepare_query() { + global $wpdb; + $this->first_user = ($this->page - 1) * $this->users_per_page; + $this->query_limit = 'LIMIT ' . $this->first_user . ',' . $this->users_per_page; + if ( $this->search_term ) { + $searches = array(); + $search_sql = 'AND ('; + foreach ( array('user_login', 'user_nicename', 'user_email', 'user_url', 'display_name') as $col ) + $searches[] = $col . " LIKE '%$this->search_term%'"; + $search_sql .= implode(' OR ', $searches); + $search_sql .= ')'; + } + $this->query_from_where = "FROM $wpdb->users, $wpdb->usermeta WHERE $wpdb->users.ID = $wpdb->usermeta.user_id AND meta_key = '".$wpdb->prefix."capabilities' $search_sql"; + + if ( !$_GET['update'] && !$this->search_term && !$this->raw_page && $wpdb->get_var("SELECT COUNT(ID) FROM $wpdb->users, $wpdb->usermeta WHERE $wpdb->users.ID = $wpdb->usermeta.user_id AND meta_key = '".$wpdb->prefix."capabilities'") > $this->users_per_page ) + $this->too_many_total_users = sprintf(__('Because this blog has more than %s users, they cannot all be shown on one page. Use the paging or search functionality in order to find the user you want to edit.'), $this->users_per_page); + } + + function query() { + global $wpdb; + $this->results = $wpdb->get_col('SELECT ID ' . $this->query_from_where . $this->query_limit); + + if ( $this->results ) + $this->total_users_for_query = $wpdb->get_var('SELECT COUNT(ID) ' . $this->query_from_where); // no limit + else + $this->search_errors = new WP_Error('no_matching_users_found', __('No matching users were found!')); + } + + function prepare_vars_for_template_usage() { + $this->search_term = stripslashes($this->search_term); // done with DB, from now on we want slashes gone + } + + function do_paging() { + if ( $this->total_users_for_query > $this->users_per_page ) { // have to page the results + $prev_page = ( $this->page > 1) ? true : false; + $next_page = ( ($this->page * $this->users_per_page) < $this->total_users_for_query ) ? true : false; + $this->paging_text = ''; + if ( $prev_page ) + $this->paging_text .= '<p class="alignleft"><a href="' . add_query_arg(array('usersearch' => $this->search_term, 'userspage' => $this->page - 1), 'users.php?') . '">« Previous Page</a></p>'; + if ( $next_page ) + $this->paging_text .= '<p class="alignright"><a href="' . add_query_arg(array('usersearch' => $this->search_term, 'userspage' => $this->page + 1), 'users.php?') . '">Next Page »</a></p>'; + if ( $prev_page || $next_page ) + $this->paging_text .= '<br style="clear:both" />'; + } + } + + function get_results() { + return $this->results; + } + + function page_links() { + echo $this->paging_text; + } + + function results_are_paged() { + if ( $this->paging_text ) + return true; + return false; + } + + function is_search() { + if ( $this->search_term ) + return true; + return false; + } +} + + switch ($action) { case 'promote': check_admin_referer('bulk-users'); if (empty($_POST['users'])) { - header('Location: users.php'); + header('Location: ' . $redirect); } if ( !current_user_can('edit_users') ) die(__('You can’t edit users.')); - $userids = $_POST['users']; + $userids = $_POST['users']; $update = 'promote'; - foreach($userids as $id) { - if ( ! current_user_can('edit_user', $id) ) - die(__('You can’t edit that user.')); + foreach($userids as $id) { + if ( ! current_user_can('edit_user', $id) ) + die(__('You can’t edit that user.')); // The new role of the current user must also have edit_users caps if($id == $current_user->id && !$wp_roles->role_objects[$_POST['new_role']]->has_cap('edit_users')) { $update = 'err_admin_role'; continue; } - $user = new WP_User($id); - $user->set_role($_POST['new_role']); - } + $user = new WP_User($id); + $user->set_role($_POST['new_role']); + } - header('Location: users.php?update=' . $update); + header('Location: ' . add_query_arg('update', $update, $redirect)); break; @@ -44,24 +154,25 @@ case 'dodelete': check_admin_referer('delete-users'); if ( empty($_POST['users']) ) { - header('Location: users.php'); + header('Location: ' . $redirect); } if ( !current_user_can('delete_users') ) die(__('You can’t delete users.')); $userids = $_POST['users']; - $update = 'del'; - foreach ($userids as $id) { - if ( ! current_user_can('delete_user', $id) ) - die(__('You can’t delete that user.')); - + $delete_count = 0; + + foreach ( (array) $userids as $id) { + if ( ! current_user_can('delete_user', $id) ) + die(__('You can’t delete that user.')); + if($id == $current_user->id) { $update = 'err_admin_del'; continue; } - switch($_POST['delete_option']) { + switch($_POST['delete_option']) { case 'delete': wp_delete_user($id); break; @@ -69,9 +180,12 @@ case 'dodelete': wp_delete_user($id, $_POST['reassign_user']); break; } + ++$delete_count; } - header('Location: users.php?update=' . $update); + $redirect = add_query_arg('delete_count', $delete_count, $redirect); + + header('Location: ' . add_query_arg('update', $update, $redirect)); break; @@ -79,12 +193,11 @@ case 'delete': die( "This function is disabled." ); check_admin_referer('bulk-users'); - if (empty($_POST['users'])) { - header('Location: users.php'); - } + if ( empty($_POST['users']) ) + header('Location: ' . $redirect); if ( !current_user_can('delete_users') ) - $error = new WP_Error('edit_users', __('You can’t delete users.')); + $errors = new WP_Error('edit_users', __('You can’t delete users.')); $userids = $_POST['users']; @@ -92,33 +205,32 @@ case 'delete': ?> <form action="" method="post" name="updateusers" id="updateusers"> <?php wp_nonce_field('delete-users') ?> +<?php echo $referer; ?> <div class="wrap"> <h2><?php _e('Delete Users'); ?></h2> <p><?php _e('You have specified these users for deletion:'); ?></p> <ul> <?php $go_delete = false; - foreach ($userids as $id) { - $user = new WP_User($id); - if ($id == $current_user->id) { + foreach ( (array) $userids as $id ) { + $user = new WP_User($id); + if ( $id == $current_user->id ) { echo "<li>" . sprintf(__('ID #%1s: %2s <strong>The current user will not be deleted.</strong>'), $id, $user->user_login) . "</li>\n"; } else { echo "<li><input type=\"hidden\" name=\"users[]\" value=\"{$id}\" />" . sprintf(__('ID #%1s: %2s'), $id, $user->user_login) . "</li>\n"; $go_delete = true; } - } + } $all_logins = $wpdb->get_results("SELECT ID, user_login FROM $wpdb->users, $wpdb->usermeta WHERE $wpdb->users.ID = $wpdb->usermeta.user_id AND meta_key = '".$wpdb->prefix."capabilities'"); - $user_dropdown = '<select name="reassign_user">'; - foreach ($all_logins as $login) { - if ( $login->ID == $current_user->id || !in_array($login->ID, $userids) ) { - $user_dropdown .= "<option value=\"{$login->ID}\">{$login->user_login}</option>"; - } - } - $user_dropdown .= '</select>'; - ?> - </ul> -<?php if($go_delete) : ?> - <p><?php _e('What should be done with posts and links owned by this user?'); ?></p> + $user_dropdown = '<select name="reassign_user">'; + foreach ( (array) $all_logins as $login ) + if ( $login->ID == $current_user->id || !in_array($login->ID, $userids) ) + $user_dropdown .= "<option value=\"{$login->ID}\">{$login->user_login}</option>"; + $user_dropdown .= '</select>'; + ?> + </ul> +<?php if ( $go_delete ) : ?> + <p><?php _e('What should be done with posts and links owned by this user?'); ?></p> <ul style="list-style:none;"> <li><label><input type="radio" id="delete_option0" name="delete_option" value="delete" checked="checked" /> <?php _e('Delete all posts and links.'); ?></label></li> @@ -137,7 +249,7 @@ case 'delete': break; case 'doremove': - check_admin_referer(); + check_admin_referer('remove-users'); if ( empty($_POST['users']) ) { header('Location: users.php'); @@ -163,7 +275,7 @@ break; case 'removeuser': - check_admin_referer(); + check_admin_referer('bulk-users'); if (empty($_POST['users'])) { header('Location: users.php'); @@ -177,6 +289,7 @@ case 'removeuser': include ('admin-header.php'); ?> <form action="" method="post" name="updateusers" id="updateusers"> +<?php wp_nonce_field('remove-users') ?> <div class="wrap"> <h2><?php _e('Remove Users from Blog'); ?></h2> <p><?php _e('You have specified these users for removal:'); ?></p> @@ -213,15 +326,18 @@ case 'adduser': die(__('You can’t create users.')); $user_id = add_user(); + $update = 'add'; if ( is_wp_error( $user_id ) ) - $errors = $user_id; + $add_user_errors = $user_id; else { - header('Location: users.php?update=add'); + $new_user_login = apply_filters('pre_user_login', sanitize_user(stripslashes($_POST['user_login']), true)); + $redirect = add_query_arg('usersearch', $new_user_login, $redirect); + header('Location: ' . add_query_arg('update', $update, $redirect) . '#user-' . $user_id); die(); } case 'addexistinguser': - check_admin_referer(); + check_admin_referer('add-user'); if ( !current_user_can('edit_users') ) die(__('You can’t edit users.')); @@ -244,32 +360,28 @@ case 'addexistinguser': die(); break; default: - wp_enqueue_script( 'admin-users' ); + wp_enqueue_script('admin-users'); - include ('admin-header.php'); + include('admin-header.php'); - if ( !current_user_can('edit_users') ) - die(__('You can’t edit users.')); - $userids = array(); - $users = get_users_of_blog(); - foreach ( $users as $user ) - $userids[] = $user->user_id; + // Query the users + $wp_user_search = new WP_User_Search($_GET['usersearch'], $_GET['userspage']); - foreach($userids as $userid) { + // Make the user objects + foreach ( $wp_user_search->get_results() as $userid ) { $tmp_user = new WP_User($userid); $roles = $tmp_user->roles; $role = array_shift($roles); $roleclasses[$role][$tmp_user->user_login] = $tmp_user; } - ?> - - <?php - if (isset($_GET['update'])) : + if ( isset($_GET['update']) ) : switch($_GET['update']) { case 'del': + case 'del_many': ?> - <div id="message" class="updated fade"><p><?php _e('User deleted.'); ?></p></div> + <?php $delete_count = (int) $_GET['delete_count']; ?> + <div id="message" class="updated fade"><p><?php printf(__('%1$s %2$s deleted.'), $delete_count, __ngettext('user', 'users', $delete_count) ); ?></p></div> <?php break; case 'remove': @@ -316,24 +428,63 @@ default: <?php break; } - endif; - if ( is_wp_error( $errors ) ) : ?> + endif; ?> + +<?php if ( is_wp_error( $errors ) ) : ?> <div class="error"> <ul> <?php foreach ( $errors->get_error_messages() as $message ) - echo "<li>$message</li>"; + echo "<li>$message</li>"; ?> </ul> </div> - <?php - endif; - ?> +<?php endif; ?> + +<?php if ( $wp_user_search->too_many_total_users ) : ?> + <div id="message" class="updated"> + <p><?php echo $wp_user_search->too_many_total_users; ?></p> + </div> +<?php endif; ?> + +<div class="wrap"> + + <?php if ( $wp_user_search->is_search() ) : ?> + <h2><?php printf(__('Users Matching "%s" by Role'), $wp_user_search->search_term); ?></h2> + <?php else : ?> + <h2><?php _e('User List by Role'); ?></h2> + <?php endif; ?> + + <form action="" method="get" name="search" id="search"> + <p><input type="text" name="usersearch" id="usersearch" value="<?php echo wp_specialchars($wp_user_search->search_term); ?>" /> <input type="submit" value="<?php _e('Search for users »'); ?>" /></p> + </form> + + <?php if ( is_wp_error( $wp_user_search->search_errors ) ) : ?> + <div class="error"> + <ul> + <?php + foreach ( $wp_user_search->search_errors->get_error_messages() as $message ) + echo "<li>$message</li>"; + ?> + </ul> + </div> + <?php endif; ?> + + +<?php if ( $wp_user_search->get_results() ) : ?> + + <?php if ( $wp_user_search->is_search() ) : ?> + <p><a href="users.php"><?php _e('« Back to All Users'); ?></a></p> + <?php endif; ?> + + <h3><?php printf(__('Results %1$s - %2$s of %3$s shown below'), $wp_user_search->first_user + 1, min($wp_user_search->first_user + $wp_user_search->users_per_page, $wp_user_search->total_users_for_query), $wp_user_search->total_users_for_query); ?></h3> + + <?php if ( $wp_user_search->results_are_paged() ) : ?> + <div class="user-paging-text"><?php $wp_user_search->page_links(); ?></p></div> + <?php endif; ?> <form action="" method="post" name="updateusers" id="updateusers"> <?php wp_nonce_field('bulk-users') ?> -<div class="wrap"> - <h2><?php _e('User List by Role'); ?></h2> <table class="widefat"> <?php foreach($roleclasses as $role => $roleclass) { @@ -341,46 +492,62 @@ foreach($roleclasses as $role => $roleclass) { ?> <tr> - <th colspan="8" align="left"><h3><?php echo $wp_roles->role_names[$role]; ?></h3></th> +<?php if ( !empty($role) ) : ?> + <th colspan="7" align="left"><h3><?php echo $wp_roles->role_names[$role]; ?></h3></th> +<?php else : ?> + <th colspan="7" align="left"><h3><em><?php _e('No role for this blog'); ?></h3></th> +<?php endif; ?> </tr> -<thead> -<tr> +<tr class="thead"> <th style="text-align: left"><?php _e('ID') ?></th> <th style="text-align: left"><?php _e('Username') ?></th> <th style="text-align: left"><?php _e('Name') ?></th> <th style="text-align: left"><?php _e('E-mail') ?></th> <th style="text-align: left"><?php _e('Website') ?></th> - <th><?php _e('Posts') ?></th> - <th> </th> + <th colspan="2"><?php _e('Actions') ?></th> </tr> </thead> <tbody id="role-<?php echo $role; ?>"><?php $style = ''; -foreach ($roleclass as $user_object) { - $style = (' class="alternate"' == $style) ? '' : ' class="alternate"'; - echo "\n\t" . user_row( $user_object, $style ); +foreach ( (array) $roleclass as $user_object ) { + $style = ( ' class="alternate"' == $style ) ? '' : ' class="alternate"'; + echo "\n\t" . user_row($user_object, $style); } - ?> </tbody> -<?php -} -?> +<?php } ?> </table> +<?php if ( $wp_user_search->results_are_paged() ) : ?> + <div class="user-paging-text"><?php $wp_user_search->page_links(); ?></div> +<?php endif; ?> <h2><?php _e('Update Users'); ?></h2> - <ul style="list-style:none;"> - <li><input type="radio" name="action" id="action0" value="removeuser" /> <label for="action0"><?php _e('Remove checked users from blog.'); ?></label></li> - <li> - <input type="radio" name="action" id="action1" value="promote" /> <label for="action1"><?php _e('Set the Role of checked users to:'); ?></label> - <select name="new_role"><?php wp_dropdown_roles(); ?></select> - </li> - </ul> - <p class="submit"><input type="submit" value="<?php _e('Update »'); ?>" /></p> -</div> + <ul style="list-style:none;"> + <li><input type="radio" name="action" id="action0" value="removeuser" /> <label for="action0"><?php _e('Remove checked users.'); ?></label></li> + <li> + <input type="radio" name="action" id="action1" value="promote" /> <label for="action1"><?php _e('Set the Role of checked users to:'); ?></label> + <select name="new_role"><?php wp_dropdown_roles(); ?></select> + </li> + </ul> + <p class="submit"> + <?php echo $referer; ?> + <input type="submit" value="<?php _e('Update »'); ?>" /> + </p> </form> +<?php endif; ?> +</div> + +<?php + if ( is_wp_error($add_user_errors) ) { + foreach ( array('user_login' => 'user_login', 'first_name' => 'user_firstname', 'last_name' => 'user_lastname', 'email' => 'user_email', 'url' => 'user_uri', 'role' => 'user_role') as $formpost => $var ) { + $var = 'new_' . $var; + $$var = wp_specialchars(stripslashes($_POST[$formpost])); + } + unset($name); + } +?> <div class="wrap"> <h2><?php _e('Add User From Community') ?></h2> @@ -402,20 +569,29 @@ foreach ($roleclass as $user_object) { ?></select></td> </tr> </table> -<br /> - - </td> - </table> - <p class="submit"> - <input name="adduser" type="submit" id="addusersub" value="<?php _e('Add User »') ?>" /> - </p> - </form> +<p class="submit"> + <?php echo $referer; ?> + <input name="adduser" type="submit" id="addusersub" value="<?php _e('Add User »') ?>" /> +</p> +</form> + +<?php if ( is_wp_error( $add_user_errors ) ) : ?> + <div class="error"> + <ul> + <?php + foreach ( $add_user_errors->get_error_messages() as $message ) + echo "$message<br />"; + ?> + </ul> + </div> +<?php endif; ?> <div id="ajax-response"></div> </div> - <?php +<?php break; -} + +} // end of the $action switch include('admin-footer.php'); ?> diff --git a/wp-inst/wp-admin/wp-admin.css b/wp-inst/wp-admin/wp-admin.css index b73b73e..eb7052d 100644 --- a/wp-inst/wp-admin/wp-admin.css +++ b/wp-inst/wp-admin/wp-admin.css @@ -52,7 +52,7 @@ a.delete:hover { font-size: 16px; } -thead { +thead, .thead { background: #dfdfdf } diff --git a/wp-inst/wp-content/themes/default/index.php b/wp-inst/wp-content/themes/default/index.php index 165cfab..9aa2c16 100644 --- a/wp-inst/wp-content/themes/default/index.php +++ b/wp-inst/wp-content/themes/default/index.php @@ -9,7 +9,7 @@ <div class="post" id="post-<?php the_ID(); ?>"> <h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?></a></h2> <small><?php the_time('F jS, Y') ?> by <?php the_author() ?></small> - + <div class="entry"> <?php the_content('Read the rest of this entry »'); ?> </div> diff --git a/wp-inst/wp-includes/template-functions-author.php b/wp-inst/wp-includes/author-template.php index daa1678..f265b3b 100644 --- a/wp-inst/wp-includes/template-functions-author.php +++ b/wp-inst/wp-includes/author-template.php @@ -155,6 +155,13 @@ function get_author_link($echo = false, $author_id, $author_nicename) { return $link; } +// Get author's preferred display name +function get_author_name( $auth_id ) { + $authordata = get_userdata( $auth_id ); + + return $authordata->display_name; +} + function wp_list_authors($args = '') { if ( is_array($args) ) $r = &$args; @@ -223,4 +230,4 @@ function wp_list_authors($args = '') { } } -?> +?>
\ No newline at end of file diff --git a/wp-inst/wp-includes/capabilities.php b/wp-inst/wp-includes/capabilities.php index a1dfa56..3e85e4f 100644 --- a/wp-inst/wp-includes/capabilities.php +++ b/wp-inst/wp-includes/capabilities.php @@ -174,7 +174,7 @@ class WP_User { //Build $allcaps from role caps, overlay user's $caps $this->allcaps = array(); - foreach($this->roles as $role) { + foreach( (array) $this->roles as $role) { $role = $wp_roles->get_role($role); $this->allcaps = array_merge($this->allcaps, $role->capabilities); } @@ -199,8 +199,12 @@ class WP_User { function set_role($role) { foreach($this->roles as $oldrole) unset($this->caps[$oldrole]); - $this->caps[$role] = true; - $this->roles = array($role => true); + if ( !empty($role) ) { + $this->caps[$role] = true; + $this->roles = array($role => true); + } else { + $this->roles = false; + } update_usermeta($this->id, $this->cap_key, $this->caps); $this->get_role_caps(); $this->update_user_level_from_caps(); diff --git a/wp-inst/wp-includes/comment.php b/wp-inst/wp-includes/comment.php index 931a8a5..45547db 100644 --- a/wp-inst/wp-includes/comment.php +++ b/wp-inst/wp-includes/comment.php @@ -195,6 +195,52 @@ function wp_allow_comment($commentdata) { return $approved; } +function wp_blacklist_check($author, $email, $url, $comment, $user_ip, $user_agent) { + global $wpdb; + + do_action('wp_blacklist_check', $author, $email, $url, $comment, $user_ip, $user_agent); + + if ( preg_match_all('/&#(\d+);/', $comment . $author . $url, $chars) ) { + foreach ($chars[1] as $char) { + // If it's an encoded char in the normal ASCII set, reject + if ( 38 == $char ) + continue; // Unless it's & + if ($char < 128) + return true; + } + } + + $mod_keys = trim( get_settings('blacklist_keys') ); + if ('' == $mod_keys ) + return false; // If moderation keys are empty + $words = explode("\n", $mod_keys ); + + foreach ($words as $word) { + $word = trim($word); + + // Skip empty lines + if ( empty($word) ) { continue; } + + // Do some escaping magic so that '#' chars in the + // spam words don't break things: + $word = preg_quote($word, '#'); + + $pattern = "#$word#i"; + if ( preg_match($pattern, $author ) ) return true; + if ( preg_match($pattern, $email ) ) return true; + if ( preg_match($pattern, $url ) ) return true; + if ( preg_match($pattern, $comment ) ) return true; + if ( preg_match($pattern, $user_ip ) ) return true; + if ( preg_match($pattern, $user_agent) ) return true; + } + + if ( isset($_SERVER['REMOTE_ADDR']) ) { + if ( wp_proxy_check($_SERVER['REMOTE_ADDR']) ) return true; + } + + return false; +} + function wp_delete_comment($comment_id) { global $wpdb; do_action('delete_comment', $comment_id); diff --git a/wp-inst/wp-includes/functions-compat.php b/wp-inst/wp-includes/compat.php index 0eb8c42..49717a4 100644 --- a/wp-inst/wp-includes/functions-compat.php +++ b/wp-inst/wp-includes/compat.php @@ -73,7 +73,7 @@ if (!defined('CASE_UPPER')) { * @link http://php.net/function.array_change_key_case * @author Stephan Schmidt <schst@php.net> * @author Aidan Lister <aidan@php.net> - * @version $Revision: 3758 $ + * @version $Revision: 3862 $ * @since PHP 4.2.0 * @require PHP 4.0.0 (user_error) */ diff --git a/wp-inst/wp-includes/cron.php b/wp-inst/wp-includes/cron.php index 87aaa8c..bab3bf6 100644 --- a/wp-inst/wp-includes/cron.php +++ b/wp-inst/wp-includes/cron.php @@ -65,7 +65,8 @@ function wp_next_scheduled( $hook ) { }
function spawn_cron() {
- if ( array_shift( array_keys( get_option( 'cron' ) ) ) > time() )
+ $keys = array_keys( get_option( 'cron' ) );
+ if ( array_shift( $keys ) > time() )
return;
$cron_url = get_settings( 'siteurl' ) . '/wp-cron.php';
@@ -81,7 +82,12 @@ function spawn_cron() { function wp_cron() {
$crons = get_option( 'cron' );
- if ( !is_array($crons) || array_shift( array_keys( $crons ) ) > time() )
+
+ if ( !is_array($crons) )
+ return;
+
+ $keys = array_keys( $crons );
+ if ( array_shift( $keys ) > time() )
return;
$schedules = wp_get_schedules();
@@ -104,4 +110,4 @@ function wp_get_schedules() { return array_merge( apply_filters( 'cron_schedules', array() ), $schedules );
}
-?>
\ No newline at end of file +?>
diff --git a/wp-inst/wp-includes/feed-functions.php b/wp-inst/wp-includes/feed.php index 728a6fa..c406b7b 100644 --- a/wp-inst/wp-includes/feed-functions.php +++ b/wp-inst/wp-includes/feed.php @@ -161,4 +161,4 @@ function rss_enclosure() { } } -?> +?>
\ No newline at end of file diff --git a/wp-inst/wp-includes/functions-formatting.php b/wp-inst/wp-includes/formatting.php index 5af4df5..61cd1b2 100644 --- a/wp-inst/wp-includes/functions-formatting.php +++ b/wp-inst/wp-includes/formatting.php @@ -521,10 +521,11 @@ function format_to_post($content) { function zeroise($number,$threshold) { // function to add leading zeros when necessary return sprintf('%0'.$threshold.'s', $number); - } +} function backslashit($string) { + $string = preg_replace('/^([0-9])/', '\\\\\\\\\1', $string); $string = preg_replace('/([a-z])/i', '\\\\\1', $string); return $string; } diff --git a/wp-inst/wp-includes/functions.php b/wp-inst/wp-includes/functions.php index 64f795e..8a465e8 100644 --- a/wp-inst/wp-includes/functions.php +++ b/wp-inst/wp-includes/functions.php @@ -1,6 +1,6 @@ <?php -require_once(dirname(__FILE__).'/functions-compat.php'); +require_once(dirname(__FILE__).'/compat.php'); if ( !function_exists('_') ) { function _($string) { @@ -8,13 +8,6 @@ if ( !function_exists('_') ) { } } -function get_profile($field, $user = false) { - global $wpdb; - if ( !$user ) - $user = $wpdb->escape($_COOKIE[USER_COOKIE]); - return $wpdb->get_var("SELECT $field FROM $wpdb->users WHERE user_login = '$user'"); -} - function mysql2date($dateformatstring, $mysqlstring, $translate = true) { global $wp_locale; $m = $mysqlstring; @@ -37,12 +30,12 @@ function mysql2date($dateformatstring, $mysqlstring, $translate = true) { $datemeridiem = $wp_locale->get_meridiem(date('a', $i)); $datemeridiem_capital = $wp_locale->get_meridiem(date('A', $i)); $dateformatstring = ' '.$dateformatstring; - $dateformatstring = preg_replace("/([^\\\])D/", "\${1}".backslashit($dateweekday_abbrev), $dateformatstring); - $dateformatstring = preg_replace("/([^\\\])F/", "\${1}".backslashit($datemonth), $dateformatstring); - $dateformatstring = preg_replace("/([^\\\])l/", "\${1}".backslashit($dateweekday), $dateformatstring); - $dateformatstring = preg_replace("/([^\\\])M/", "\${1}".backslashit($datemonth_abbrev), $dateformatstring); - $dateformatstring = preg_replace("/([^\\\])a/", "\${1}".backslashit($datemeridiem), $dateformatstring); - $dateformatstring = preg_replace("/([^\\\])A/", "\${1}".backslashit($datemeridiem_capital), $dateformatstring); + $dateformatstring = preg_replace("/([^\\\])D/", "\\1".backslashit($dateweekday_abbrev), $dateformatstring); + $dateformatstring = preg_replace("/([^\\\])F/", "\\1".backslashit($datemonth), $dateformatstring); + $dateformatstring = preg_replace("/([^\\\])l/", "\\1".backslashit($dateweekday), $dateformatstring); + $dateformatstring = preg_replace("/([^\\\])M/", "\\1".backslashit($datemonth_abbrev), $dateformatstring); + $dateformatstring = preg_replace("/([^\\\])a/", "\\1".backslashit($datemeridiem), $dateformatstring); + $dateformatstring = preg_replace("/([^\\\])A/", "\\1".backslashit($datemeridiem_capital), $dateformatstring); $dateformatstring = substr($dateformatstring, 1, strlen($dateformatstring)-1); } @@ -80,12 +73,12 @@ function date_i18n($dateformatstring, $unixtimestamp) { $datemeridiem = $wp_locale->get_meridiem(date('a', $i)); $datemeridiem_capital = $wp_locale->get_meridiem(date('A', $i)); $dateformatstring = ' '.$dateformatstring; - $dateformatstring = preg_replace("/([^\\\])D/", "\${1}".backslashit($dateweekday_abbrev), $dateformatstring); - $dateformatstring = preg_replace("/([^\\\])F/", "\${1}".backslashit($datemonth), $dateformatstring); - $dateformatstring = preg_replace("/([^\\\])l/", "\${1}".backslashit($dateweekday), $dateformatstring); - $dateformatstring = preg_replace("/([^\\\])M/", "\${1}".backslashit($datemonth_abbrev), $dateformatstring); - $dateformatstring = preg_replace("/([^\\\])a/", "\${1}".backslashit($datemeridiem), $dateformatstring); - $dateformatstring = preg_replace("/([^\\\])A/", "\${1}".backslashit($datemeridiem_capital), $dateformatstring); + $dateformatstring = preg_replace("/([^\\\])D/", "\\1".backslashit($dateweekday_abbrev), $dateformatstring); + $dateformatstring = preg_replace("/([^\\\])F/", "\\1".backslashit($datemonth), $dateformatstring); + $dateformatstring = preg_replace("/([^\\\])l/", "\\1".backslashit($dateweekday), $dateformatstring); + $dateformatstring = preg_replace("/([^\\\])M/", "\\1".backslashit($datemonth_abbrev), $dateformatstring); + $dateformatstring = preg_replace("/([^\\\])a/", "\\1".backslashit($datemeridiem), $dateformatstring); + $dateformatstring = preg_replace("/([^\\\])A/", "\\1".backslashit($datemeridiem_capital), $dateformatstring); $dateformatstring = substr($dateformatstring, 1, strlen($dateformatstring)-1); } @@ -168,21 +161,6 @@ function get_lastpostmodified($timezone = 'server') { return $lastpostmodified; } -function user_pass_ok($user_login,$user_pass) { - global $cache_userdata; - if ( empty($cache_userdata[$user_login]) ) { - $userdata = get_userdatabylogin($user_login); - } else { - $userdata = $cache_userdata[$user_login]; - } - return (md5($user_pass) == $userdata->user_pass); -} - -function get_usernumposts($userid) { - global $wpdb; - return $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = '$userid' AND post_type = 'post' AND post_status = 'publish'"); -} - function maybe_unserialize($original) { if ( false !== $gm = @ unserialize($original) ) return $gm; @@ -243,22 +221,6 @@ function get_option($option) { return get_settings($option); } -function get_user_option( $option, $user = 0 ) { - global $wpdb; - - if ( empty($user) ) - $user = wp_get_current_user(); - else - $user = get_userdata($user); - - if ( isset( $user->{$wpdb->prefix . $option} ) ) // Blog specific - return $user->{$wpdb->prefix . $option}; - elseif ( isset( $user->{$option} ) ) // User specific and cross-blog - return $user->{$option}; - else // Blog global - return get_option( $option ); -} - function form_option($option) { echo htmlspecialchars( get_option($option), ENT_QUOTES ); } @@ -319,13 +281,6 @@ function update_option($option_name, $newvalue) { return false; } -function update_user_option( $user_id, $option_name, $newvalue, $global = false ) { - global $wpdb; - if ( !$global ) - $option_name = $wpdb->prefix . $option_name; - return update_usermeta( $user_id, $option_name, $newvalue ); -} - // thx Alex Stapleton, http://alex.vort-x.net/blog/ function add_option($name, $value = '', $description = '', $autoload = 'yes') { global $wpdb; @@ -357,303 +312,6 @@ function delete_option($name) { return true; } -function add_post_meta($post_id, $key, $value, $unique = false) { - global $wpdb, $post_meta_cache; - - if ( $unique ) { - if ( $wpdb->get_var("SELECT meta_key FROM $wpdb->postmeta WHERE meta_key -= '$key' AND post_id = '$post_id'") ) { - return false; - } - } - - $original = $value; - if ( is_array($value) || is_object($value) ) - $value = $wpdb->escape(serialize($value)); - - $wpdb->query("INSERT INTO $wpdb->postmeta (post_id,meta_key,meta_value) VALUES ('$post_id','$key','$value')"); - - $post_meta_cache['$post_id'][$key][] = $original; - - return true; -} - -function delete_post_meta($post_id, $key, $value = '') { - global $wpdb, $post_meta_cache; - - if ( empty($value) ) { - $meta_id = $wpdb->get_var("SELECT meta_id FROM $wpdb->postmeta WHERE -post_id = '$post_id' AND meta_key = '$key'"); - } else { - $meta_id = $wpdb->get_var("SELECT meta_id FROM $wpdb->postmeta WHERE -post_id = '$post_id' AND meta_key = '$key' AND meta_value = '$value'"); - } - - if ( !$meta_id ) - return false; - - if ( empty($value) ) { - $wpdb->query("DELETE FROM $wpdb->postmeta WHERE post_id = '$post_id' -AND meta_key = '$key'"); - unset($post_meta_cache['$post_id'][$key]); - } else { - $wpdb->query("DELETE FROM $wpdb->postmeta WHERE post_id = '$post_id' -AND meta_key = '$key' AND meta_value = '$value'"); - $cache_key = $post_meta_cache['$post_id'][$key]; - if ($cache_key) foreach ( $cache_key as $index => $data ) - if ( $data == $value ) - unset($post_meta_cache['$post_id'][$key][$index]); - } - - unset($post_meta_cache['$post_id'][$key]); - - return true; -} - -function get_post_meta($post_id, $key, $single = false) { - global $wpdb, $post_meta_cache; - - if ( isset($post_meta_cache[$post_id][$key]) ) { - if ( $single ) { - return maybe_unserialize( $post_meta_cache[$post_id][$key][0] ); - } else { - return maybe_unserialize( $post_meta_cache[$post_id][$key] ); - } - } - - $metalist = $wpdb->get_results("SELECT meta_value FROM $wpdb->postmeta WHERE post_id = '$post_id' AND meta_key = '$key'", ARRAY_N); - - $values = array(); - if ( $metalist ) { - foreach ($metalist as $metarow) { - $values[] = $metarow[0]; - } - } - - if ( $single ) { - if ( count($values) ) { - $return = maybe_unserialize( $values[0] ); - } else { - return ''; - } - } else { - $return = $values; - } - - return maybe_unserialize($return); -} - -function update_post_meta($post_id, $key, $value, $prev_value = '') { - global $wpdb, $post_meta_cache; - - $original_value = $value; - if ( is_array($value) || is_object($value) ) - $value = $wpdb->escape(serialize($value)); - - $original_prev = $prev_value; - if ( is_array($prev_value) || is_object($prev_value) ) - $prev_value = $wpdb->escape(serialize($prev_value)); - - if (! $wpdb->get_var("SELECT meta_key FROM $wpdb->postmeta WHERE meta_key -= '$key' AND post_id = '$post_id'") ) { - return false; - } - - if ( empty($prev_value) ) { - $wpdb->query("UPDATE $wpdb->postmeta SET meta_value = '$value' WHERE -meta_key = '$key' AND post_id = '$post_id'"); - $cache_key = $post_meta_cache['$post_id'][$key]; - if ( !empty($cache_key) ) - foreach ($cache_key as $index => $data) - $post_meta_cache['$post_id'][$key][$index] = $original_value; - } else { - $wpdb->query("UPDATE $wpdb->postmeta SET meta_value = '$value' WHERE -meta_key = '$key' AND post_id = '$post_id' AND meta_value = '$prev_value'"); - $cache_key = $post_meta_cache['$post_id'][$key]; - if ( !empty($cache_key) ) - foreach ($cache_key as $index => $data) - if ( $data == $original_prev ) - $post_meta_cache['$post_id'][$key][$index] = $original_value; - } - - return true; -} - -// Retrieves post data given a post ID or post object. -// Handles post caching. -function &get_post(&$post, $output = OBJECT) { - global $post_cache, $wpdb; - - if ( empty($post) ) { - if ( isset($GLOBALS['post']) ) - $_post = & $GLOBALS['post']; - else - $_post = null; - } elseif ( is_object($post) ) { - if ( 'page' == $post->post_type ) - return get_page($post, $output); - if ( !isset($post_cache[$post->ID]) ) - $post_cache[$post->ID] = &$post; - $_post = & $post_cache[$post->ID]; - } else { - if ( $_post = wp_cache_get($post, 'pages') ) - return get_page($_post, $output); - elseif ( isset($post_cache[$post]) ) - $_post = & $post_cache[$post]; - else { - $query = "SELECT * FROM $wpdb->posts WHERE ID = '$post' LIMIT 1"; - $_post = & $wpdb->get_row($query); - if ( 'page' == $_post->post_type ) - return get_page($_post, $output); - $post_cache[$post] = & $_post; - } - } - - if ( defined(WP_IMPORTING) ) - unset($post_cache); - - if ( $output == OBJECT ) { - return $_post; - } elseif ( $output == ARRAY_A ) { - return get_object_vars($_post); - } elseif ( $output == ARRAY_N ) { - return array_values(get_object_vars($_post)); - } else { - return $_post; - } -} - -function &get_children($post = 0, $output = OBJECT) { - global $post_cache, $wpdb; - - if ( empty($post) ) { - if ( isset($GLOBALS['post']) ) - $post_parent = & $GLOBALS['post']->post_parent; - else - return false; - } elseif ( is_object($post) ) { - $post_parent = $post->post_parent; - } else { - $post_parent = $post; - } - - $post_parent = (int) $post_parent; - - $query = "SELECT * FROM $wpdb->posts WHERE post_parent = $post_parent"; - - $children = $wpdb->get_results($query); - - if ( $children ) { - foreach ( $children as $key => $child ) { - $post_cache[$child->ID] =& $children[$key]; - $kids[$child->ID] =& $children[$key]; - } - } else { - return false; - } - - if ( $output == OBJECT ) { - return $kids; - } elseif ( $output == ARRAY_A ) { - foreach ( $kids as $kid ) - $weeuns[$kid->ID] = get_object_vars($kids[$kid->ID]); - return $weeuns; - } elseif ( $output == ARRAY_N ) { - foreach ( $kids as $kid ) - $babes[$kid->ID] = array_values(get_object_vars($kids[$kid->ID])); - return $babes; - } else { - return $kids; - } -} - -function get_page_by_path($page_path, $output = OBJECT) { - global $wpdb; - $page_path = rawurlencode(urldecode($page_path)); - $page_path = str_replace('%2F', '/', $page_path); - $page_path = str_replace('%20', ' ', $page_path); - $page_paths = '/' . trim($page_path, '/'); - $leaf_path = sanitize_title(basename($page_paths)); - $page_paths = explode('/', $page_paths); - foreach($page_paths as $pathdir) - $full_path .= ($pathdir!=''?'/':'') . sanitize_title($pathdir); - - $pages = $wpdb->get_results("SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_name = '$leaf_path' AND post_type='page'"); - - if ( empty($pages) ) - return NULL; - - foreach ($pages as $page) { - $path = '/' . $leaf_path; - $curpage = $page; - while ($curpage->post_parent != 0) { - $curpage = $wpdb->get_row("SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE ID = '$curpage->post_parent' and post_type='page'"); - $path = '/' . $curpage->post_name . $path; - } - - if ( $path == $full_path ) - return get_page($page->ID, $output); - } - - return NULL; -} - -// Retrieves page data given a page ID or page object. -// Handles page caching. -function &get_page(&$page, $output = OBJECT) { - global $wpdb; - - if ( empty($page) ) { - if ( isset($GLOBALS['page']) ) { - $_page = & $GLOBALS['page']; - wp_cache_add($_page->ID, $_page, 'pages'); - } else { - $_page = null; - } - } elseif ( is_object($page) ) { - if ( 'post' == $page->post_type ) - return get_post($page, $output); - wp_cache_add($page->ID, $page, 'pages'); - $_page = $page; - } else { - if ( isset($GLOBALS['page']) && ($page == $GLOBALS['page']->ID) ) { - $_page = & $GLOBALS['page']; - wp_cache_add($_page->ID, $_page, 'pages'); - } elseif ( $_page = $GLOBALS['post_cache'][$page] ) { - return get_post($page, $output); - } elseif ( $_page = wp_cache_get($page, 'pages') ) { - // Got it. - } else { - $query = "SELECT * FROM $wpdb->posts WHERE ID= '$page' LIMIT 1"; - $_page = & $wpdb->get_row($query); - if ( 'post' == $_page->post_type ) - return get_post($_page, $output); - wp_cache_add($_page->ID, $_page, 'pages'); - } - } - - if ( $output == OBJECT ) { - return $_page; - } elseif ( $output == ARRAY_A ) { - return get_object_vars($_page); - } elseif ( $output == ARRAY_N ) { - return array_values(get_object_vars($_page)); - } else { - return $_page; - } -} - -function get_all_page_ids() { - global $wpdb; - - if ( ! $page_ids = wp_cache_get('all_page_ids', 'pages') ) { - $page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'page'"); - wp_cache_add('all_page_ids', $page_ids, 'pages'); - } - - return $page_ids; -} - function gzip_compression() { if ( !get_settings('gzipcompression') ) return false; @@ -911,62 +569,6 @@ function wp_get_http_headers( $url, $red = 1 ) { return $headers; } -// Setup global post data. -function setup_postdata($post) { - global $id, $postdata, $authordata, $day, $page, $pages, $multipage, $more, $numpages, $wp_query; - global $pagenow; - - $id = $post->ID; - - $authordata = get_userdata($post->post_author); - - $day = mysql2date('d.m.y', $post->post_date); - $currentmonth = mysql2date('m', $post->post_date); - $numpages = 1; - $page = get_query_var('page'); - if ( !$page ) - $page = 1; - if ( is_single() || is_page() ) - $more = 1; - $content = $post->post_content; - if ( preg_match('/<!--nextpage-->/', $content) ) { - if ( $page > 1 ) - $more = 1; - $multipage = 1; - $content = str_replace("\n<!--nextpage-->\n", '<!--nextpage-->', $content); - $content = str_replace("\n<!--nextpage-->", '<!--nextpage-->', $content); - $content = str_replace("<!--nextpage-->\n", '<!--nextpage-->', $content); - $pages = explode('<!--nextpage-->', $content); - $numpages = count($pages); - } else { - $pages[0] = $post->post_content; - $multipage = 0; - } - return true; -} - -// Setup global user vars. Used by set_current_user() for back compat. -function setup_userdata($user_id = '') { - global $user_login, $userdata, $user_level, $user_ID, $user_email, $user_url, $user_pass_md5, $user_identity; - - if ( '' == $user_id ) - $user = wp_get_current_user(); - else - $user = new WP_User($user_id); - - if ( 0 == $user->ID ) - return; - - $userdata = $user->data; - $user_login = $user->user_login; - $user_level = $user->user_level; - $user_ID = $user->ID; - $user_email = $user->user_email; - $user_url = $user->user_url; - $user_pass_md5 = md5($user->user_pass); - $user_identity = $user->display_name; -} - function is_new_day() { global $day, $previousday; if ( $day != $previousday ) { @@ -1112,86 +714,6 @@ function remove_action($tag, $function_to_remove, $priority = 10, $accepted_args remove_filter($tag, $function_to_remove, $priority, $accepted_args); } -function get_page_uri($page_id) { - $page = get_page($page_id); - $uri = urldecode($page->post_name); - - // A page cannot be it's own parent. - if ( $page->post_parent == $page->ID ) - return $uri; - - while ($page->post_parent != 0) { - $page = get_page($page->post_parent); - $uri = urldecode($page->post_name) . "/" . $uri; - } - - return $uri; -} - -function get_posts($args) { - global $wpdb; - - if ( is_array($args) ) - $r = &$args; - else - parse_str($args, $r); - - $defaults = array('numberposts' => 5, 'offset' => 0, 'category' => '', - 'orderby' => 'post_date', 'order' => 'DESC', 'include' => '', 'exclude' => '', 'meta_key' => '', 'meta_value' =>''); - $r = array_merge($defaults, $r); - extract($r); - - $inclusions = ''; - if ( !empty($include) ) { - $offset = 0; //ignore offset, category, exclude, meta_key, and meta_value params if using include - $category = ''; - $exclude = ''; - $meta_key = ''; - $meta_value = ''; - $incposts = preg_split('/[\s,]+/',$include); - $numberposts = count($incposts); // only the number of posts included - if ( count($incposts) ) { - foreach ( $incposts as $incpost ) { - if (empty($inclusions)) - $inclusions = ' AND ( ID = ' . intval($incpost) . ' '; - else - $inclusions .= ' OR ID = ' . intval($incpost) . ' '; - } - } - } - if (!empty($inclusions)) - $inclusions .= ')'; - - $exclusions = ''; - if ( !empty($exclude) ) { - $exposts = preg_split('/[\s,]+/',$exclude); - if ( count($exposts) ) { - foreach ( $exposts as $expost ) { - if (empty($exclusions)) - $exclusions = ' AND ( ID <> ' . intval($expost) . ' '; - else - $exclusions .= ' AND ID <> ' . intval($expost) . ' '; - } - } - } - if (!empty($exclusions)) - $exclusions .= ')'; - - $query ="SELECT DISTINCT * FROM $wpdb->posts " ; - $query .= ( empty( $category ) ? "" : ", $wpdb->post2cat " ) ; - $query .= ( empty( $meta_key ) ? "" : ", $wpdb->postmeta " ) ; - $query .= " WHERE (post_type = 'post' AND post_status = 'publish') $exclusions $inclusions " ; - $query .= ( empty( $category ) ? "" : "AND ($wpdb->posts.ID = $wpdb->post2cat.post_id AND $wpdb->post2cat.category_id = " . $category. ") " ) ; - $query .= ( empty( $meta_key ) | empty($meta_value) ? "" : " AND ($wpdb->posts.ID = $wpdb->postmeta.post_id AND $wpdb->postmeta.meta_key = '$meta_key' AND $wpdb->postmeta.meta_value = '$meta_value' )" ) ; - $query .= " GROUP BY $wpdb->posts.ID ORDER BY " . $orderby . " " . $order . " LIMIT " . $offset . ',' . $numberposts ; - - $posts = $wpdb->get_results($query); - - update_post_caches($posts); - - return $posts; -} - function update_post_cache(&$posts) { global $post_cache; @@ -1295,14 +817,6 @@ function update_category_cache() { return true; } -function wp_head() { - do_action('wp_head'); -} - -function wp_footer() { - do_action('wp_footer'); -} - /* add_query_arg: Returns a modified querystring by adding a single key & value or an associative array. @@ -1316,17 +830,24 @@ add_query_arg(associative_array, oldquery_or_uri) function add_query_arg() { $ret = ''; if ( is_array(func_get_arg(0)) ) { - if ( @func_num_args() < 2 ) + if ( @func_num_args() < 2 || '' == @func_get_arg(1) ) $uri = $_SERVER['REQUEST_URI']; else $uri = @func_get_arg(1); } else { - if ( @func_num_args() < 3 ) + if ( @func_num_args() < 3 || '' == @func_get_arg(2) ) $uri = $_SERVER['REQUEST_URI']; else $uri = @func_get_arg(2); } + if ( preg_match('|^https?://|i', $uri, $matches) ) { + $protocol = $matches[0]; + $uri = substr($uri, strlen($protocol)); + } else { + $protocol = ''; + } + if ( strstr($uri, '?') ) { $parts = explode('?', $uri, 2); if ( 1 == count($parts) ) { @@ -1336,8 +857,7 @@ function add_query_arg() { $base = $parts[0] . '?'; $query = $parts[1]; } - } - else if ( strstr($uri, '/') ) { + } else if ( strstr($uri, '/') ) { $base = $uri . '?'; $query = ''; } else { @@ -1360,11 +880,28 @@ function add_query_arg() { $ret .= "$k=$v"; } } - $ret = $base . $ret; + $ret = $protocol . $base . $ret; + if ( get_magic_quotes_gpc() ) + $ret = stripslashes($ret); // parse_str() adds slashes if magicquotes is on. See: http://php.net/parse_str return trim($ret, '?'); } -function remove_query_arg($key, $query) { +/* +remove_query_arg: Returns a modified querystring by removing +a single key or an array of keys. +Omitting oldquery_or_uri uses the $_SERVER value. + +Parameters: +remove_query_arg(removekey, [oldquery_or_uri]) or +remove_query_arg(removekeyarray, [oldquery_or_uri]) +*/ + +function remove_query_arg($key, $query='') { + if ( is_array($key) ) { // removing multiple keys + foreach ( (array) $key as $k ) + $query = add_query_arg($k, '', $query); + return $query; + } return add_query_arg($key, '', $query); } @@ -1435,99 +972,6 @@ function nocache_headers() { @ header('Pragma: no-cache'); } -function get_usermeta( $user_id, $meta_key = '') { - global $wpdb; - $user_id = (int) $user_id; - - $user = get_userdata( $user_id ); - - if ( $meta_key && isset($user->{$meta_key}) ) - return $user->{$meta_key}; - - if ( !empty($meta_key) ) { - $meta_key = preg_replace('|a-z0-9_|i', '', $meta_key); - $metas = $wpdb->get_results("SELECT meta_key, meta_value FROM $wpdb->usermeta WHERE user_id = '$user_id' AND meta_key = '$meta_key'"); - } else { - $metas = $wpdb->get_results("SELECT meta_key, meta_value FROM $wpdb->usermeta WHERE user_id = '$user_id'"); - } - - if ( empty($metas) ) { - if ( empty($meta_key) ) - return array(); - else - return ''; - } - - foreach ($metas as $index => $meta) { - @ $value = unserialize($meta->meta_value); - if ( $value === FALSE ) - $value = $meta->meta_value; - - $values[] = $value; - } - - if ( count($values) == 1 ) - return $values[0]; - else - return $values; -} - -function update_usermeta( $user_id, $meta_key, $meta_value ) { - global $wpdb; - if ( !is_numeric( $user_id ) ) - return false; - $meta_key = preg_replace('|[^a-z0-9_]|i', '', $meta_key); - - if ( is_array($meta_value) || is_object($meta_value) ) - $meta_value = serialize($meta_value); - $meta_value = trim( $meta_value ); - - if (empty($meta_value)) { - return delete_usermeta($user_id, $meta_key); - } - - $cur = $wpdb->get_row("SELECT * FROM $wpdb->usermeta WHERE user_id = '$user_id' AND meta_key = '$meta_key'"); - if ( !$cur ) { - $wpdb->query("INSERT INTO $wpdb->usermeta ( user_id, meta_key, meta_value ) - VALUES - ( '$user_id', '$meta_key', '$meta_value' )"); - } else if ( $cur->meta_value != $meta_value ) { - $wpdb->query("UPDATE $wpdb->usermeta SET meta_value = '$meta_value' WHERE user_id = '$user_id' AND meta_key = '$meta_key'"); - } else { - return false; - } - - $user = get_userdata($user_id); - wp_cache_delete($user_id, 'users'); - wp_cache_delete($user->user_login, 'userlogins'); - wp_cache_delete( md5($user_id . $meta_key), 'usermeta' ); - - return true; -} - -function delete_usermeta( $user_id, $meta_key, $meta_value = '' ) { - global $wpdb; - if ( !is_numeric( $user_id ) ) - return false; - $meta_key = preg_replace('|[^a-z0-9_]|i', '', $meta_key); - - if ( is_array($meta_value) || is_object($meta_value) ) - $meta_value = serialize($meta_value); - $meta_value = trim( $meta_value ); - - if ( ! empty($meta_value) ) - $wpdb->query("DELETE FROM $wpdb->usermeta WHERE user_id = '$user_id' AND meta_key = '$meta_key' AND meta_value = '$meta_value'"); - else - $wpdb->query("DELETE FROM $wpdb->usermeta WHERE user_id = '$user_id' AND meta_key = '$meta_key'"); - - $user = get_userdata($user_id); - wp_cache_delete($user_id, 'users'); - wp_cache_delete($user->user_login, 'userlogins'); - wp_cache_delete( md5($user_id . $meta_key), 'usermeta' ); - - return true; -} - function register_activation_hook($file, $function) { $file = plugin_basename($file); @@ -1629,4 +1073,189 @@ function wp_nonce_field($action = -1) { echo '<input type="hidden" name="_wpnonce" value="' . wp_create_nonce($action) . '" />'; } +function wp_mkdir_p($target) { + // from php.net/mkdir user contributed notes + if (file_exists($target)) { + if (! @ is_dir($target)) + return false; + else + return true; + } + + // Attempting to create the directory may clutter up our display. + if (@ mkdir($target)) { + $stat = @ stat(dirname($target)); + $dir_perms = $stat['mode'] & 0007777; // Get the permission bits. + @ chmod($target, $dir_perms); + return true; + } else { + if ( is_dir(dirname($target)) ) + return false; + } + + // If the above failed, attempt to create the parent node, then try again. + if (wp_mkdir_p(dirname($target))) + return wp_mkdir_p($target); + + return false; +} + +// Returns an array containing the current upload directory's path and url, or an error message. +function wp_upload_dir() { + $siteurl = get_settings('siteurl'); + //prepend ABSPATH to $dir and $siteurl to $url if they're not already there + $path = str_replace(ABSPATH, '', trim(get_settings('upload_path'))); + $dir = ABSPATH . $path; + $url = trailingslashit($siteurl) . $path; + + if ( $dir == ABSPATH ) { //the option was empty + $dir = ABSPATH . 'wp-content/uploads'; + } + + if ( defined('UPLOADS') ) { + $dir = ABSPATH . UPLOADS; + $url = trailingslashit($siteurl) . UPLOADS; + } + + if ( get_settings('uploads_use_yearmonth_folders')) { + // Generate the yearly and monthly dirs + $time = current_time( 'mysql' ); + $y = substr( $time, 0, 4 ); + $m = substr( $time, 5, 2 ); + $dir = $dir . "/$y/$m"; + $url = $url . "/$y/$m"; + } + + // Make sure we have an uploads dir + if ( ! wp_mkdir_p( $dir ) ) { + $message = sprintf(__('Unable to create directory %s. Is its parent directory writable by the server?'), $dir); + return array('error' => $message); + } + + $uploads = array('path' => $dir, 'url' => $url, 'error' => false); + return apply_filters('upload_dir', $uploads); +} + +function wp_upload_bits($name, $type, $bits) { + if ( empty($name) ) + return array('error' => "Empty filename"); + + $upload = wp_upload_dir(); + + if ( $upload['error'] !== false ) + return $upload; + + $number = ''; + $filename = $name; + $path_parts = pathinfo($filename); + $ext = $path_parts['extension']; + if ( empty($ext) ) + $ext = ''; + else + $ext = ".$ext"; + while ( file_exists($upload['path'] . "/$filename") ) { + if ( '' == "$number$ext" ) + $filename = $filename . ++$number . $ext; + else + $filename = str_replace("$number$ext", ++$number . $ext, $filename); + } + + $new_file = $upload['path'] . "/$filename"; + if ( ! wp_mkdir_p( dirname($new_file) ) ) { + $message = sprintf(__('Unable to create directory %s. Is its parent directory writable by the server?'), dirname($new_file)); + return array('error' => $message); + } + + $ifp = @ fopen($new_file, 'wb'); + if ( ! $ifp ) + return array('error' => "Could not write file $new_file."); + + $success = @ fwrite($ifp, $bits); + fclose($ifp); + // Set correct file permissions + $stat = @ stat(dirname($new_file)); + $perms = $stat['mode'] & 0007777; + $perms = $perms & 0000666; + @ chmod($new_file, $perms); + + // Compute the URL + $url = $upload['url'] . "/$filename"; + + return array('file' => $new_file, 'url' => $url, 'error' => false); +} + +function do_trackbacks($post_id) { + global $wpdb; + + $post = $wpdb->get_row("SELECT * FROM $wpdb->posts WHERE ID = $post_id"); + $to_ping = get_to_ping($post_id); + $pinged = get_pung($post_id); + if ( empty($to_ping) ) { + $wpdb->query("UPDATE $wpdb->posts SET to_ping = '' WHERE ID = '$post_id'"); + return; + } + + if (empty($post->post_excerpt)) + $excerpt = apply_filters('the_content', $post->post_content); + else + $excerpt = apply_filters('the_excerpt', $post->post_excerpt); + $excerpt = str_replace(']]>', ']]>', $excerpt); + $excerpt = strip_tags($excerpt); + if ( function_exists('mb_strcut') ) // For international trackbacks + $excerpt = mb_strcut($excerpt, 0, 252, get_settings('blog_charset')) . '...'; + else + $excerpt = substr($excerpt, 0, 252) . '...'; + + $post_title = apply_filters('the_title', $post->post_title); + $post_title = strip_tags($post_title); + + if ($to_ping) : foreach ($to_ping as $tb_ping) : + $tb_ping = trim($tb_ping); + if ( !in_array($tb_ping, $pinged) ) { + trackback($tb_ping, $post_title, $excerpt, $post_id); + $pinged[] = $tb_ping; + } else { + $wpdb->query("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, '$tb_ping', '')) WHERE ID = '$post_id'"); + } + endforeach; endif; +} + +function do_all_pings() { + global $wpdb; + + // Do pingbacks + while ($ping = $wpdb->get_row("SELECT * FROM {$wpdb->posts}, {$wpdb->postmeta} WHERE {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id AND {$wpdb->postmeta}.meta_key = '_pingme' LIMIT 1")) { + $wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE post_id = {$ping->ID} AND meta_key = '_pingme';"); + pingback($ping->post_content, $ping->ID); + } + + // Do Enclosures + while ($enclosure = $wpdb->get_row("SELECT * FROM {$wpdb->posts}, {$wpdb->postmeta} WHERE {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id AND {$wpdb->postmeta}.meta_key = '_encloseme' LIMIT 1")) { + $wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE post_id = {$enclosure->ID} AND meta_key = '_encloseme';"); + do_enclose($enclosure->post_content, $enclosure->ID); + } + + // Do Trackbacks + $trackbacks = $wpdb->get_results("SELECT ID FROM $wpdb->posts WHERE CHAR_LENGTH(TRIM(to_ping)) > 7 AND post_status = 'publish'"); + if ( is_array($trackbacks) ) { + foreach ( $trackbacks as $trackback ) { + do_trackbacks($trackback->ID); + } + } + + //Do Update Services/Generic Pings + generic_ping(); +} + +function wp_proxy_check($ipnum) { + if ( get_option('open_proxy_check') && isset($ipnum) ) { + $rev_ip = implode( '.', array_reverse( explode( '.', $ipnum ) ) ); + $lookup = $rev_ip . '.opm.blitzed.org.'; + if ( $lookup != gethostbyname( $lookup ) ) + return true; + } + + return false; +} + ?> diff --git a/wp-inst/wp-includes/template-functions-general.php b/wp-inst/wp-includes/general-template.php index 1830c4d..4a80d8b 100644 --- a/wp-inst/wp-includes/template-functions-general.php +++ b/wp-inst/wp-includes/general-template.php @@ -326,11 +326,7 @@ function get_archives($type='', $limit='', $format='html', $before = '', $after $add_minutes = intval(60 * (get_settings('gmt_offset') - $add_hours)); if ( 'monthly' == $type ) { - $arcresults = wp_cache_get( md5('archives' . $type . $limit), 'general'); - if ( !$arcresults ) { - $arcresults = $wpdb->get_results("SELECT DISTINCT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC" . $limit); - wp_cache_set( md5('archives' . $type . $limit), $arcresults, 'general', 360 ); - } + $arcresults = $wpdb->get_results("SELECT DISTINCT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC" . $limit); if ( $arcresults ) { $afterafter = $after; foreach ( $arcresults as $arcresult ) { @@ -698,14 +694,88 @@ function the_weekday_date($before='',$after='') { echo $the_weekday_date; } +function wp_head() { + do_action('wp_head'); +} + +function wp_footer() { + do_action('wp_footer'); +} + function rsd_link() { echo '<link rel="EditURI" type="application/rsd+xml" title="RSD" href="' . get_bloginfo('wpurl') . "/xmlrpc.php?rsd\" />\n"; } function noindex() { - global $current_blog; // If the blog is not public, tell robots to go away. - if ( 0 == $current_blog->public ) + if ( ! get_option('blog_public') ) echo '<meta name="robots" content="noindex,nofollow" />' . "\n"; } + +/** + * Places a textarea according to the current user's preferences, filled with $content. + * Also places a script block that enables tabbing between Title and Content. + * + * @param string Editor contents + * @param string (optional) Previous form field's ID (for tabbing support) + */ +function the_editor($content, $id = 'content', $prev_id = 'title') { + $rows = get_settings('default_post_edit_rows'); + if (($rows < 3) || ($rows > 100)) + $rows = 12; + + $rows = "rows='$rows'"; + + the_quicktags(); + + if ( user_can_richedit() ) + add_filter('the_editor_content', 'wp_richedit_pre'); + + $the_editor = apply_filters('the_editor', "<div><textarea class='mceEditor' $rows cols='40' name='$id' tabindex='2' id='$id'>%s</textarea></div>\n"); + $the_editor_content = apply_filters('the_editor_content', $content); + + printf($the_editor, $the_editor_content); + + ?> + <script type="text/javascript"> + //<!-- + edCanvas = document.getElementById('<?php echo $id; ?>'); + <?php if ( user_can_richedit() ) : ?> + // This code is meant to allow tabbing from Title to Post (TinyMCE). + if ( tinyMCE.isMSIE ) + document.getElementById('<?php echo $prev_id; ?>').onkeydown = function (e) + { + e = e ? e : window.event; + if (e.keyCode == 9 && !e.shiftKey && !e.controlKey && !e.altKey) { + var i = tinyMCE.selectedInstance; + if(typeof i == 'undefined') + return true; + tinyMCE.execCommand("mceStartTyping"); + this.blur(); + i.contentWindow.focus(); + e.returnValue = false; + return false; + } + } + else + document.getElementById('<?php echo $prev_id; ?>').onkeypress = function (e) + { + e = e ? e : window.event; + if (e.keyCode == 9 && !e.shiftKey && !e.controlKey && !e.altKey) { + var i = tinyMCE.selectedInstance; + if(typeof i == 'undefined') + return true; + tinyMCE.execCommand("mceStartTyping"); + this.blur(); + i.contentWindow.focus(); + e.returnValue = false; + return false; + } + } + <?php endif; ?> + //--> + </script> + <?php +} + ?> diff --git a/wp-inst/wp-includes/js/dbx-key.js b/wp-inst/wp-includes/js/dbx-key.js deleted file mode 100644 index f7155de..0000000 --- a/wp-inst/wp-includes/js/dbx-key.js +++ /dev/null @@ -1,39 +0,0 @@ - -//initialisation function -addLoadEvent( function() -{ - //create new docking boxes group - var meta = new dbxGroup( - 'grabit', // container ID [/-_a-zA-Z0-9/] - 'vertical', // orientation ['vertical'|'horizontal'] - '10', // drag threshold ['n' pixels] - 'no', // restrict drag movement to container axis ['yes'|'no'] - '10', // animate re-ordering [frames per transition, or '0' for no effect] - 'yes', // include open/close toggle buttons ['yes'|'no'] - 'closed', // default state ['open'|'closed'] - 'open', // word for "open", as in "open this box" - 'close', // word for "close", as in "close this box" - 'click-down and drag to move this box', // sentence for "move this box" by mouse - 'click to %toggle% this box', // pattern-match sentence for "(open|close) this box" by mouse - 'use the arrow keys to move this box', // sentence for "move this box" by keyboard - ', or press the enter key to %toggle% it', // pattern-match sentence-fragment for "(open|close) this box" by keyboard - '%mytitle% [%dbxtitle%]' // pattern-match syntax for title-attribute conflicts - ); - - var advanced = new dbxGroup( - 'advancedstuff', // container ID [/-_a-zA-Z0-9/] - 'vertical', // orientation ['vertical'|'horizontal'] - '10', // drag threshold ['n' pixels] - 'yes', // restrict drag movement to container axis ['yes'|'no'] - '10', // animate re-ordering [frames per transition, or '0' for no effect] - 'yes', // include open/close toggle buttons ['yes'|'no'] - 'closed', // default state ['open'|'closed'] - 'open', // word for "open", as in "open this box" - 'close', // word for "close", as in "close this box" - 'click-down and drag to move this box', // sentence for "move this box" by mouse - 'click to %toggle% this box', // pattern-match sentence for "(open|close) this box" by mouse - 'use the arrow keys to move this box', // sentence for "move this box" by keyboard - ', or press the enter key to %toggle% it', // pattern-match sentence-fragment for "(open|close) this box" by keyboard - '%mytitle% [%dbxtitle%]' // pattern-match syntax for title-attribute conflicts - ); -}); diff --git a/wp-inst/wp-includes/js/dbx.js b/wp-inst/wp-includes/js/dbx.js index c6312e9..b75f897 100644 --- a/wp-inst/wp-includes/js/dbx.js +++ b/wp-inst/wp-includes/js/dbx.js @@ -1,6 +1,6 @@ -// DBX2.01 :: Docking Boxes (dbx) +// DBX2.02 :: Docking Boxes (dbx) // ***************************************************** // DOM scripting by brothercake -- http://www.brothercake.com/ // GNU Lesser General Public License -- http://www.gnu.org/licenses/lgpl.html //****************************************************** -var dbx;function dbxManager(sid){dbx = this;if(!/^[-_a-z0-9]+$/i.test(sid)) { alert('Error from dbxManager:\n"' + sid + '" is an invalid session ID'); return; }this.supported = !(document.getElementsByTagName('*').length == 0 || (navigator.vendor == 'KDE' && typeof window.sidebar == 'undefined'));if(!this.supported) { return; }this.etype = typeof document.addEventListener != 'undefined' ? 'addEventListener' : typeof document.attachEvent != 'undefined' ? 'attachEvent' : 'none';this.eprefix = (this.etype == 'attachEvent' ? 'on' : '');if(typeof window.opera != 'undefined' && parseFloat(navigator.userAgent.toLowerCase().split(/opera[\/ ]/)[1].split(' ')[0], 10) < 7.5){this.etype = 'none';}if(this.etype == 'none') { this.supported = false; return; }this.running = 0;this.sid = sid;this.savedata = {};this.cookiestate = this.getCookieState();};dbxManager.prototype.setCookieState = function(){var now = new Date();now.setTime(now.getTime() + (365*24*60*60*1000));var str = '';for(j in this.savedata){if(typeof this.savedata[j]!='function'){str += j + '=' + this.savedata[j] + '&'}}this.state = str.replace(/^(.+)&$/, '$1');if(typeof this.onstatechange == 'undefined' || this.onstatechange()){document.cookie = 'dbx-' + this.sid + '='+ this.state+ '; expires=' + now.toGMTString()+ '; path=/';}};dbxManager.prototype.getCookieState = function(){this.cookiestate = null;if(document.cookie){if(document.cookie.indexOf('dbx-' + this.sid)!=-1){this.cookie = document.cookie.split('dbx-' + this.sid + '=')[1].split('&');for(var i in this.cookie){if(typeof this.cookie[i]!='function'){this.cookie[i] = this.cookie[i].split('=');this.cookie[i][1] = this.cookie[i][1].split(',');}}this.cookiestate = {};for(i in this.cookie){if(typeof this.cookie[i]!='function'){this.cookiestate[this.cookie[i][0]] = this.cookie[i][1];}}}}return this.cookiestate;};dbxManager.prototype.addDataMember = function(gid, order){this.savedata[gid] = order;};dbxManager.prototype.createElement = function(tag){return typeof document.createElementNS != 'undefined' ? document.createElementNS('http://www.w3.org/1999/xhtml', tag) : document.createElement(tag);};dbxManager.prototype.getTarget = function(e, pattern, node){if(typeof node != 'undefined'){var target = node;}else{target = typeof e.target != 'undefined' ? e.target : e.srcElement;}var regex = new RegExp(pattern, '');while(!regex.test(target.className)){target = target.parentNode;}return target;};function dbxGroup(gid, dir, thresh, fix, ani, togs, def, open, close, move, toggle, kmove, ktoggle, syntax){if(!/^[-_a-z0-9]+$/i.test(gid)) { alert('Error from dbxGroup:\n"' + gid + '" is an invalid container ID'); return; }this.container = document.getElementById(gid);if(this.container == null || !dbx.supported) { return; }var self = this;this.gid = gid;this.dragok = false;this.box = null;this.vertical = dir == 'vertical';this.threshold = parseInt(thresh, 10);this.restrict = fix == 'yes';this.resolution = parseInt(ani, 10);this.toggles = togs == 'yes';this.defopen = def != 'closed';this.vocab = {'open' : open,'close' : close,'move' : move,'toggle' : toggle,'kmove' : kmove,'ktoggle' : ktoggle,'syntax' : syntax};this.container.style.position = 'relative';this.container.style.display = 'block';if(typeof window.opera != 'undefined'){this.container.style.display = 'run-in';}this.boxes = [];this.buttons = [];this.order = [];this.eles = this.container.getElementsByTagName('*');for(var i=0; i<this.eles.length; i++){if(/dbx\-box/i.test(this.eles[i].className) && !/dbx\-dummy/i.test(this.eles[i].className)){this.eles[i].style.position = 'relative';this.eles[i].style.display = 'block';this.boxes.push(this.eles[i]);this.eles[i].className += ' dbx-box-open';this.eles[i].className += ' dbxid' + this.order.length;this.order.push(this.order.length.toString() + '+');this.eles[i][dbx.etype](dbx.eprefix + 'mousedown', function(e){if(!e) { e = window.event; }self.mousedown(e, dbx.getTarget(e, 'dbx\-box'));}, false);}if(/dbx\-handle/i.test(this.eles[i].className)){this.eles[i].style.position = 'relative';this.eles[i].style.display = 'block';this.eles[i].className += ' dbx-handle-cursor';this.eles[i].setAttribute('title', this.eles[i].getAttribute('title') == null || this.eles[i].title == '' ? this.vocab.move : this.vocab.syntax.replace('%mytitle%', this.eles[i].title).replace('%dbxtitle%', this.vocab.move));if(this.toggles){this.buttons.push(this.addToggleBehavior(this.eles[i]));}else{this.eles[i][dbx.etype](dbx.eprefix + 'key' + (typeof document.uniqueID != 'undefined' || navigator.vendor == 'Apple Computer, Inc.' ? 'down' : 'press'), function(e){if(!e) { e = window.event; }return self.keypress(e, dbx.getTarget(e, 'dbx\-handle'));}, false);this.eles[i][dbx.etype](dbx.eprefix + 'focus', function(e){if(!e) { e = window.event; }self.createTooltip(null, dbx.getTarget(e, 'dbx\-handle'));}, false);this.eles[i][dbx.etype](dbx.eprefix + 'blur', function(){self.removeTooltip();}, false);}}}dbx.addDataMember(this.gid, this.order.join(','));var dummy = this.container.appendChild(dbx.createElement('span'));dummy.className = 'dbx-box dbx-dummy';dummy.style.display = 'block';dummy.style.width = '0';dummy.style.height = '0';dummy.style.overflow = 'hidden';if(this.vertical) { dummy.className += ' dbx-offdummy'; }this.boxes.push(dummy);if(dbx.cookiestate != null && typeof dbx.cookiestate[this.gid] != 'undefined'){var num = dbx.cookiestate[this.gid].length;if(num == this.boxes.length - 1){for(i=0; i<num; i++){var index = parseInt(dbx.cookiestate[this.gid][i], 10);this.container.insertBefore(this.boxes[index], dummy);if(this.toggles && dbx.cookiestate[this.gid][i].charAt(1) == '-'){this.toggleBoxState(this.buttons[index], false);}}this.getBoxOrder();}}else if(!this.defopen && this.toggles){var len = this.buttons.length;for(i=0; i<len; i++){this.toggleBoxState(this.buttons[i], true);}}document[dbx.etype](dbx.eprefix + 'mouseout', function(e){if(typeof e.target == 'undefined') { e = window.event; e.relatedTarget = e.toElement; }if(e.relatedTarget == null){self.mouseup(e);}}, false);document[dbx.etype](dbx.eprefix + 'mousemove', function(e){self.mousemove(e);}, false);document[dbx.etype](dbx.eprefix + 'mouseup', function(e){self.mouseup(e);}, false);this.keydown = false;document[dbx.etype](dbx.eprefix + 'keydown', function(){self.keydown = true;}, false);document[dbx.etype](dbx.eprefix + 'keyup', function(){self.keydown = false;}, false);};dbxGroup.prototype.addToggleBehavior = function(){var self = this;var button = arguments[0].appendChild(dbx.createElement('a'));button.appendChild(document.createTextNode('\u00a0'));button.style.cursor = 'pointer';button.href = 'javascript:void(null)';button.className = 'dbx-toggle dbx-toggle-open';button.setAttribute('title', this.vocab.toggle.replace('%toggle%', this.vocab.close));button.hasfocus = typeof window.opera != 'undefined' || navigator.vendor == 'Apple Computer, Inc.' ? null : false;this.tooltip = null;button.onclick = function(){if(this.hasfocus === true || this.hasfocus === null){self.removeTooltip();self.toggleBoxState(this, true);}};button['onkey' + (typeof document.uniqueID != 'undefined' || navigator.vendor == 'Apple Computer, Inc.' ? 'down' : 'press')] = function(e){if(!e) { e = window.event; }return self.keypress(e, this);};button.onfocus = function(){var len = self.buttons.length;for(var i=0; i<len; i++){self.buttons[i].className = self.buttons[i].className.replace(/[ ](dbx\-toggle\-hilite\-)(open|closed)/, '');}var isopen = (/dbx\-toggle\-open/.test(this.className));this.className += ' dbx-toggle-hilite-' + (isopen ? 'open' : 'closed');self.createTooltip(isopen, this);this.isactive = true;if(this.hasfocus !== null) { this.hasfocus = true; }};button.onblur = function(){this.className = this.className.replace(/[ ](dbx\-toggle\-hilite\-)(open|closed)/, '');self.removeTooltip();if(this.hasfocus !== null) { this.hasfocus = false; }};return button;};dbxGroup.prototype.toggleBoxState = function(button, regen){var isopen = (/dbx\-toggle\-open/.test(button.className));var parent = dbx.getTarget(null, 'dbx\-box', button);dbx.box = parent;dbx.toggle = button;if(typeof dbx.container == 'undefined'){dbx.group = dbx.getTarget(null, 'dbx\-group', parent);}else { dbx.group = dbx.container; }if((!isopen && (typeof dbx.onboxopen == 'undefined' || dbx.onboxopen()))||(isopen && (typeof dbx.onboxclose == 'undefined' || dbx.onboxclose()))){button.className = 'dbx-toggle dbx-toggle-' + (isopen ? 'closed' : 'open');button.title = this.vocab.toggle.replace('%toggle%', isopen ? this.vocab.open : this.vocab.close);if(typeof button.isactive != 'undefined'){button.className += ' dbx-toggle-hilite-' + (isopen ? 'closed' : 'open')}parent.className = parent.className.replace(/[ ](dbx-box-)(open|closed)/, ' $1' + (isopen ? 'closed' : 'open'));if(regen) { this.getBoxOrder(); }}};dbxGroup.prototype.shiftBoxPosition = function(e, anchor, positive){var parent = dbx.getTarget(null, 'dbx\-box', anchor);dbx.group = this.container;dbx.box = parent;dbx.event = e;if(typeof dbx.onboxdrag == 'undefined' || dbx.onboxdrag()){var positions = [];var len = this.boxes.length;for(var i=0; i<len; i++){positions[i] = [i, this.boxes[i][this.vertical ? 'offsetTop' : 'offsetLeft']];if(parent == this.boxes[i]) { this.idref = i; }}positions.sort(this.compare);for(i=0; i<len; i++){if(positions[i][0] == this.idref){if((positive && i < len - 2) || (!positive && i > 0)){var sibling = this.boxes[positions[i + (positive ? 1 : -1)][0]];if(this.resolution > 0){var visipos = { 'x' : parent.offsetLeft, 'y' : parent.offsetTop };var siblingpos = { 'x' : sibling.offsetLeft, 'y' : sibling.offsetTop };}var obj = { 'insert' : (positive ? sibling : parent), 'before' : (positive ? parent : sibling) };this.container.insertBefore(obj.insert, obj.before);if(this.resolution > 0){var animators ={'sibling' : new dbxAnimator(this, sibling, siblingpos, this.resolution, true, anchor),'parent' : new dbxAnimator(this, parent, visipos, this.resolution, true, anchor)};}else{anchor.focus();}break;}}}this.getBoxOrder();}};dbxGroup.prototype.compare = function(a, b){return a[1] - b[1];};dbxGroup.prototype.createTooltip = function(isopen, anchor){if(this.keydown){this.tooltip = this.container.appendChild(dbx.createElement('span'));this.tooltip.style.visibility = 'hidden';this.tooltip.className = 'dbx-tooltip';if(isopen != null){this.tooltip.appendChild(document.createTextNode(this.vocab.kmove + this.vocab.ktoggle.replace('%toggle%', isopen ? this.vocab.close : this.vocab.open)));}else{this.tooltip.appendChild(document.createTextNode(this.vocab.kmove));}var parent = dbx.getTarget(null, 'dbx\-box', anchor);this.tooltip.style.left = parent.offsetLeft + 'px';this.tooltip.style.top = parent.offsetTop + 'px';var tooltip = this.tooltip;window.setTimeout(function(){if(tooltip != null) { tooltip.style.visibility = 'visible'; }}, 500);}};dbxGroup.prototype.removeTooltip = function(){if(this.tooltip != null){this.tooltip.parentNode.removeChild(this.tooltip);this.tooltip = null;}};dbxGroup.prototype.mousedown = function(e, box){var node = typeof e.target != 'undefined' ? e.target : e.srcElement;if(node.nodeName == '#text') { node = node.parentNode; }if(!/dbx\-(toggle|box|group)/i.test(node.className)){while(!/dbx\-(handle|box|group)/i.test(node.className)){node = node.parentNode;}}if(/dbx\-handle/i.test(node.className)){this.removeTooltip();this.released = false;this.initial = { 'x' : e.clientX, 'y' : e.clientY };this.current = { 'x' : 0, 'y' : 0 };this.createCloneBox(box);if(typeof e.preventDefault != 'undefined' ) { e.preventDefault(); }if(typeof document.onselectstart != 'undefined'){document.onselectstart = function() { return false; }}}};dbxGroup.prototype.mousemove = function(e){if(this.dragok && this.box != null){this.positive = this.vertical ? (e.clientY > this.current.y ? true : false) : (e.clientX > this.current.x ? true : false);this.current = { 'x' : e.clientX, 'y' : e.clientY };var overall = { 'x' : this.current.x - this.initial.x, 'y' : this.current.y - this.initial.y };if(((overall.x >= 0 && overall.x <= this.threshold) || (overall.x <= 0 && overall.x >= 0 - this.threshold))&&((overall.y >= 0 && overall.y <= this.threshold) || (overall.y <= 0 && overall.y >= 0 - this.threshold))){this.current.x -= overall.x;this.current.y -= overall.y;}if(this.released || overall.x > this.threshold || overall.x < (0 - this.threshold) || overall.y > this.threshold || overall.y < (0 - this.threshold)){dbx.group = this.container;dbx.box = this.box;dbx.event = e;if(typeof dbx.onboxdrag == 'undefined' || dbx.onboxdrag()){this.released = true;if(!this.restrict || !this.vertical) { this.boxclone.style.left = (this.current.x - this.difference.x) + 'px'; }if(!this.restrict || this.vertical) { this.boxclone.style.top = (this.current.y - this.difference.y) + 'px'; }this.moveOriginalToPosition(this.current.x, this.current.y);if(typeof e.preventDefault != 'undefined' ) { e.preventDefault(); }}}}return true;};dbxGroup.prototype.mouseup = function(e){if(this.box != null){this.moveOriginalToPosition(e.clientX, e.clientY);this.removeCloneBox();this.getBoxOrder();if(typeof document.onselectstart != 'undefined'){document.onselectstart = function() { return true; }}}this.dragok = false;};dbxGroup.prototype.keypress = function(e, anchor){if(/^(3[7-9])|(40)$/.test(e.keyCode)){this.removeTooltip();if((this.vertical && /^(38|40)$/.test(e.keyCode)) || (!this.vertical && /^(37|39)$/.test(e.keyCode))){this.shiftBoxPosition(e, anchor, /^[3][78]$/.test(e.keyCode) ? false : true);if(typeof e.preventDefault != 'undefined') { e.preventDefault(); }else { return false; }typeof e.stopPropagation != 'undefined' ? e.stopPropagation() : e.cancelBubble = true;this.keydown = false;}}return true;};dbxGroup.prototype.getBoxOrder = function(){this.order = [];var len = this.eles.length;for(var j=0; j<len; j++){if(/dbx\-box/i.test(this.eles[j].className) && !/dbx\-(clone|dummy)/i.test(this.eles[j].className)){this.order.push(this.eles[j].className.split('dbxid')[1] + (/dbx\-box\-open/i.test(this.eles[j].className) ? '+' : '-'));}}dbx.savedata[this.gid] = this.order.join(',');dbx.setCookieState();};dbxGroup.prototype.createClone = function(){var clone = this.container.appendChild(arguments[0].cloneNode(true));clone.className += ' dbx-clone';clone.style.position = 'absolute';clone.style.visibility = 'hidden';clone.style.zIndex = arguments[1];clone.style.left = arguments[2].x + 'px';clone.style.top = arguments[2].y + 'px';clone.style.width = arguments[0].offsetWidth + 'px';clone.style.height = arguments[0].offsetHeight + 'px';return clone;};dbxGroup.prototype.createCloneBox = function(box){this.box = box;this.position = { 'x' : this.box.offsetLeft, 'y' : this.box.offsetTop };this.difference = { 'x' : (this.initial.x - this.position.x), 'y' : (this.initial.y - this.position.y) };this.boxclone = this.createClone(this.box, 30000, this.position);this.boxclone.style.cursor = 'move';this.dragok = true;};dbxGroup.prototype.removeCloneBox = function(){this.container.removeChild(this.boxclone);this.box.style.visibility = 'visible';this.box = null;};dbxGroup.prototype.moveOriginalToPosition = function(clientX, clientY){var cloneprops = {'xy' : this.vertical ? clientY - this.difference.y : clientX - this.difference.x,'wh' : this.vertical ? this.boxclone.offsetHeight : this.boxclone.offsetWidth};this.box.style.visibility = 'hidden';this.boxclone.style.visibility = 'visible';var len = this.boxes.length;for(var i=0; i<len; i++){var boxprops = {'xy' : this.vertical ? this.boxes[i].offsetTop : this.boxes[i].offsetLeft,'wh' : this.vertical ? this.boxes[i].offsetHeight : this.boxes[i].offsetWidth};if((this.positive && cloneprops.xy + cloneprops.wh > boxprops.xy && cloneprops.xy < boxprops.xy)||(!this.positive && cloneprops.xy < boxprops.xy && cloneprops.xy + cloneprops.wh > boxprops.xy)){if(this.boxes[i] == this.box) { return; }var sibling = this.box.nextSibling;while(sibling.className == null || !/dbx\-box/.test(sibling.className)){sibling = sibling.nextSibling;}if(this.boxes[i] == sibling) { return; }if(this.resolution > 0){if(this.box[this.vertical ? 'offsetTop' : 'offsetLeft'] < boxprops.xy){var visibox = this.boxes[i].previousSibling;while(visibox.className == null || !/dbx\-box/.test(visibox.className)){visibox = visibox.previousSibling;}}else{visibox = this.boxes[i];}var visipos = { 'x' : visibox.offsetLeft, 'y' : visibox.offsetTop };}var prepos = { 'x' : this.box.offsetLeft, 'y' : this.box.offsetTop };this.container.insertBefore(this.box, this.boxes[i]);this.initial.x += (this.box.offsetLeft - prepos.x);this.initial.y += (this.box.offsetTop - prepos.y);if(this.resolution > 0 && visibox != this.box){var animator = new dbxAnimator(this, visibox, visipos, this.resolution, false, null);}else{}break;}}};function dbxAnimator(caller, box, pos, res, kbd, anchor){this.caller = caller;this.box = box;this.timer = null;var before = pos[this.caller.vertical ? 'y' : 'x'];var after = this.box[this.caller.vertical ? 'offsetTop' : 'offsetLeft'];if(before != after){if(dbx.running > this.caller.boxes.length - 1) { return; }var clone = this.caller.createClone(this.box, 29999, arguments[2]);clone.style.visibility = 'visible';this.box.style.visibility = 'hidden';this.animateClone(clone,before,after > before ? after - before : 0 - (before - after),this.caller.vertical ? 'top' : 'left',res,kbd,anchor);}};dbxAnimator.prototype.animateClone = function(clone, current, change, dir, res, kbd, anchor){var self = this;var count = 0;dbx.running ++;this.timer = window.setInterval(function(){count ++;current += change / res;clone.style[dir] = current + 'px';if(count == res){window.clearTimeout(self.timer);self.timer = null;dbx.running --;self.caller.container.removeChild(clone);self.box.style.visibility = 'visible';if(kbd){if(anchor != null && anchor.parentNode.style.visibility != 'hidden'){anchor.focus();}else if(self.caller.toggles){var button = self.caller.buttons[parseInt(self.box.className.split('dbxid')[1],10)];if(button != null && typeof button.isactive != 'undefined'){button.focus();}}}}}, 20);};if(typeof window.attachEvent != 'undefined'){window.attachEvent('onunload', function(){var ev = ['mousedown', 'mousemove', 'mouseup', 'mouseout', 'click', 'keydown', 'keyup', 'focus', 'blur', 'selectstart', 'statechange', 'boxdrag', 'boxopen', 'boxclose'];var el = ev.length;var dl = document.all.length;for(var i=0; i<dl; i++){for(var j=0; j<el; j++){document.all[i]['on' + ev[j]] = null;}}});} +var dbx;function dbxManager(sid){dbx = this;if(!/^[-_a-z0-9]+$/i.test(sid)) { alert('Error from dbxManager:\n"' + sid + '" is an invalid session ID'); return; }this.supported = !(document.getElementsByTagName('*').length == 0 || (navigator.vendor == 'KDE' && typeof window.sidebar == 'undefined'));if(!this.supported) { return; }this.etype = typeof document.addEventListener != 'undefined' ? 'addEventListener' : typeof document.attachEvent != 'undefined' ? 'attachEvent' : 'none';this.eprefix = (this.etype == 'attachEvent' ? 'on' : '');if(typeof window.opera != 'undefined' && parseFloat(navigator.userAgent.toLowerCase().split(/opera[\/ ]/)[1].split(' ')[0], 10) < 7.5){this.etype = 'none';}if(this.etype == 'none') { this.supported = false; return; }this.running = 0;this.sid = sid;this.savedata = {};this.cookiestate = this.getCookieState();};dbxManager.prototype.setCookieState = function(){var now = new Date();now.setTime(now.getTime() + (365*24*60*60*1000));var str = '';for(j in this.savedata){if(typeof this.savedata[j]!='function'){str += j + '=' + this.savedata[j] + '&'}}this.state = str.replace(/^(.+)&$/, '$1');if(typeof this.onstatechange == 'undefined' || this.onstatechange()){document.cookie = 'dbx-' + this.sid + '='+ this.state+ '; expires=' + now.toGMTString()+ '; path=/';}};dbxManager.prototype.getCookieState = function(){this.cookiestate = null;if(document.cookie){if(document.cookie.indexOf('dbx-' + this.sid)!=-1){this.cookie = document.cookie.split('dbx-' + this.sid + '=')[1].split('&');for(var i in this.cookie){if(typeof this.cookie[i]!='function'){this.cookie[i] = this.cookie[i].split('=');this.cookie[i][1] = this.cookie[i][1].split(',');}}this.cookiestate = {};for(i in this.cookie){if(typeof this.cookie[i]!='function'){this.cookiestate[this.cookie[i][0]] = this.cookie[i][1];}}}}return this.cookiestate;};dbxManager.prototype.addDataMember = function(gid, order){this.savedata[gid] = order;};dbxManager.prototype.createElement = function(tag){return typeof document.createElementNS != 'undefined' ? document.createElementNS('http://www.w3.org/1999/xhtml', tag) : document.createElement(tag);};dbxManager.prototype.getTarget = function(e, pattern, node){if(typeof node != 'undefined'){var target = node;}else{target = typeof e.target != 'undefined' ? e.target : e.srcElement;}var regex = new RegExp(pattern, '');while(!regex.test(target.className)){target = target.parentNode;}return target;};function dbxGroup(gid, dir, thresh, fix, ani, togs, def, open, close, move, toggle, kmove, ktoggle, syntax){if(!/^[-_a-z0-9]+$/i.test(gid)) { alert('Error from dbxGroup:\n"' + gid + '" is an invalid container ID'); return; }this.container = document.getElementById(gid);if(this.container == null || !dbx.supported) { return; }var self = this;this.gid = gid;this.dragok = false;this.box = null;this.vertical = dir == 'vertical';this.threshold = parseInt(thresh, 10);this.restrict = fix == 'yes';this.resolution = parseInt(ani, 10);this.toggles = togs == 'yes';this.defopen = def != 'closed';this.vocab = {'open' : open,'close' : close,'move' : move,'toggle' : toggle,'kmove' : kmove,'ktoggle' : ktoggle,'syntax' : syntax};this.container.style.position = 'relative';this.container.style.display = 'block';if(typeof window.opera != 'undefined'){this.container.style.display = 'run-in';}this.boxes = [];this.buttons = [];this.order = [];this.eles = this.container.getElementsByTagName('*');for(var i=0; i<this.eles.length; i++){if(/dbx\-box/i.test(this.eles[i].className) && !/dbx\-dummy/i.test(this.eles[i].className)){this.eles[i].style.position = 'relative';this.eles[i].style.display = 'block';this.boxes.push(this.eles[i]);this.eles[i].className += ' dbx-box-open';this.eles[i].className += ' dbxid' + this.order.length;this.order.push(this.order.length.toString() + '+');this.eles[i][dbx.etype](dbx.eprefix + 'mousedown', function(e){if(!e) { e = window.event; }self.mousedown(e, dbx.getTarget(e, 'dbx\-box'));}, false);}if(/dbx\-handle/i.test(this.eles[i].className)){this.eles[i].style.position = 'relative';this.eles[i].style.display = 'block';this.eles[i].className += ' dbx-handle-cursor';this.eles[i].setAttribute('title', this.eles[i].getAttribute('title') == null || this.eles[i].title == '' ? this.vocab.move : this.vocab.syntax.replace('%mytitle%', this.eles[i].title).replace('%dbxtitle%', this.vocab.move));if(this.toggles){this.buttons.push(this.addToggleBehavior(this.eles[i]));}else{this.eles[i][dbx.etype](dbx.eprefix + 'key' + (typeof document.uniqueID != 'undefined' || navigator.vendor == 'Apple Computer, Inc.' ? 'down' : 'press'), function(e){if(!e) { e = window.event; }return self.keypress(e, dbx.getTarget(e, 'dbx\-handle'));}, false);this.eles[i][dbx.etype](dbx.eprefix + 'focus', function(e){if(!e) { e = window.event; }self.createTooltip(null, dbx.getTarget(e, 'dbx\-handle'));}, false);this.eles[i][dbx.etype](dbx.eprefix + 'blur', function(){self.removeTooltip();}, false);}}}dbx.addDataMember(this.gid, this.order.join(','));var dummy = this.container.appendChild(dbx.createElement('span'));dummy.className = 'dbx-box dbx-dummy';dummy.style.display = 'block';dummy.style.width = '0';dummy.style.height = '0';dummy.style.overflow = 'hidden';if(this.vertical) { dummy.className += ' dbx-offdummy'; }this.boxes.push(dummy);if(dbx.cookiestate != null && typeof dbx.cookiestate[this.gid] != 'undefined'){var num = dbx.cookiestate[this.gid].length;if(num == this.boxes.length - 1){for(i=0; i<num; i++){var index = parseInt(dbx.cookiestate[this.gid][i], 10);this.container.insertBefore(this.boxes[index], dummy);if(this.toggles && /\-$/.test(dbx.cookiestate[this.gid][i])){this.toggleBoxState(this.buttons[index], false);}}this.getBoxOrder();}}else if(!this.defopen && this.toggles){var len = this.buttons.length;for(i=0; i<len; i++){this.toggleBoxState(this.buttons[i], true);}}document[dbx.etype](dbx.eprefix + 'mouseout', function(e){if(typeof e.target == 'undefined') { e = window.event; e.relatedTarget = e.toElement; }if(e.relatedTarget == null){self.mouseup(e);}}, false);document[dbx.etype](dbx.eprefix + 'mousemove', function(e){self.mousemove(e);return false;}, false);document[dbx.etype](dbx.eprefix + 'mouseup', function(e){self.mouseup(e);}, false);this.keydown = false;document[dbx.etype](dbx.eprefix + 'keydown', function(){self.keydown = true;}, false);document[dbx.etype](dbx.eprefix + 'keyup', function(){self.keydown = false;}, false);};dbxGroup.prototype.addToggleBehavior = function(){var self = this;var button = arguments[0].appendChild(dbx.createElement('a'));button.appendChild(document.createTextNode('\u00a0'));button.style.cursor = 'pointer';button.href = 'javascript:void(null)';button.className = 'dbx-toggle dbx-toggle-open';button.setAttribute('title', this.vocab.toggle.replace('%toggle%', this.vocab.close));button.hasfocus = typeof window.opera != 'undefined' || navigator.vendor == 'Apple Computer, Inc.' ? null : false;this.tooltip = null;button.onclick = function(){if(this.hasfocus === true || this.hasfocus === null){self.removeTooltip();self.toggleBoxState(this, true);}};button['onkey' + (typeof document.uniqueID != 'undefined' || navigator.vendor == 'Apple Computer, Inc.' ? 'down' : 'press')] = function(e){if(!e) { e = window.event; }return self.keypress(e, this);};button.onfocus = function(){var len = self.buttons.length;for(var i=0; i<len; i++){self.buttons[i].className = self.buttons[i].className.replace(/[ ](dbx\-toggle\-hilite\-)(open|closed)/, '');}var isopen = (/dbx\-toggle\-open/.test(this.className));this.className += ' dbx-toggle-hilite-' + (isopen ? 'open' : 'closed');self.createTooltip(isopen, this);this.isactive = true;if(this.hasfocus !== null) { this.hasfocus = true; }};button.onblur = function(){this.className = this.className.replace(/[ ](dbx\-toggle\-hilite\-)(open|closed)/, '');self.removeTooltip();if(this.hasfocus !== null) { this.hasfocus = false; }};return button;};dbxGroup.prototype.toggleBoxState = function(button, regen){var isopen = (/dbx\-toggle\-open/.test(button.className));var parent = dbx.getTarget(null, 'dbx\-box', button);dbx.box = parent;dbx.toggle = button;if(typeof dbx.container == 'undefined'){dbx.group = dbx.getTarget(null, 'dbx\-group', parent);}else { dbx.group = dbx.container; }if((!isopen && (typeof dbx.onboxopen == 'undefined' || dbx.onboxopen()))||(isopen && (typeof dbx.onboxclose == 'undefined' || dbx.onboxclose()))){button.className = 'dbx-toggle dbx-toggle-' + (isopen ? 'closed' : 'open');button.title = this.vocab.toggle.replace('%toggle%', isopen ? this.vocab.open : this.vocab.close);if(typeof button.isactive != 'undefined'){button.className += ' dbx-toggle-hilite-' + (isopen ? 'closed' : 'open')}parent.className = parent.className.replace(/[ ](dbx-box-)(open|closed)/, ' $1' + (isopen ? 'closed' : 'open'));if(regen) { this.getBoxOrder(); }}};dbxGroup.prototype.shiftBoxPosition = function(e, anchor, positive){var parent = dbx.getTarget(null, 'dbx\-box', anchor);dbx.group = this.container;dbx.box = parent;dbx.event = e;if(typeof dbx.onboxdrag == 'undefined' || dbx.onboxdrag()){var positions = [];var len = this.boxes.length;for(var i=0; i<len; i++){positions[i] = [i, this.boxes[i][this.vertical ? 'offsetTop' : 'offsetLeft']];if(parent == this.boxes[i]) { this.idref = i; }}positions.sort(this.compare);for(i=0; i<len; i++){if(positions[i][0] == this.idref){if((positive && i < len - 2) || (!positive && i > 0)){var sibling = this.boxes[positions[i + (positive ? 1 : -1)][0]];if(this.resolution > 0){var visipos = { 'x' : parent.offsetLeft, 'y' : parent.offsetTop };var siblingpos = { 'x' : sibling.offsetLeft, 'y' : sibling.offsetTop };}var obj = { 'insert' : (positive ? sibling : parent), 'before' : (positive ? parent : sibling) };this.container.insertBefore(obj.insert, obj.before);if(this.resolution > 0){var animators ={'sibling' : new dbxAnimator(this, sibling, siblingpos, this.resolution, true, anchor),'parent' : new dbxAnimator(this, parent, visipos, this.resolution, true, anchor)};}else{anchor.focus();}break;}}}this.getBoxOrder();}};dbxGroup.prototype.compare = function(a, b){return a[1] - b[1];};dbxGroup.prototype.createTooltip = function(isopen, anchor){if(this.keydown){this.tooltip = this.container.appendChild(dbx.createElement('span'));this.tooltip.style.visibility = 'hidden';this.tooltip.className = 'dbx-tooltip';if(isopen != null){this.tooltip.appendChild(document.createTextNode(this.vocab.kmove + this.vocab.ktoggle.replace('%toggle%', isopen ? this.vocab.close : this.vocab.open)));}else{this.tooltip.appendChild(document.createTextNode(this.vocab.kmove));}var parent = dbx.getTarget(null, 'dbx\-box', anchor);this.tooltip.style.left = parent.offsetLeft + 'px';this.tooltip.style.top = parent.offsetTop + 'px';var tooltip = this.tooltip;window.setTimeout(function(){if(tooltip != null) { tooltip.style.visibility = 'visible'; }}, 500);}};dbxGroup.prototype.removeTooltip = function(){if(this.tooltip != null){this.tooltip.parentNode.removeChild(this.tooltip);this.tooltip = null;}};dbxGroup.prototype.mousedown = function(e, box){var node = typeof e.target != 'undefined' ? e.target : e.srcElement;if(node.nodeName == '#text') { node = node.parentNode; }if(!/dbx\-(toggle|box|group)/i.test(node.className)){while(!/dbx\-(handle|box|group)/i.test(node.className)){node = node.parentNode;}}if(/dbx\-handle/i.test(node.className)){this.removeTooltip();this.released = false;this.initial = { 'x' : e.clientX, 'y' : e.clientY };this.current = { 'x' : 0, 'y' : 0 };this.createCloneBox(box);if(typeof e.preventDefault != 'undefined' ) { e.preventDefault(); }if(typeof document.onselectstart != 'undefined'){document.onselectstart = function() { return false; }}}};dbxGroup.prototype.mousemove = function(e){if(this.dragok && this.box != null){this.positive = this.vertical ? (e.clientY > this.current.y ? true : false) : (e.clientX > this.current.x ? true : false);this.current = { 'x' : e.clientX, 'y' : e.clientY };var overall = { 'x' : this.current.x - this.initial.x, 'y' : this.current.y - this.initial.y };if(((overall.x >= 0 && overall.x <= this.threshold) || (overall.x <= 0 && overall.x >= 0 - this.threshold))&&((overall.y >= 0 && overall.y <= this.threshold) || (overall.y <= 0 && overall.y >= 0 - this.threshold))){this.current.x -= overall.x;this.current.y -= overall.y;}if(this.released || overall.x > this.threshold || overall.x < (0 - this.threshold) || overall.y > this.threshold || overall.y < (0 - this.threshold)){dbx.group = this.container;dbx.box = this.box;dbx.event = e;if(typeof dbx.onboxdrag == 'undefined' || dbx.onboxdrag()){this.released = true;if(!this.restrict || !this.vertical) { this.boxclone.style.left = (this.current.x - this.difference.x) + 'px'; }if(!this.restrict || this.vertical) { this.boxclone.style.top = (this.current.y - this.difference.y) + 'px'; }this.moveOriginalToPosition(this.current.x, this.current.y);if(typeof e.preventDefault != 'undefined' ) { e.preventDefault(); }}}}return true;};dbxGroup.prototype.mouseup = function(e){if(this.box != null){this.moveOriginalToPosition(e.clientX, e.clientY);this.removeCloneBox();this.getBoxOrder();if(typeof document.onselectstart != 'undefined'){document.onselectstart = function() { return true; }}}this.dragok = false;};dbxGroup.prototype.keypress = function(e, anchor){if(/^(3[7-9])|(40)$/.test(e.keyCode)){this.removeTooltip();if((this.vertical && /^(38|40)$/.test(e.keyCode)) || (!this.vertical && /^(37|39)$/.test(e.keyCode))){this.shiftBoxPosition(e, anchor, /^[3][78]$/.test(e.keyCode) ? false : true);if(typeof e.preventDefault != 'undefined') { e.preventDefault(); }else { return false; }typeof e.stopPropagation != 'undefined' ? e.stopPropagation() : e.cancelBubble = true;this.keydown = false;}}return true;};dbxGroup.prototype.getBoxOrder = function(){this.order = [];var len = this.eles.length;for(var j=0; j<len; j++){if(/dbx\-box/i.test(this.eles[j].className) && !/dbx\-(clone|dummy)/i.test(this.eles[j].className)){this.order.push(this.eles[j].className.split('dbxid')[1] + (/dbx\-box\-open/i.test(this.eles[j].className) ? '+' : '-'));}}dbx.savedata[this.gid] = this.order.join(',');dbx.setCookieState();};dbxGroup.prototype.createClone = function(){var clone = this.container.appendChild(arguments[0].cloneNode(true));clone.className += ' dbx-clone';clone.style.position = 'absolute';clone.style.visibility = 'hidden';clone.style.zIndex = arguments[1];clone.style.left = arguments[2].x + 'px';clone.style.top = arguments[2].y + 'px';clone.style.width = arguments[0].offsetWidth + 'px';clone.style.height = arguments[0].offsetHeight + 'px';return clone;};dbxGroup.prototype.createCloneBox = function(box){this.box = box;this.position = { 'x' : this.box.offsetLeft, 'y' : this.box.offsetTop };this.difference = { 'x' : (this.initial.x - this.position.x), 'y' : (this.initial.y - this.position.y) };this.boxclone = this.createClone(this.box, 30000, this.position);this.boxclone.style.cursor = 'move';this.dragok = true;};dbxGroup.prototype.removeCloneBox = function(){this.container.removeChild(this.boxclone);this.box.style.visibility = 'visible';this.box = null;};dbxGroup.prototype.moveOriginalToPosition = function(clientX, clientY){var cloneprops = {'xy' : this.vertical ? clientY - this.difference.y : clientX - this.difference.x,'wh' : this.vertical ? this.boxclone.offsetHeight : this.boxclone.offsetWidth};this.box.style.visibility = 'hidden';this.boxclone.style.visibility = 'visible';var len = this.boxes.length;for(var i=0; i<len; i++){var boxprops = {'xy' : this.vertical ? this.boxes[i].offsetTop : this.boxes[i].offsetLeft,'wh' : this.vertical ? this.boxes[i].offsetHeight : this.boxes[i].offsetWidth};if((this.positive && cloneprops.xy + cloneprops.wh > boxprops.xy && cloneprops.xy < boxprops.xy)||(!this.positive && cloneprops.xy < boxprops.xy && cloneprops.xy + cloneprops.wh > boxprops.xy)){if(this.boxes[i] == this.box) { return; }var sibling = this.box.nextSibling;while(sibling.className == null || !/dbx\-box/.test(sibling.className)){sibling = sibling.nextSibling;}if(this.boxes[i] == sibling) { return; }if(this.resolution > 0){if(this.box[this.vertical ? 'offsetTop' : 'offsetLeft'] < boxprops.xy){var visibox = this.boxes[i].previousSibling;while(visibox.className == null || !/dbx\-box/.test(visibox.className)){visibox = visibox.previousSibling;}}else{visibox = this.boxes[i];}var visipos = { 'x' : visibox.offsetLeft, 'y' : visibox.offsetTop };}var prepos = { 'x' : this.box.offsetLeft, 'y' : this.box.offsetTop };this.container.insertBefore(this.box, this.boxes[i]);this.initial.x += (this.box.offsetLeft - prepos.x);this.initial.y += (this.box.offsetTop - prepos.y);if(this.resolution > 0 && visibox != this.box){var animator = new dbxAnimator(this, visibox, visipos, this.resolution, false, null);}else{}break;}}};function dbxAnimator(caller, box, pos, res, kbd, anchor){this.caller = caller;this.box = box;this.timer = null;var before = pos[this.caller.vertical ? 'y' : 'x'];var after = this.box[this.caller.vertical ? 'offsetTop' : 'offsetLeft'];if(before != after){if(dbx.running > this.caller.boxes.length - 1) { return; }var clone = this.caller.createClone(this.box, 29999, arguments[2]);clone.style.visibility = 'visible';this.box.style.visibility = 'hidden';this.animateClone(clone,before,after > before ? after - before : 0 - (before - after),this.caller.vertical ? 'top' : 'left',res,kbd,anchor);}};dbxAnimator.prototype.animateClone = function(clone, current, change, dir, res, kbd, anchor){var self = this;var count = 0;dbx.running ++;this.timer = window.setInterval(function(){count ++;current += change / res;clone.style[dir] = current + 'px';if(count == res){window.clearTimeout(self.timer);self.timer = null;dbx.running --;self.caller.container.removeChild(clone);self.box.style.visibility = 'visible';if(kbd){if(anchor != null && anchor.parentNode.style.visibility != 'hidden'){anchor.focus();}else if(self.caller.toggles){var button = self.caller.buttons[parseInt(self.box.className.split('dbxid')[1],10)];if(button != null && typeof button.isactive != 'undefined'){button.focus();}}}}}, 20);};if(typeof window.attachEvent != 'undefined'){window.attachEvent('onunload', function(){var ev = ['mousedown', 'mousemove', 'mouseup', 'mouseout', 'click', 'keydown', 'keyup', 'focus', 'blur', 'selectstart', 'statechange', 'boxdrag', 'boxopen', 'boxclose'];var el = ev.length;var dl = document.all.length;for(var i=0; i<dl; i++){for(var j=0; j<el; j++){document.all[i]['on' + ev[j]] = null;}}});} diff --git a/wp-inst/wp-includes/js/scriptaculous/MIT-LICENSE b/wp-inst/wp-includes/js/scriptaculous/MIT-LICENSE new file mode 100644 index 0000000..36af55c --- /dev/null +++ b/wp-inst/wp-includes/js/scriptaculous/MIT-LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file diff --git a/wp-inst/wp-includes/js/scriptaculous/builder.js b/wp-inst/wp-includes/js/scriptaculous/builder.js new file mode 100644 index 0000000..5b15ba9 --- /dev/null +++ b/wp-inst/wp-includes/js/scriptaculous/builder.js @@ -0,0 +1,101 @@ +// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) +// +// See scriptaculous.js for full license. + +var Builder = { + NODEMAP: { + AREA: 'map', + CAPTION: 'table', + COL: 'table', + COLGROUP: 'table', + LEGEND: 'fieldset', + OPTGROUP: 'select', + OPTION: 'select', + PARAM: 'object', + TBODY: 'table', + TD: 'table', + TFOOT: 'table', + TH: 'table', + THEAD: 'table', + TR: 'table' + }, + // note: For Firefox < 1.5, OPTION and OPTGROUP tags are currently broken, + // due to a Firefox bug + node: function(elementName) { + elementName = elementName.toUpperCase(); + + // try innerHTML approach + var parentTag = this.NODEMAP[elementName] || 'div'; + var parentElement = document.createElement(parentTag); + try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707 + parentElement.innerHTML = "<" + elementName + "></" + elementName + ">"; + } catch(e) {} + var element = parentElement.firstChild || null; + + // see if browser added wrapping tags + if(element && (element.tagName != elementName)) + element = element.getElementsByTagName(elementName)[0]; + + // fallback to createElement approach + if(!element) element = document.createElement(elementName); + + // abort if nothing could be created + if(!element) return; + + // attributes (or text) + if(arguments[1]) + if(this._isStringOrNumber(arguments[1]) || + (arguments[1] instanceof Array)) { + this._children(element, arguments[1]); + } else { + var attrs = this._attributes(arguments[1]); + if(attrs.length) { + try { // prevent IE "feature": http://dev.rubyonrails.org/ticket/2707 + parentElement.innerHTML = "<" +elementName + " " + + attrs + "></" + elementName + ">"; + } catch(e) {} + element = parentElement.firstChild || null; + // workaround firefox 1.0.X bug + if(!element) { + element = document.createElement(elementName); + for(attr in arguments[1]) + element[attr == 'class' ? 'className' : attr] = arguments[1][attr]; + } + if(element.tagName != elementName) + element = parentElement.getElementsByTagName(elementName)[0]; + } + } + + // text, or array of children + if(arguments[2]) + this._children(element, arguments[2]); + + return element; + }, + _text: function(text) { + return document.createTextNode(text); + }, + _attributes: function(attributes) { + var attrs = []; + for(attribute in attributes) + attrs.push((attribute=='className' ? 'class' : attribute) + + '="' + attributes[attribute].toString().escapeHTML() + '"'); + return attrs.join(" "); + }, + _children: function(element, children) { + if(typeof children=='object') { // array can hold nodes and text + children.flatten().each( function(e) { + if(typeof e=='object') + element.appendChild(e) + else + if(Builder._isStringOrNumber(e)) + element.appendChild(Builder._text(e)); + }); + } else + if(Builder._isStringOrNumber(children)) + element.appendChild(Builder._text(children)); + }, + _isStringOrNumber: function(param) { + return(typeof param=='string' || typeof param=='number'); + } +}
\ No newline at end of file diff --git a/wp-inst/wp-includes/js/scriptaculous/controls.js b/wp-inst/wp-includes/js/scriptaculous/controls.js new file mode 100644 index 0000000..de0261e --- /dev/null +++ b/wp-inst/wp-includes/js/scriptaculous/controls.js @@ -0,0 +1,815 @@ +// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) +// (c) 2005 Ivan Krstic (http://blogs.law.harvard.edu/ivan) +// (c) 2005 Jon Tirsen (http://www.tirsen.com) +// Contributors: +// Richard Livsey +// Rahul Bhargava +// Rob Wills +// +// See scriptaculous.js for full license. + +// Autocompleter.Base handles all the autocompletion functionality +// that's independent of the data source for autocompletion. This +// includes drawing the autocompletion menu, observing keyboard +// and mouse events, and similar. +// +// Specific autocompleters need to provide, at the very least, +// a getUpdatedChoices function that will be invoked every time +// the text inside the monitored textbox changes. This method +// should get the text for which to provide autocompletion by +// invoking this.getToken(), NOT by directly accessing +// this.element.value. This is to allow incremental tokenized +// autocompletion. Specific auto-completion logic (AJAX, etc) +// belongs in getUpdatedChoices. +// +// Tokenized incremental autocompletion is enabled automatically +// when an autocompleter is instantiated with the 'tokens' option +// in the options parameter, e.g.: +// new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' }); +// will incrementally autocomplete with a comma as the token. +// Additionally, ',' in the above example can be replaced with +// a token array, e.g. { tokens: [',', '\n'] } which +// enables autocompletion on multiple tokens. This is most +// useful when one of the tokens is \n (a newline), as it +// allows smart autocompletion after linebreaks. + +var Autocompleter = {} +Autocompleter.Base = function() {}; +Autocompleter.Base.prototype = { + baseInitialize: function(element, update, options) { + this.element = $(element); + this.update = $(update); + this.hasFocus = false; + this.changed = false; + this.active = false; + this.index = 0; + this.entryCount = 0; + + if (this.setOptions) + this.setOptions(options); + else + this.options = options || {}; + + this.options.paramName = this.options.paramName || this.element.name; + this.options.tokens = this.options.tokens || []; + this.options.frequency = this.options.frequency || 0.4; + this.options.minChars = this.options.minChars || 1; + this.options.onShow = this.options.onShow || + function(element, update){ + if(!update.style.position || update.style.position=='absolute') { + update.style.position = 'absolute'; + Position.clone(element, update, {setHeight: false, offsetTop: element.offsetHeight}); + } + Effect.Appear(update,{duration:0.15}); + }; + this.options.onHide = this.options.onHide || + function(element, update){ new Effect.Fade(update,{duration:0.15}) }; + + if (typeof(this.options.tokens) == 'string') + this.options.tokens = new Array(this.options.tokens); + + this.observer = null; + + this.element.setAttribute('autocomplete','off'); + + Element.hide(this.update); + + Event.observe(this.element, "blur", this.onBlur.bindAsEventListener(this)); + Event.observe(this.element, "keypress", this.onKeyPress.bindAsEventListener(this)); + }, + + show: function() { + if(Element.getStyle(this.update, 'display')=='none') this.options.onShow(this.element, this.update); + if(!this.iefix && + (navigator.appVersion.indexOf('MSIE')>0) && + (navigator.userAgent.indexOf('Opera')<0) && + (Element.getStyle(this.update, 'position')=='absolute')) { + new Insertion.After(this.update, + '<iframe id="' + this.update.id + '_iefix" '+ + 'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" ' + + 'src="javascript:false;" frameborder="0" scrolling="no"></iframe>'); + this.iefix = $(this.update.id+'_iefix'); + } + if(this.iefix) setTimeout(this.fixIEOverlapping.bind(this), 50); + }, + + fixIEOverlapping: function() { + Position.clone(this.update, this.iefix); + this.iefix.style.zIndex = 1; + this.update.style.zIndex = 2; + Element.show(this.iefix); + }, + + hide: function() { + this.stopIndicator(); + if(Element.getStyle(this.update, 'display')!='none') this.options.onHide(this.element, this.update); + if(this.iefix) Element.hide(this.iefix); + }, + + startIndicator: function() { + if(this.options.indicator) Element.show(this.options.indicator); + }, + + stopIndicator: function() { + if(this.options.indicator) Element.hide(this.options.indicator); + }, + + onKeyPress: function(event) { + if(this.active) + switch(event.keyCode) { + case Event.KEY_TAB: + case Event.KEY_RETURN: + this.selectEntry(); + Event.stop(event); + case Event.KEY_ESC: + this.hide(); + this.active = false; + Event.stop(event); + return; + case Event.KEY_LEFT: + case Event.KEY_RIGHT: + return; + case Event.KEY_UP: + this.markPrevious(); + this.render(); + if(navigator.appVersion.indexOf('AppleWebKit')>0) Event.stop(event); + return; + case Event.KEY_DOWN: + this.markNext(); + this.render(); + if(navigator.appVersion.indexOf('AppleWebKit')>0) Event.stop(event); + return; + } + else + if(event.keyCode==Event.KEY_TAB || event.keyCode==Event.KEY_RETURN || + (navigator.appVersion.indexOf('AppleWebKit') > 0 && event.keyCode == 0)) return; + + this.changed = true; + this.hasFocus = true; + + if(this.observer) clearTimeout(this.observer); + this.observer = + setTimeout(this.onObserverEvent.bind(this), this.options.frequency*1000); + }, + + activate: function() { + this.changed = false; + this.hasFocus = true; + this.getUpdatedChoices(); + }, + + onHover: function(event) { + var element = Event.findElement(event, 'LI'); + if(this.index != element.autocompleteIndex) + { + this.index = element.autocompleteIndex; + this.render(); + } + Event.stop(event); + }, + + onClick: function(event) { + var element = Event.findElement(event, 'LI'); + this.index = element.autocompleteIndex; + this.selectEntry(); + this.hide(); + }, + + onBlur: function(event) { + // needed to make click events working + setTimeout(this.hide.bind(this), 250); + this.hasFocus = false; + this.active = false; + }, + + render: function() { + if(this.entryCount > 0) { + for (var i = 0; i < this.entryCount; i++) + this.index==i ? + Element.addClassName(this.getEntry(i),"selected") : + Element.removeClassName(this.getEntry(i),"selected"); + + if(this.hasFocus) { + this.show(); + this.active = true; + } + } else { + this.active = false; + this.hide(); + } + }, + + markPrevious: function() { + if(this.index > 0) this.index-- + else this.index = this.entryCount-1; + }, + + markNext: function() { + if(this.index < this.entryCount-1) this.index++ + else this.index = 0; + }, + + getEntry: function(index) { + return this.update.firstChild.childNodes[index]; + }, + + getCurrentEntry: function() { + return this.getEntry(this.index); + }, + + selectEntry: function() { + this.active = false; + this.updateElement(this.getCurrentEntry()); + }, + + updateElement: function(selectedElement) { + if (this.options.updateElement) { + this.options.updateElement(selectedElement); + return; + } + var value = ''; + if (this.options.select) { + var nodes = document.getElementsByClassName(this.options.select, selectedElement) || []; + if(nodes.length>0) value = Element.collectTextNodes(nodes[0], this.options.select); + } else + value = Element.collectTextNodesIgnoreClass(selectedElement, 'informal'); + + var lastTokenPos = this.findLastToken(); + if (lastTokenPos != -1) { + var newValue = this.element.value.substr(0, lastTokenPos + 1); + var whitespace = this.element.value.substr(lastTokenPos + 1).match(/^\s+/); + if (whitespace) + newValue += whitespace[0]; + this.element.value = newValue + value; + } else { + this.element.value = value; + } + this.element.focus(); + + if (this.options.afterUpdateElement) + this.options.afterUpdateElement(this.element, selectedElement); + }, + + updateChoices: function(choices) { + if(!this.changed && this.hasFocus) { + this.update.innerHTML = choices; + Element.cleanWhitespace(this.update); + Element.cleanWhitespace(this.update.firstChild); + + if(this.update.firstChild && this.update.firstChild.childNodes) { + this.entryCount = + this.update.firstChild.childNodes.length; + for (var i = 0; i < this.entryCount; i++) { + var entry = this.getEntry(i); + entry.autocompleteIndex = i; + this.addObservers(entry); + } + } else { + this.entryCount = 0; + } + + this.stopIndicator(); + + this.index = 0; + this.render(); + } + }, + + addObservers: function(element) { + Event.observe(element, "mouseover", this.onHover.bindAsEventListener(this)); + Event.observe(element, "click", this.onClick.bindAsEventListener(this)); + }, + + onObserverEvent: function() { + this.changed = false; + if(this.getToken().length>=this.options.minChars) { + this.startIndicator(); + this.getUpdatedChoices(); + } else { + this.active = false; + this.hide(); + } + }, + + getToken: function() { + var tokenPos = this.findLastToken(); + if (tokenPos != -1) + var ret = this.element.value.substr(tokenPos + 1).replace(/^\s+/,'').replace(/\s+$/,''); + else + var ret = this.element.value; + + return /\n/.test(ret) ? '' : ret; + }, + + findLastToken: function() { + var lastTokenPos = -1; + + for (var i=0; i<this.options.tokens.length; i++) { + var thisTokenPos = this.element.value.lastIndexOf(this.options.tokens[i]); + if (thisTokenPos > lastTokenPos) + lastTokenPos = thisTokenPos; + } + return lastTokenPos; + } +} + +Ajax.Autocompleter = Class.create(); +Object.extend(Object.extend(Ajax.Autocompleter.prototype, Autocompleter.Base.prototype), { + initialize: function(element, update, url, options) { + this.baseInitialize(element, update, options); + this.options.asynchronous = true; + this.options.onComplete = this.onComplete.bind(this); + this.options.defaultParams = this.options.parameters || null; + this.url = url; + }, + + getUpdatedChoices: function() { + entry = encodeURIComponent(this.options.paramName) + '=' + + encodeURIComponent(this.getToken()); + + this.options.parameters = this.options.callback ? + this.options.callback(this.element, entry) : entry; + + if(this.options.defaultParams) + this.options.parameters += '&' + this.options.defaultParams; + + new Ajax.Request(this.url, this.options); + }, + + onComplete: function(request) { + this.updateChoices(request.responseText); + } + +}); + +// The local array autocompleter. Used when you'd prefer to +// inject an array of autocompletion options into the page, rather +// than sending out Ajax queries, which can be quite slow sometimes. +// +// The constructor takes four parameters. The first two are, as usual, +// the id of the monitored textbox, and id of the autocompletion menu. +// The third is the array you want to autocomplete from, and the fourth +// is the options block. +// +// Extra local autocompletion options: +// - choices - How many autocompletion choices to offer +// +// - partialSearch - If false, the autocompleter will match entered +// text only at the beginning of strings in the +// autocomplete array. Defaults to true, which will +// match text at the beginning of any *word* in the +// strings in the autocomplete array. If you want to +// search anywhere in the string, additionally set +// the option fullSearch to true (default: off). +// +// - fullSsearch - Search anywhere in autocomplete array strings. +// +// - partialChars - How many characters to enter before triggering +// a partial match (unlike minChars, which defines +// how many characters are required to do any match +// at all). Defaults to 2. +// +// - ignoreCase - Whether to ignore case when autocompleting. +// Defaults to true. +// +// It's possible to pass in a custom function as the 'selector' +// option, if you prefer to write your own autocompletion logic. +// In that case, the other options above will not apply unless +// you support them. + +Autocompleter.Local = Class.create(); +Autocompleter.Local.prototype = Object.extend(new Autocompleter.Base(), { + initialize: function(element, update, array, options) { + this.baseInitialize(element, update, options); + this.options.array = array; + }, + + getUpdatedChoices: function() { + this.updateChoices(this.options.selector(this)); + }, + + setOptions: function(options) { + this.options = Object.extend({ + choices: 10, + partialSearch: true, + partialChars: 2, + ignoreCase: true, + fullSearch: false, + selector: function(instance) { + var ret = []; // Beginning matches + var partial = []; // Inside matches + var entry = instance.getToken(); + var count = 0; + + for (var i = 0; i < instance.options.array.length && + ret.length < instance.options.choices ; i++) { + + var elem = instance.options.array[i]; + var foundPos = instance.options.ignoreCase ? + elem.toLowerCase().indexOf(entry.toLowerCase()) : + elem.indexOf(entry); + + while (foundPos != -1) { + if (foundPos == 0 && elem.length != entry.length) { + ret.push("<li><strong>" + elem.substr(0, entry.length) + "</strong>" + + elem.substr(entry.length) + "</li>"); + break; + } else if (entry.length >= instance.options.partialChars && + instance.options.partialSearch && foundPos != -1) { + if (instance.options.fullSearch || /\s/.test(elem.substr(foundPos-1,1))) { + partial.push("<li>" + elem.substr(0, foundPos) + "<strong>" + + elem.substr(foundPos, entry.length) + "</strong>" + elem.substr( + foundPos + entry.length) + "</li>"); + break; + } + } + + foundPos = instance.options.ignoreCase ? + elem.toLowerCase().indexOf(entry.toLowerCase(), foundPos + 1) : + elem.indexOf(entry, foundPos + 1); + + } + } + if (partial.length) + ret = ret.concat(partial.slice(0, instance.options.choices - ret.length)) + return "<ul>" + ret.join('') + "</ul>"; + } + }, options || {}); + } +}); + +// AJAX in-place editor +// +// see documentation on http://wiki.script.aculo.us/scriptaculous/show/Ajax.InPlaceEditor + +// Use this if you notice weird scrolling problems on some browsers, +// the DOM might be a bit confused when this gets called so do this +// waits 1 ms (with setTimeout) until it does the activation +Field.scrollFreeActivate = function(field) { + setTimeout(function() { + Field.activate(field); + }, 1); +} + +Ajax.InPlaceEditor = Class.create(); +Ajax.InPlaceEditor.defaultHighlightColor = "#FFFF99"; +Ajax.InPlaceEditor.prototype = { + initialize: function(element, url, options) { + this.url = url; + this.element = $(element); + + this.options = Object.extend({ + okButton: true, + okText: "ok", + cancelLink: true, + cancelText: "cancel", + savingText: "Saving...", + clickToEditText: "Click to edit", + okText: "ok", + rows: 1, + onComplete: function(transport, element) { + new Effect.Highlight(element, {startcolor: this.options.highlightcolor}); + }, + onFailure: function(transport) { + alert("Error communicating with the server: " + transport.responseText.stripTags()); + }, + callback: function(form) { + return Form.serialize(form); + }, + handleLineBreaks: true, + loadingText: 'Loading...', + savingClassName: 'inplaceeditor-saving', + loadingClassName: 'inplaceeditor-loading', + formClassName: 'inplaceeditor-form', + highlightcolor: Ajax.InPlaceEditor.defaultHighlightColor, + highlightendcolor: "#FFFFFF", + externalControl: null, + submitOnBlur: false, + ajaxOptions: {}, + evalScripts: false + }, options || {}); + + if(!this.options.formId && this.element.id) { + this.options.formId = this.element.id + "-inplaceeditor"; + if ($(this.options.formId)) { + // there's already a form with that name, don't specify an id + this.options.formId = null; + } + } + + if (this.options.externalControl) { + this.options.externalControl = $(this.options.externalControl); + } + + this.originalBackground = Element.getStyle(this.element, 'background-color'); + if (!this.originalBackground) { + this.originalBackground = "transparent"; + } + + this.element.title = this.options.clickToEditText; + + this.onclickListener = this.enterEditMode.bindAsEventListener(this); + this.mouseoverListener = this.enterHover.bindAsEventListener(this); + this.mouseoutListener = this.leaveHover.bindAsEventListener(this); + Event.observe(this.element, 'click', this.onclickListener); + Event.observe(this.element, 'mouseover', this.mouseoverListener); + Event.observe(this.element, 'mouseout', this.mouseoutListener); + if (this.options.externalControl) { + Event.observe(this.options.externalControl, 'click', this.onclickListener); + Event.observe(this.options.externalControl, 'mouseover', this.mouseoverListener); + Event.observe(this.options.externalControl, 'mouseout', this.mouseoutListener); + } + }, + enterEditMode: function(evt) { + if (this.saving) return; + if (this.editing) return; + this.editing = true; + this.onEnterEditMode(); + if (this.options.externalControl) { + Element.hide(this.options.externalControl); + } + Element.hide(this.element); + this.createForm(); + this.element.parentNode.insertBefore(this.form, this.element); + Field.scrollFreeActivate(this.editField); + // stop the event to avoid a page refresh in Safari + if (evt) { + Event.stop(evt); + } + return false; + }, + createForm: function() { + this.form = document.createElement("form"); + this.form.id = this.options.formId; + Element.addClassName(this.form, this.options.formClassName) + this.form.onsubmit = this.onSubmit.bind(this); + + this.createEditField(); + + if (this.options.textarea) { + var br = document.createElement("br"); + this.form.appendChild(br); + } + + if (this.options.okButton) { + okButton = document.createElement("input"); + okButton.type = "submit"; + okButton.value = this.options.okText; + okButton.className = 'editor_ok_button'; + this.form.appendChild(okButton); + } + + if (this.options.cancelLink) { + cancelLink = document.createElement("a"); + cancelLink.href = "#"; + cancelLink.appendChild(document.createTextNode(this.options.cancelText)); + cancelLink.onclick = this.onclickCancel.bind(this); + cancelLink.className = 'editor_cancel'; + this.form.appendChild(cancelLink); + } + }, + hasHTMLLineBreaks: function(string) { + if (!this.options.handleLineBreaks) return false; + return string.match(/<br/i) || string.match(/<p>/i); + }, + convertHTMLLineBreaks: function(string) { + return string.replace(/<br>/gi, "\n").replace(/<br\/>/gi, "\n").replace(/<\/p>/gi, "\n").replace(/<p>/gi, ""); + }, + createEditField: function() { + var text; + if(this.options.loadTextURL) { + text = this.options.loadingText; + } else { + text = this.getText(); + } + + var obj = this; + + if (this.options.rows == 1 && !this.hasHTMLLineBreaks(text)) { + this.options.textarea = false; + var textField = document.createElement("input"); + textField.obj = this; + textField.type = "text"; + textField.name = "value"; + textField.value = text; + textField.style.backgroundColor = this.options.highlightcolor; + textField.className = 'editor_field'; + var size = this.options.size || this.options.cols || 0; + if (size != 0) textField.size = size; + if (this.options.submitOnBlur) + textField.onblur = this.onSubmit.bind(this); + this.editField = textField; + } else { + this.options.textarea = true; + var textArea = document.createElement("textarea"); + textArea.obj = this; + textArea.name = "value"; + textArea.value = this.convertHTMLLineBreaks(text); + textArea.rows = this.options.rows; + textArea.cols = this.options.cols || 40; + textArea.className = 'editor_field'; + if (this.options.submitOnBlur) + textArea.onblur = this.onSubmit.bind(this); + this.editField = textArea; + } + + if(this.options.loadTextURL) { + this.loadExternalText(); + } + this.form.appendChild(this.editField); + }, + getText: function() { + return this.element.innerHTML; + }, + loadExternalText: function() { + Element.addClassName(this.form, this.options.loadingClassName); + this.editField.disabled = true; + new Ajax.Request( + this.options.loadTextURL, + Object.extend({ + asynchronous: true, + onComplete: this.onLoadedExternalText.bind(this) + }, this.options.ajaxOptions) + ); + }, + onLoadedExternalText: function(transport) { + Element.removeClassName(this.form, this.options.loadingClassName); + this.editField.disabled = false; + this.editField.value = transport.responseText.stripTags(); + }, + onclickCancel: function() { + this.onComplete(); + this.leaveEditMode(); + return false; + }, + onFailure: function(transport) { + this.options.onFailure(transport); + if (this.oldInnerHTML) { + this.element.innerHTML = this.oldInnerHTML; + this.oldInnerHTML = null; + } + return false; + }, + onSubmit: function() { + // onLoading resets these so we need to save them away for the Ajax call + var form = this.form; + var value = this.editField.value; + + // do this first, sometimes the ajax call returns before we get a chance to switch on Saving... + // which means this will actually switch on Saving... *after* we've left edit mode causing Saving... + // to be displayed indefinitely + this.onLoading(); + + if (this.options.evalScripts) { + new Ajax.Request( + this.url, Object.extend({ + parameters: this.options.callback(form, value), + onComplete: this.onComplete.bind(this), + onFailure: this.onFailure.bind(this), + asynchronous:true, + evalScripts:true + }, this.options.ajaxOptions)); + } else { + new Ajax.Updater( + { success: this.element, + // don't update on failure (this could be an option) + failure: null }, + this.url, Object.extend({ + parameters: this.options.callback(form, value), + onComplete: this.onComplete.bind(this), + onFailure: this.onFailure.bind(this) + }, this.options.ajaxOptions)); + } + // stop the event to avoid a page refresh in Safari + if (arguments.length > 1) { + Event.stop(arguments[0]); + } + return false; + }, + onLoading: function() { + this.saving = true; + this.removeForm(); + this.leaveHover(); + this.showSaving(); + }, + showSaving: function() { + this.oldInnerHTML = this.element.innerHTML; + this.element.innerHTML = this.options.savingText; + Element.addClassName(this.element, this.options.savingClassName); + this.element.style.backgroundColor = this.originalBackground; + Element.show(this.element); + }, + removeForm: function() { + if(this.form) { + if (this.form.parentNode) Element.remove(this.form); + this.form = null; + } + }, + enterHover: function() { + if (this.saving) return; + this.element.style.backgroundColor = this.options.highlightcolor; + if (this.effect) { + this.effect.cancel(); + } + Element.addClassName(this.element, this.options.hoverClassName) + }, + leaveHover: function() { + if (this.options.backgroundColor) { + this.element.style.backgroundColor = this.oldBackground; + } + Element.removeClassName(this.element, this.options.hoverClassName) + if (this.saving) return; + this.effect = new Effect.Highlight(this.element, { + startcolor: this.options.highlightcolor, + endcolor: this.options.highlightendcolor, + restorecolor: this.originalBackground + }); + }, + leaveEditMode: function() { + Element.removeClassName(this.element, this.options.savingClassName); + this.removeForm(); + this.leaveHover(); + this.element.style.backgroundColor = this.originalBackground; + Element.show(this.element); + if (this.options.externalControl) { + Element.show(this.options.externalControl); + } + this.editing = false; + this.saving = false; + this.oldInnerHTML = null; + this.onLeaveEditMode(); + }, + onComplete: function(transport) { + this.leaveEditMode(); + this.options.onComplete.bind(this)(transport, this.element); + }, + onEnterEditMode: function() {}, + onLeaveEditMode: function() {}, + dispose: function() { + if (this.oldInnerHTML) { + this.element.innerHTML = this.oldInnerHTML; + } + this.leaveEditMode(); + Event.stopObserving(this.element, 'click', this.onclickListener); + Event.stopObserving(this.element, 'mouseover', this.mouseoverListener); + Event.stopObserving(this.element, 'mouseout', this.mouseoutListener); + if (this.options.externalControl) { + Event.stopObserving(this.options.externalControl, 'click', this.onclickListener); + Event.stopObserving(this.options.externalControl, 'mouseover', this.mouseoverListener); + Event.stopObserving(this.options.externalControl, 'mouseout', this.mouseoutListener); + } + } +}; + +Ajax.InPlaceCollectionEditor = Class.create(); +Object.extend(Ajax.InPlaceCollectionEditor.prototype, Ajax.InPlaceEditor.prototype); +Object.extend(Ajax.InPlaceCollectionEditor.prototype, { + createEditField: function() { + if (!this.cached_selectTag) { + var selectTag = document.createElement("select"); + var collection = this.options.collection || []; + var optionTag; + collection.each(function(e,i) { + optionTag = document.createElement("option"); + optionTag.value = (e instanceof Array) ? e[0] : e; + if(this.options.value==optionTag.value) optionTag.selected = true; + optionTag.appendChild(document.createTextNode((e instanceof Array) ? e[1] : e)); + selectTag.appendChild(optionTag); + }.bind(this)); + this.cached_selectTag = selectTag; + } + + this.editField = this.cached_selectTag; + if(this.options.loadTextURL) this.loadExternalText(); + this.form.appendChild(this.editField); + this.options.callback = function(form, value) { + return "value=" + encodeURIComponent(value); + } + } +}); + +// Delayed observer, like Form.Element.Observer, +// but waits for delay after last key input +// Ideal for live-search fields + +Form.Element.DelayedObserver = Class.create(); +Form.Element.DelayedObserver.prototype = { + initialize: function(element, delay, callback) { + this.delay = delay || 0.5; + this.element = $(element); + this.callback = callback; + this.timer = null; + this.lastValue = $F(this.element); + Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this)); + }, + delayedListener: function(event) { + if(this.lastValue == $F(this.element)) return; + if(this.timer) clearTimeout(this.timer); + this.timer = setTimeout(this.onTimerEvent.bind(this), this.delay * 1000); + this.lastValue = $F(this.element); + }, + onTimerEvent: function() { + this.timer = null; + this.callback(this.element, $F(this.element)); + } +}; diff --git a/wp-inst/wp-includes/js/scriptaculous/dragdrop.js b/wp-inst/wp-includes/js/scriptaculous/dragdrop.js new file mode 100644 index 0000000..be2a30f --- /dev/null +++ b/wp-inst/wp-includes/js/scriptaculous/dragdrop.js @@ -0,0 +1,915 @@ +// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) +// (c) 2005 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz) +// +// See scriptaculous.js for full license. + +/*--------------------------------------------------------------------------*/ + +var Droppables = { + drops: [], + + remove: function(element) { + this.drops = this.drops.reject(function(d) { return d.element==$(element) }); + }, + + add: function(element) { + element = $(element); + var options = Object.extend({ + greedy: true, + hoverclass: null, + tree: false + }, arguments[1] || {}); + + // cache containers + if(options.containment) { + options._containers = []; + var containment = options.containment; + if((typeof containment == 'object') && + (containment.constructor == Array)) { + containment.each( function(c) { options._containers.push($(c)) }); + } else { + options._containers.push($(containment)); + } + } + + if(options.accept) options.accept = [options.accept].flatten(); + + Element.makePositioned(element); // fix IE + options.element = element; + + this.drops.push(options); + }, + + findDeepestChild: function(drops) { + deepest = drops[0]; + + for (i = 1; i < drops.length; ++i) + if (Element.isParent(drops[i].element, deepest.element)) + deepest = drops[i]; + + return deepest; + }, + + isContained: function(element, drop) { + var containmentNode; + if(drop.tree) { + containmentNode = element.treeNode; + } else { + containmentNode = element.parentNode; + } + return drop._containers.detect(function(c) { return containmentNode == c }); + }, + + isAffected: function(point, element, drop) { + return ( + (drop.element!=element) && + ((!drop._containers) || + this.isContained(element, drop)) && + ((!drop.accept) || + (Element.classNames(element).detect( + function(v) { return drop.accept.include(v) } ) )) && + Position.within(drop.element, point[0], point[1]) ); + }, + + deactivate: function(drop) { + if(drop.hoverclass) + Element.removeClassName(drop.element, drop.hoverclass); + this.last_active = null; + }, + + activate: function(drop) { + if(drop.hoverclass) + Element.addClassName(drop.element, drop.hoverclass); + this.last_active = drop; + }, + + show: function(point, element) { + if(!this.drops.length) return; + var affected = []; + + if(this.last_active) this.deactivate(this.last_active); + this.drops.each( function(drop) { + if(Droppables.isAffected(point, element, drop)) + affected.push(drop); + }); + + if(affected.length>0) { + drop = Droppables.findDeepestChild(affected); + Position.within(drop.element, point[0], point[1]); + if(drop.onHover) + drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element)); + + Droppables.activate(drop); + } + }, + + fire: function(event, element) { + if(!this.last_active) return; + Position.prepare(); + + if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active)) + if (this.last_active.onDrop) + this.last_active.onDrop(element, this.last_active.element, event); + }, + + reset: function() { + if(this.last_active) + this.deactivate(this.last_active); + } +} + +var Draggables = { + drags: [], + observers: [], + + register: function(draggable) { + if(this.drags.length == 0) { + this.eventMouseUp = this.endDrag.bindAsEventListener(this); + this.eventMouseMove = this.updateDrag.bindAsEventListener(this); + this.eventKeypress = this.keyPress.bindAsEventListener(this); + + Event.observe(document, "mouseup", this.eventMouseUp); + Event.observe(document, "mousemove", this.eventMouseMove); + Event.observe(document, "keypress", this.eventKeypress); + } + this.drags.push(draggable); + }, + + unregister: function(draggable) { + this.drags = this.drags.reject(function(d) { return d==draggable }); + if(this.drags.length == 0) { + Event.stopObserving(document, "mouseup", this.eventMouseUp); + Event.stopObserving(document, "mousemove", this.eventMouseMove); + Event.stopObserving(document, "keypress", this.eventKeypress); + } + }, + + activate: function(draggable) { + window.focus(); // allows keypress events if window isn't currently focused, fails for Safari + this.activeDraggable = draggable; + }, + + deactivate: function() { + this.activeDraggable = null; + }, + + updateDrag: function(event) { + if(!this.activeDraggable) return; + var pointer = [Event.pointerX(event), Event.pointerY(event)]; + // Mozilla-based browsers fire successive mousemove events with + // the same coordinates, prevent needless redrawing (moz bug?) + if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return; + this._lastPointer = pointer; + this.activeDraggable.updateDrag(event, pointer); + }, + + endDrag: function(event) { + if(!this.activeDraggable) return; + this._lastPointer = null; + this.activeDraggable.endDrag(event); + this.activeDraggable = null; + }, + + keyPress: function(event) { + if(this.activeDraggable) + this.activeDraggable.keyPress(event); + }, + + addObserver: function(observer) { + this.observers.push(observer); + this._cacheObserverCallbacks(); + }, + + removeObserver: function(element) { // element instead of observer fixes mem leaks + this.observers = this.observers.reject( function(o) { return o.element==element }); + this._cacheObserverCallbacks(); + }, + + notify: function(eventName, draggable, event) { // 'onStart', 'onEnd', 'onDrag' + if(this[eventName+'Count'] > 0) + this.observers.each( function(o) { + if(o[eventName]) o[eventName](eventName, draggable, event); + }); + }, + + _cacheObserverCallbacks: function() { + ['onStart','onEnd','onDrag'].each( function(eventName) { + Draggables[eventName+'Count'] = Draggables.observers.select( + function(o) { return o[eventName]; } + ).length; + }); + } +} + +/*--------------------------------------------------------------------------*/ + +var Draggable = Class.create(); +Draggable.prototype = { + initialize: function(element) { + var options = Object.extend({ + handle: false, + starteffect: function(element) { + element._opacity = Element.getOpacity(element); + new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7}); + }, + reverteffect: function(element, top_offset, left_offset) { + var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02; + element._revert = new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur}); + }, + endeffect: function(element) { + var toOpacity = typeof element._opacity == 'number' ? element._opacity : 1.0 + new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity}); + }, + zindex: 1000, + revert: false, + scroll: false, + scrollSensitivity: 20, + scrollSpeed: 15, + snap: false // false, or xy or [x,y] or function(x,y){ return [x,y] } + }, arguments[1] || {}); + + this.element = $(element); + + if(options.handle && (typeof options.handle == 'string')) { + var h = Element.childrenWithClassName(this.element, options.handle, true); + if(h.length>0) this.handle = h[0]; + } + if(!this.handle) this.handle = $(options.handle); + if(!this.handle) this.handle = this.element; + + if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) + options.scroll = $(options.scroll); + + Element.makePositioned(this.element); // fix IE + + this.delta = this.currentDelta(); + this.options = options; + this.dragging = false; + + this.eventMouseDown = this.initDrag.bindAsEventListener(this); + Event.observe(this.handle, "mousedown", this.eventMouseDown); + + Draggables.register(this); + }, + + destroy: function() { + Event.stopObserving(this.handle, "mousedown", this.eventMouseDown); + Draggables.unregister(this); + }, + + currentDelta: function() { + return([ + parseInt(Element.getStyle(this.element,'left') || '0'), + parseInt(Element.getStyle(this.element,'top') || '0')]); + }, + + initDrag: function(event) { + if(Event.isLeftClick(event)) { + // abort on form elements, fixes a Firefox issue + var src = Event.element(event); + if(src.tagName && ( + src.tagName=='INPUT' || + src.tagName=='SELECT' || + src.tagName=='OPTION' || + src.tagName=='BUTTON' || + src.tagName=='TEXTAREA')) return; + + if(this.element._revert) { + this.element._revert.cancel(); + this.element._revert = null; + } + + var pointer = [Event.pointerX(event), Event.pointerY(event)]; + var pos = Position.cumulativeOffset(this.element); + this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) }); + + Draggables.activate(this); + Event.stop(event); + } + }, + + startDrag: function(event) { + this.dragging = true; + + if(this.options.zindex) { + this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0); + this.element.style.zIndex = this.options.zindex; + } + + if(this.options.ghosting) { + this._clone = this.element.cloneNode(true); + Position.absolutize(this.element); + this.element.parentNode.insertBefore(this._clone, this.element); + } + + if(this.options.scroll) { + if (this.options.scroll == window) { + var where = this._getWindowScroll(this.options.scroll); + this.originalScrollLeft = where.left; + this.originalScrollTop = where.top; + } else { + this.originalScrollLeft = this.options.scroll.scrollLeft; + this.originalScrollTop = this.options.scroll.scrollTop; + } + } + + Draggables.notify('onStart', this, event); + if(this.options.starteffect) this.options.starteffect(this.element); + }, + + updateDrag: function(event, pointer) { + if(!this.dragging) this.startDrag(event); + Position.prepare(); + Droppables.show(pointer, this.element); + Draggables.notify('onDrag', this, event); + this.draw(pointer); + if(this.options.change) this.options.change(this); + + if(this.options.scroll) { + this.stopScrolling(); + + var p; + if (this.options.scroll == window) { + with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; } + } else { + p = Position.page(this.options.scroll); + p[0] += this.options.scroll.scrollLeft; + p[1] += this.options.scroll.scrollTop; + p.push(p[0]+this.options.scroll.offsetWidth); + p.push(p[1]+this.options.scroll.offsetHeight); + } + var speed = [0,0]; + if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity); + if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity); + if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity); + if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity); + this.startScrolling(speed); + } + + // fix AppleWebKit rendering + if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0); + + Event.stop(event); + }, + + finishDrag: function(event, success) { + this.dragging = false; + + if(this.options.ghosting) { + Position.relativize(this.element); + Element.remove(this._clone); + this._clone = null; + } + + if(success) Droppables.fire(event, this.element); + Draggables.notify('onEnd', this, event); + + var revert = this.options.revert; + if(revert && typeof revert == 'function') revert = revert(this.element); + + var d = this.currentDelta(); + if(revert && this.options.reverteffect) { + this.options.reverteffect(this.element, + d[1]-this.delta[1], d[0]-this.delta[0]); + } else { + this.delta = d; + } + + if(this.options.zindex) + this.element.style.zIndex = this.originalZ; + + if(this.options.endeffect) + this.options.endeffect(this.element); + + Draggables.deactivate(this); + Droppables.reset(); + }, + + keyPress: function(event) { + if(event.keyCode!=Event.KEY_ESC) return; + this.finishDrag(event, false); + Event.stop(event); + }, + + endDrag: function(event) { + if(!this.dragging) return; + this.stopScrolling(); + this.finishDrag(event, true); + Event.stop(event); + }, + + draw: function(point) { + var pos = Position.cumulativeOffset(this.element); + var d = this.currentDelta(); + pos[0] -= d[0]; pos[1] -= d[1]; + + if(this.options.scroll && (this.options.scroll != window)) { + pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft; + pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop; + } + + var p = [0,1].map(function(i){ + return (point[i]-pos[i]-this.offset[i]) + }.bind(this)); + + if(this.options.snap) { + if(typeof this.options.snap == 'function') { + p = this.options.snap(p[0],p[1],this); + } else { + if(this.options.snap instanceof Array) { + p = p.map( function(v, i) { + return Math.round(v/this.options.snap[i])*this.options.snap[i] }.bind(this)) + } else { + p = p.map( function(v) { + return Math.round(v/this.options.snap)*this.options.snap }.bind(this)) + } + }} + + var style = this.element.style; + if((!this.options.constraint) || (this.options.constraint=='horizontal')) + style.left = p[0] + "px"; + if((!this.options.constraint) || (this.options.constraint=='vertical')) + style.top = p[1] + "px"; + if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering + }, + + stopScrolling: function() { + if(this.scrollInterval) { + clearInterval(this.scrollInterval); + this.scrollInterval = null; + Draggables._lastScrollPointer = null; + } + }, + + startScrolling: function(speed) { + this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed]; + this.lastScrolled = new Date(); + this.scrollInterval = setInterval(this.scroll.bind(this), 10); + }, + + scroll: function() { + var current = new Date(); + var delta = current - this.lastScrolled; + this.lastScrolled = current; + if(this.options.scroll == window) { + with (this._getWindowScroll(this.options.scroll)) { + if (this.scrollSpeed[0] || this.scrollSpeed[1]) { + var d = delta / 1000; + this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] ); + } + } + } else { + this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000; + this.options.scroll.scrollTop += this.scrollSpeed[1] * delta / 1000; + } + + Position.prepare(); + Droppables.show(Draggables._lastPointer, this.element); + Draggables.notify('onDrag', this); + Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer); + Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000; + Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000; + if (Draggables._lastScrollPointer[0] < 0) + Draggables._lastScrollPointer[0] = 0; + if (Draggables._lastScrollPointer[1] < 0) + Draggables._lastScrollPointer[1] = 0; + this.draw(Draggables._lastScrollPointer); + + if(this.options.change) this.options.change(this); + }, + + _getWindowScroll: function(w) { + var T, L, W, H; + with (w.document) { + if (w.document.documentElement && documentElement.scrollTop) { + T = documentElement.scrollTop; + L = documentElement.scrollLeft; + } else if (w.document.body) { + T = body.scrollTop; + L = body.scrollLeft; + } + if (w.innerWidth) { + W = w.innerWidth; + H = w.innerHeight; + } else if (w.document.documentElement && documentElement.clientWidth) { + W = documentElement.clientWidth; + H = documentElement.clientHeight; + } else { + W = body.offsetWidth; + H = body.offsetHeight + } + } + return { top: T, left: L, width: W, height: H }; + } +} + +/*--------------------------------------------------------------------------*/ + +var SortableObserver = Class.create(); +SortableObserver.prototype = { + initialize: function(element, observer) { + this.element = $(element); + this.observer = observer; + this.lastValue = Sortable.serialize(this.element); + }, + + onStart: function() { + this.lastValue = Sortable.serialize(this.element); + }, + + onEnd: function() { + Sortable.unmark(); + if(this.lastValue != Sortable.serialize(this.element)) + this.observer(this.element) + } +} + +var Sortable = { + sortables: {}, + + _findRootElement: function(element) { + while (element.tagName != "BODY") { + if(element.id && Sortable.sortables[element.id]) return element; + element = element.parentNode; + } + }, + + options: function(element) { + element = Sortable._findRootElement($(element)); + if(!element) return; + return Sortable.sortables[element.id]; + }, + + destroy: function(element){ + var s = Sortable.options(element); + + if(s) { + Draggables.removeObserver(s.element); + s.droppables.each(function(d){ Droppables.remove(d) }); + s.draggables.invoke('destroy'); + + delete Sortable.sortables[s.element.id]; + } + }, + + create: function(element) { + element = $(element); + var options = Object.extend({ + element: element, + tag: 'li', // assumes li children, override with tag: 'tagname' + dropOnEmpty: false, + tree: false, + treeTag: 'ul', + overlap: 'vertical', // one of 'vertical', 'horizontal' + constraint: 'vertical', // one of 'vertical', 'horizontal', false + containment: element, // also takes array of elements (or id's); or false + handle: false, // or a CSS class + only: false, + hoverclass: null, + ghosting: false, + scroll: false, + scrollSensitivity: 20, + scrollSpeed: 15, + format: /^[^_]*_(.*)$/, + onChange: Prototype.emptyFunction, + onUpdate: Prototype.emptyFunction + }, arguments[1] || {}); + + // clear any old sortable with same element + this.destroy(element); + + // build options for the draggables + var options_for_draggable = { + revert: true, + scroll: options.scroll, + scrollSpeed: options.scrollSpeed, + scrollSensitivity: options.scrollSensitivity, + ghosting: options.ghosting, + constraint: options.constraint, + handle: options.handle }; + + if(options.starteffect) + options_for_draggable.starteffect = options.starteffect; + + if(options.reverteffect) + options_for_draggable.reverteffect = options.reverteffect; + else + if(options.ghosting) options_for_draggable.reverteffect = function(element) { + element.style.top = 0; + element.style.left = 0; + }; + + if(options.endeffect) + options_for_draggable.endeffect = options.endeffect; + + if(options.zindex) + options_for_draggable.zindex = options.zindex; + + // build options for the droppables + var options_for_droppable = { + overlap: options.overlap, + containment: options.containment, + tree: options.tree, + hoverclass: options.hoverclass, + onHover: Sortable.onHover + //greedy: !options.dropOnEmpty + } + + var options_for_tree = { + onHover: Sortable.onEmptyHover, + overlap: options.overlap, + containment: options.containment, + hoverclass: options.hoverclass + } + + // fix for gecko engine + Element.cleanWhitespace(element); + + options.draggables = []; + options.droppables = []; + + // drop on empty handling + if(options.dropOnEmpty || options.tree) { + Droppables.add(element, options_for_tree); + options.droppables.push(element); + } + + (this.findElements(element, options) || []).each( function(e) { + // handles are per-draggable + var handle = options.handle ? + Element.childrenWithClassName(e, options.handle)[0] : e; + options.draggables.push( + new Draggable(e, Object.extend(options_for_draggable, { handle: handle }))); + Droppables.add(e, options_for_droppable); + if(options.tree) e.treeNode = element; + options.droppables.push(e); + }); + + if(options.tree) { + (Sortable.findTreeElements(element, options) || []).each( function(e) { + Droppables.add(e, options_for_tree); + e.treeNode = element; + options.droppables.push(e); + }); + } + + // keep reference + this.sortables[element.id] = options; + + // for onupdate + Draggables.addObserver(new SortableObserver(element, options.onUpdate)); + + }, + + // return all suitable-for-sortable elements in a guaranteed order + findElements: function(element, options) { + return Element.findChildren( + element, options.only, options.tree ? true : false, options.tag); + }, + + findTreeElements: function(element, options) { + return Element.findChildren( + element, options.only, options.tree ? true : false, options.treeTag); + }, + + onHover: function(element, dropon, overlap) { + if(Element.isParent(dropon, element)) return; + + if(overlap > .33 && overlap < .66 && Sortable.options(dropon).tree) { + return; + } else if(overlap>0.5) { + Sortable.mark(dropon, 'before'); + if(dropon.previousSibling != element) { + var oldParentNode = element.parentNode; + element.style.visibility = "hidden"; // fix gecko rendering + dropon.parentNode.insertBefore(element, dropon); + if(dropon.parentNode!=oldParentNode) + Sortable.options(oldParentNode).onChange(element); + Sortable.options(dropon.parentNode).onChange(element); + } + } else { + Sortable.mark(dropon, 'after'); + var nextElement = dropon.nextSibling || null; + if(nextElement != element) { + var oldParentNode = element.parentNode; + element.style.visibility = "hidden"; // fix gecko rendering + dropon.parentNode.insertBefore(element, nextElement); + if(dropon.parentNode!=oldParentNode) + Sortable.options(oldParentNode).onChange(element); + Sortable.options(dropon.parentNode).onChange(element); + } + } + }, + + onEmptyHover: function(element, dropon, overlap) { + var oldParentNode = element.parentNode; + var droponOptions = Sortable.options(dropon); + + if(!Element.isParent(dropon, element)) { + var index; + + var children = Sortable.findElements(dropon, {tag: droponOptions.tag}); + var child = null; + + if(children) { + var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap); + + for (index = 0; index < children.length; index += 1) { + if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) { + offset -= Element.offsetSize (children[index], droponOptions.overlap); + } else if (offset - (Element.offsetSize (children[index], droponOptions.overlap) / 2) >= 0) { + child = index + 1 < children.length ? children[index + 1] : null; + break; + } else { + child = children[index]; + break; + } + } + } + + dropon.insertBefore(element, child); + + Sortable.options(oldParentNode).onChange(element); + droponOptions.onChange(element); + } + }, + + unmark: function() { + if(Sortable._marker) Element.hide(Sortable._marker); + }, + + mark: function(dropon, position) { + // mark on ghosting only + var sortable = Sortable.options(dropon.parentNode); + if(sortable && !sortable.ghosting) return; + + if(!Sortable._marker) { + Sortable._marker = $('dropmarker') || document.createElement('DIV'); + Element.hide(Sortable._marker); + Element.addClassName(Sortable._marker, 'dropmarker'); + Sortable._marker.style.position = 'absolute'; + document.getElementsByTagName("body").item(0).appendChild(Sortable._marker); + } + var offsets = Position.cumulativeOffset(dropon); + Sortable._marker.style.left = offsets[0] + 'px'; + Sortable._marker.style.top = offsets[1] + 'px'; + + if(position=='after') + if(sortable.overlap == 'horizontal') + Sortable._marker.style.left = (offsets[0]+dropon.clientWidth) + 'px'; + else + Sortable._marker.style.top = (offsets[1]+dropon.clientHeight) + 'px'; + + Element.show(Sortable._marker); + }, + + _tree: function(element, options, parent) { + var children = Sortable.findElements(element, options) || []; + + for (var i = 0; i < children.length; ++i) { + var match = children[i].id.match(options.format); + + if (!match) continue; + + var child = { + id: encodeURIComponent(match ? match[1] : null), + element: element, + parent: parent, + children: new Array, + position: parent.children.length, + container: Sortable._findChildrenElement(children[i], options.treeTag.toUpperCase()) + } + + /* Get the element containing the children and recurse over it */ + if (child.container) + this._tree(child.container, options, child) + + parent.children.push (child); + } + + return parent; + }, + + /* Finds the first element of the given tag type within a parent element. + Used for finding the first LI[ST] within a L[IST]I[TEM].*/ + _findChildrenElement: function (element, containerTag) { + if (element && element.hasChildNodes) + for (var i = 0; i < element.childNodes.length; ++i) + if (element.childNodes[i].tagName == containerTag) + return element.childNodes[i]; + + return null; + }, + + tree: function(element) { + element = $(element); + var sortableOptions = this.options(element); + var options = Object.extend({ + tag: sortableOptions.tag, + treeTag: sortableOptions.treeTag, + only: sortableOptions.only, + name: element.id, + format: sortableOptions.format + }, arguments[1] || {}); + + var root = { + id: null, + parent: null, + children: new Array, + container: element, + position: 0 + } + + return Sortable._tree (element, options, root); + }, + + /* Construct a [i] index for a particular node */ + _constructIndex: function(node) { + var index = ''; + do { + if (node.id) index = '[' + node.position + ']' + index; + } while ((node = node.parent) != null); + return index; + }, + + sequence: function(element) { + element = $(element); + var options = Object.extend(this.options(element), arguments[1] || {}); + + return $(this.findElements(element, options) || []).map( function(item) { + return item.id.match(options.format) ? item.id.match(options.format)[1] : ''; + }); + }, + + setSequence: function(element, new_sequence) { + element = $(element); + var options = Object.extend(this.options(element), arguments[2] || {}); + + var nodeMap = {}; + this.findElements(element, options).each( function(n) { + if (n.id.match(options.format)) + nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode]; + n.parentNode.removeChild(n); + }); + + new_sequence.each(function(ident) { + var n = nodeMap[ident]; + if (n) { + n[1].appendChild(n[0]); + delete nodeMap[ident]; + } + }); + }, + + serialize: function(element) { + element = $(element); + var options = Object.extend(Sortable.options(element), arguments[1] || {}); + var name = encodeURIComponent( + (arguments[1] && arguments[1].name) ? arguments[1].name : element.id); + + if (options.tree) { + return Sortable.tree(element, arguments[1]).children.map( function (item) { + return [name + Sortable._constructIndex(item) + "=" + + encodeURIComponent(item.id)].concat(item.children.map(arguments.callee)); + }).flatten().join('&'); + } else { + return Sortable.sequence(element, arguments[1]).map( function(item) { + return name + "[]=" + encodeURIComponent(item); + }).join('&'); + } + } +} + +/* Returns true if child is contained within element */ +Element.isParent = function(child, element) { + if (!child.parentNode || child == element) return false; + + if (child.parentNode == element) return true; + + return Element.isParent(child.parentNode, element); +} + +Element.findChildren = function(element, only, recursive, tagName) { + if(!element.hasChildNodes()) return null; + tagName = tagName.toUpperCase(); + if(only) only = [only].flatten(); + var elements = []; + $A(element.childNodes).each( function(e) { + if(e.tagName && e.tagName.toUpperCase()==tagName && + (!only || (Element.classNames(e).detect(function(v) { return only.include(v) })))) + elements.push(e); + if(recursive) { + var grandchildren = Element.findChildren(e, only, recursive, tagName); + if(grandchildren) elements.push(grandchildren); + } + }); + + return (elements.length>0 ? elements.flatten() : []); +} + +Element.offsetSize = function (element, type) { + if (type == 'vertical' || type == 'height') + return element.offsetHeight; + else + return element.offsetWidth; +}
\ No newline at end of file diff --git a/wp-inst/wp-includes/js/scriptaculous/effects.js b/wp-inst/wp-includes/js/scriptaculous/effects.js new file mode 100644 index 0000000..0864323 --- /dev/null +++ b/wp-inst/wp-includes/js/scriptaculous/effects.js @@ -0,0 +1,958 @@ +// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) +// Contributors: +// Justin Palmer (http://encytemedia.com/) +// Mark Pilgrim (http://diveintomark.org/) +// Martin Bialasinki +// +// See scriptaculous.js for full license. + +// converts rgb() and #xxx to #xxxxxx format, +// returns self (or first argument) if not convertable +String.prototype.parseColor = function() { + var color = '#'; + if(this.slice(0,4) == 'rgb(') { + var cols = this.slice(4,this.length-1).split(','); + var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3); + } else { + if(this.slice(0,1) == '#') { + if(this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase(); + if(this.length==7) color = this.toLowerCase(); + } + } + return(color.length==7 ? color : (arguments[0] || this)); +} + +/*--------------------------------------------------------------------------*/ + +Element.collectTextNodes = function(element) { + return $A($(element).childNodes).collect( function(node) { + return (node.nodeType==3 ? node.nodeValue : + (node.hasChildNodes() ? Element.collectTextNodes(node) : '')); + }).flatten().join(''); +} + +Element.collectTextNodesIgnoreClass = function(element, className) { + return $A($(element).childNodes).collect( function(node) { + return (node.nodeType==3 ? node.nodeValue : + ((node.hasChildNodes() && !Element.hasClassName(node,className)) ? + Element.collectTextNodesIgnoreClass(node, className) : '')); + }).flatten().join(''); +} + +Element.setContentZoom = function(element, percent) { + element = $(element); + Element.setStyle(element, {fontSize: (percent/100) + 'em'}); + if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0); +} + +Element.getOpacity = function(element){ + var opacity; + if (opacity = Element.getStyle(element, 'opacity')) + return parseFloat(opacity); + if (opacity = (Element.getStyle(element, 'filter') || '').match(/alpha\(opacity=(.*)\)/)) + if(opacity[1]) return parseFloat(opacity[1]) / 100; + return 1.0; +} + +Element.setOpacity = function(element, value){ + element= $(element); + if (value == 1){ + Element.setStyle(element, { opacity: + (/Gecko/.test(navigator.userAgent) && !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ? + 0.999999 : null }); + if(/MSIE/.test(navigator.userAgent)) + Element.setStyle(element, {filter: Element.getStyle(element,'filter').replace(/alpha\([^\)]*\)/gi,'')}); + } else { + if(value < 0.00001) value = 0; + Element.setStyle(element, {opacity: value}); + if(/MSIE/.test(navigator.userAgent)) + Element.setStyle(element, + { filter: Element.getStyle(element,'filter').replace(/alpha\([^\)]*\)/gi,'') + + 'alpha(opacity='+value*100+')' }); + } +} + +Element.getInlineOpacity = function(element){ + return $(element).style.opacity || ''; +} + +Element.childrenWithClassName = function(element, className, findFirst) { + var classNameRegExp = new RegExp("(^|\\s)" + className + "(\\s|$)"); + var results = $A($(element).getElementsByTagName('*'))[findFirst ? 'detect' : 'select']( function(c) { + return (c.className && c.className.match(classNameRegExp)); + }); + if(!results) results = []; + return results; +} + +Element.forceRerendering = function(element) { + try { + element = $(element); + var n = document.createTextNode(' '); + element.appendChild(n); + element.removeChild(n); + } catch(e) { } +}; + +/*--------------------------------------------------------------------------*/ + +Array.prototype.call = function() { + var args = arguments; + this.each(function(f){ f.apply(this, args) }); +} + +/*--------------------------------------------------------------------------*/ + +var Effect = { + tagifyText: function(element) { + var tagifyStyle = 'position:relative'; + if(/MSIE/.test(navigator.userAgent)) tagifyStyle += ';zoom:1'; + element = $(element); + $A(element.childNodes).each( function(child) { + if(child.nodeType==3) { + child.nodeValue.toArray().each( function(character) { + element.insertBefore( + Builder.node('span',{style: tagifyStyle}, + character == ' ' ? String.fromCharCode(160) : character), + child); + }); + Element.remove(child); + } + }); + }, + multiple: function(element, effect) { + var elements; + if(((typeof element == 'object') || + (typeof element == 'function')) && + (element.length)) + elements = element; + else + elements = $(element).childNodes; + + var options = Object.extend({ + speed: 0.1, + delay: 0.0 + }, arguments[2] || {}); + var masterDelay = options.delay; + + $A(elements).each( function(element, index) { + new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay })); + }); + }, + PAIRS: { + 'slide': ['SlideDown','SlideUp'], + 'blind': ['BlindDown','BlindUp'], + 'appear': ['Appear','Fade'] + }, + toggle: function(element, effect) { + element = $(element); + effect = (effect || 'appear').toLowerCase(); + var options = Object.extend({ + queue: { position:'end', scope:(element.id || 'global'), limit: 1 } + }, arguments[2] || {}); + Effect[element.visible() ? + Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options); + } +}; + +var Effect2 = Effect; // deprecated + +/* ------------- transitions ------------- */ + +Effect.Transitions = {} + +Effect.Transitions.linear = function(pos) { + return pos; +} +Effect.Transitions.sinoidal = function(pos) { + return (-Math.cos(pos*Math.PI)/2) + 0.5; +} +Effect.Transitions.reverse = function(pos) { + return 1-pos; +} +Effect.Transitions.flicker = function(pos) { + return ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4; +} +Effect.Transitions.wobble = function(pos) { + return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5; +} +Effect.Transitions.pulse = function(pos) { + return (Math.floor(pos*10) % 2 == 0 ? + (pos*10-Math.floor(pos*10)) : 1-(pos*10-Math.floor(pos*10))); +} +Effect.Transitions.none = function(pos) { + return 0; +} +Effect.Transitions.full = function(pos) { + return 1; +} + +/* ------------- core effects ------------- */ + +Effect.ScopedQueue = Class.create(); +Object.extend(Object.extend(Effect.ScopedQueue.prototype, Enumerable), { + initialize: function() { + this.effects = []; + this.interval = null; + }, + _each: function(iterator) { + this.effects._each(iterator); + }, + add: function(effect) { + var timestamp = new Date().getTime(); + + var position = (typeof effect.options.queue == 'string') ? + effect.options.queue : effect.options.queue.position; + + switch(position) { + case 'front': + // move unstarted effects after this effect + this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) { + e.startOn += effect.finishOn; + e.finishOn += effect.finishOn; + }); + break; + case 'end': + // start effect after last queued effect has finished + timestamp = this.effects.pluck('finishOn').max() || timestamp; + break; + } + + effect.startOn += timestamp; + effect.finishOn += timestamp; + + if(!effect.options.queue.limit || (this.effects.length < effect.options.queue.limit)) + this.effects.push(effect); + + if(!this.interval) + this.interval = setInterval(this.loop.bind(this), 40); + }, + remove: function(effect) { + this.effects = this.effects.reject(function(e) { return e==effect }); + if(this.effects.length == 0) { + clearInterval(this.interval); + this.interval = null; + } + }, + loop: function() { + var timePos = new Date().getTime(); + this.effects.invoke('loop', timePos); + } +}); + +Effect.Queues = { + instances: $H(), + get: function(queueName) { + if(typeof queueName != 'string') return queueName; + + if(!this.instances[queueName]) + this.instances[queueName] = new Effect.ScopedQueue(); + + return this.instances[queueName]; + } +} +Effect.Queue = Effect.Queues.get('global'); + +Effect.DefaultOptions = { + transition: Effect.Transitions.sinoidal, + duration: 1.0, // seconds + fps: 25.0, // max. 25fps due to Effect.Queue implementation + sync: false, // true for combining + from: 0.0, + to: 1.0, + delay: 0.0, + queue: 'parallel' +} + +Effect.Base = function() {}; +Effect.Base.prototype = { + position: null, + start: function(options) { + this.options = Object.extend(Object.extend({},Effect.DefaultOptions), options || {}); + this.currentFrame = 0; + this.state = 'idle'; + this.startOn = this.options.delay*1000; + this.finishOn = this.startOn + (this.options.duration*1000); + this.event('beforeStart'); + if(!this.options.sync) + Effect.Queues.get(typeof this.options.queue == 'string' ? + 'global' : this.options.queue.scope).add(this); + }, + loop: function(timePos) { + if(timePos >= this.startOn) { + if(timePos >= this.finishOn) { + this.render(1.0); + this.cancel(); + this.event('beforeFinish'); + if(this.finish) this.finish(); + this.event('afterFinish'); + return; + } + var pos = (timePos - this.startOn) / (this.finishOn - this.startOn); + var frame = Math.round(pos * this.options.fps * this.options.duration); + if(frame > this.currentFrame) { + this.render(pos); + this.currentFrame = frame; + } + } + }, + render: function(pos) { + if(this.state == 'idle') { + this.state = 'running'; + this.event('beforeSetup'); + if(this.setup) this.setup(); + this.event('afterSetup'); + } + if(this.state == 'running') { + if(this.options.transition) pos = this.options.transition(pos); + pos *= (this.options.to-this.options.from); + pos += this.options.from; + this.position = pos; + this.event('beforeUpdate'); + if(this.update) this.update(pos); + this.event('afterUpdate'); + } + }, + cancel: function() { + if(!this.options.sync) + Effect.Queues.get(typeof this.options.queue == 'string' ? + 'global' : this.options.queue.scope).remove(this); + this.state = 'finished'; + }, + event: function(eventName) { + if(this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this); + if(this.options[eventName]) this.options[eventName](this); + }, + inspect: function() { + return '#<Effect:' + $H(this).inspect() + ',options:' + $H(this.options).inspect() + '>'; + } +} + +Effect.Parallel = Class.create(); +Object.extend(Object.extend(Effect.Parallel.prototype, Effect.Base.prototype), { + initialize: function(effects) { + this.effects = effects || []; + this.start(arguments[1]); + }, + update: function(position) { + this.effects.invoke('render', position); + }, + finish: function(position) { + this.effects.each( function(effect) { + effect.render(1.0); + effect.cancel(); + effect.event('beforeFinish'); + if(effect.finish) effect.finish(position); + effect.event('afterFinish'); + }); + } +}); + +Effect.Opacity = Class.create(); +Object.extend(Object.extend(Effect.Opacity.prototype, Effect.Base.prototype), { + initialize: function(element) { + this.element = $(element); + // make this work on IE on elements without 'layout' + if(/MSIE/.test(navigator.userAgent) && (!this.element.hasLayout)) + this.element.setStyle({zoom: 1}); + var options = Object.extend({ + from: this.element.getOpacity() || 0.0, + to: 1.0 + }, arguments[1] || {}); + this.start(options); + }, + update: function(position) { + this.element.setOpacity(position); + } +}); + +Effect.Move = Class.create(); +Object.extend(Object.extend(Effect.Move.prototype, Effect.Base.prototype), { + initialize: function(element) { + this.element = $(element); + var options = Object.extend({ + x: 0, + y: 0, + mode: 'relative' + }, arguments[1] || {}); + this.start(options); + }, + setup: function() { + // Bug in Opera: Opera returns the "real" position of a static element or + // relative element that does not have top/left explicitly set. + // ==> Always set top and left for position relative elements in your stylesheets + // (to 0 if you do not need them) + this.element.makePositioned(); + this.originalLeft = parseFloat(this.element.getStyle('left') || '0'); + this.originalTop = parseFloat(this.element.getStyle('top') || '0'); + if(this.options.mode == 'absolute') { + // absolute movement, so we need to calc deltaX and deltaY + this.options.x = this.options.x - this.originalLeft; + this.options.y = this.options.y - this.originalTop; + } + }, + update: function(position) { + this.element.setStyle({ + left: this.options.x * position + this.originalLeft + 'px', + top: this.options.y * position + this.originalTop + 'px' + }); + } +}); + +// for backwards compatibility +Effect.MoveBy = function(element, toTop, toLeft) { + return new Effect.Move(element, + Object.extend({ x: toLeft, y: toTop }, arguments[3] || {})); +}; + +Effect.Scale = Class.create(); +Object.extend(Object.extend(Effect.Scale.prototype, Effect.Base.prototype), { + initialize: function(element, percent) { + this.element = $(element) + var options = Object.extend({ + scaleX: true, + scaleY: true, + scaleContent: true, + scaleFromCenter: false, + scaleMode: 'box', // 'box' or 'contents' or {} with provided values + scaleFrom: 100.0, + scaleTo: percent + }, arguments[2] || {}); + this.start(options); + }, + setup: function() { + this.restoreAfterFinish = this.options.restoreAfterFinish || false; + this.elementPositioning = this.element.getStyle('position'); + + this.originalStyle = {}; + ['top','left','width','height','fontSize'].each( function(k) { + this.originalStyle[k] = this.element.style[k]; + }.bind(this)); + + this.originalTop = this.element.offsetTop; + this.originalLeft = this.element.offsetLeft; + + var fontSize = this.element.getStyle('font-size') || '100%'; + ['em','px','%'].each( function(fontSizeType) { + if(fontSize.indexOf(fontSizeType)>0) { + this.fontSize = parseFloat(fontSize); + this.fontSizeType = fontSizeType; + } + }.bind(this)); + + this.factor = (this.options.scaleTo - this.options.scaleFrom)/100; + + this.dims = null; + if(this.options.scaleMode=='box') + this.dims = [this.element.offsetHeight, this.element.offsetWidth]; + if(/^content/.test(this.options.scaleMode)) + this.dims = [this.element.scrollHeight, this.element.scrollWidth]; + if(!this.dims) + this.dims = [this.options.scaleMode.originalHeight, + this.options.scaleMode.originalWidth]; + }, + update: function(position) { + var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position); + if(this.options.scaleContent && this.fontSize) + this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType }); + this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale); + }, + finish: function(position) { + if (this.restoreAfterFinish) this.element.setStyle(this.originalStyle); + }, + setDimensions: function(height, width) { + var d = {}; + if(this.options.scaleX) d.width = width + 'px'; + if(this.options.scaleY) d.height = height + 'px'; + if(this.options.scaleFromCenter) { + var topd = (height - this.dims[0])/2; + var leftd = (width - this.dims[1])/2; + if(this.elementPositioning == 'absolute') { + if(this.options.scaleY) d.top = this.originalTop-topd + 'px'; + if(this.options.scaleX) d.left = this.originalLeft-leftd + 'px'; + } else { + if(this.options.scaleY) d.top = -topd + 'px'; + if(this.options.scaleX) d.left = -leftd + 'px'; + } + } + this.element.setStyle(d); + } +}); + +Effect.Highlight = Class.create(); +Object.extend(Object.extend(Effect.Highlight.prototype, Effect.Base.prototype), { + initialize: function(element) { + this.element = $(element); + var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || {}); + this.start(options); + }, + setup: function() { + // Prevent executing on elements not in the layout flow + if(this.element.getStyle('display')=='none') { this.cancel(); return; } + // Disable background image during the effect + this.oldStyle = { + backgroundImage: this.element.getStyle('background-image') }; + this.element.setStyle({backgroundImage: 'none'}); + if(!this.options.endcolor) + this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff'); + if(!this.options.restorecolor) + this.options.restorecolor = this.element.getStyle('background-color'); + // init color calculations + this._base = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this)); + this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this)); + }, + update: function(position) { + this.element.setStyle({backgroundColor: $R(0,2).inject('#',function(m,v,i){ + return m+(Math.round(this._base[i]+(this._delta[i]*position)).toColorPart()); }.bind(this)) }); + }, + finish: function() { + this.element.setStyle(Object.extend(this.oldStyle, { + backgroundColor: this.options.restorecolor + })); + } +}); + +Effect.ScrollTo = Class.create(); +Object.extend(Object.extend(Effect.ScrollTo.prototype, Effect.Base.prototype), { + initialize: function(element) { + this.element = $(element); + this.start(arguments[1] || {}); + }, + setup: function() { + Position.prepare(); + var offsets = Position.cumulativeOffset(this.element); + if(this.options.offset) offsets[1] += this.options.offset; + var max = window.innerHeight ? + window.height - window.innerHeight : + document.body.scrollHeight - + (document.documentElement.clientHeight ? + document.documentElement.clientHeight : document.body.clientHeight); + this.scrollStart = Position.deltaY; + this.delta = (offsets[1] > max ? max : offsets[1]) - this.scrollStart; + }, + update: function(position) { + Position.prepare(); + window.scrollTo(Position.deltaX, + this.scrollStart + (position*this.delta)); + } +}); + +/* ------------- combination effects ------------- */ + +Effect.Fade = function(element) { + element = $(element); + var oldOpacity = element.getInlineOpacity(); + var options = Object.extend({ + from: element.getOpacity() || 1.0, + to: 0.0, + afterFinishInternal: function(effect) { + if(effect.options.to!=0) return; + effect.element.hide(); + effect.element.setStyle({opacity: oldOpacity}); + }}, arguments[1] || {}); + return new Effect.Opacity(element,options); +} + +Effect.Appear = function(element) { + element = $(element); + var options = Object.extend({ + from: (element.getStyle('display') == 'none' ? 0.0 : element.getOpacity() || 0.0), + to: 1.0, + // force Safari to render floated elements properly + afterFinishInternal: function(effect) { + effect.element.forceRerendering(); + }, + beforeSetup: function(effect) { + effect.element.setOpacity(effect.options.from); + effect.element.show(); + }}, arguments[1] || {}); + return new Effect.Opacity(element,options); +} + +Effect.Puff = function(element) { + element = $(element); + var oldStyle = { opacity: element.getInlineOpacity(), position: element.getStyle('position') }; + return new Effect.Parallel( + [ new Effect.Scale(element, 200, + { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }), + new Effect.Opacity(element, { sync: true, to: 0.0 } ) ], + Object.extend({ duration: 1.0, + beforeSetupInternal: function(effect) { + effect.effects[0].element.setStyle({position: 'absolute'}); }, + afterFinishInternal: function(effect) { + effect.effects[0].element.hide(); + effect.effects[0].element.setStyle(oldStyle); } + }, arguments[1] || {}) + ); +} + +Effect.BlindUp = function(element) { + element = $(element); + element.makeClipping(); + return new Effect.Scale(element, 0, + Object.extend({ scaleContent: false, + scaleX: false, + restoreAfterFinish: true, + afterFinishInternal: function(effect) { + effect.element.hide(); + effect.element.undoClipping(); + } + }, arguments[1] || {}) + ); +} + +Effect.BlindDown = function(element) { + element = $(element); + var elementDimensions = element.getDimensions(); + return new Effect.Scale(element, 100, + Object.extend({ scaleContent: false, + scaleX: false, + scaleFrom: 0, + scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width}, + restoreAfterFinish: true, + afterSetup: function(effect) { + effect.element.makeClipping(); + effect.element.setStyle({height: '0px'}); + effect.element.show(); + }, + afterFinishInternal: function(effect) { + effect.element.undoClipping(); + } + }, arguments[1] || {}) + ); +} + +Effect.SwitchOff = function(element) { + element = $(element); + var oldOpacity = element.getInlineOpacity(); + return new Effect.Appear(element, { + duration: 0.4, + from: 0, + transition: Effect.Transitions.flicker, + afterFinishInternal: function(effect) { + new Effect.Scale(effect.element, 1, { + duration: 0.3, scaleFromCenter: true, + scaleX: false, scaleContent: false, restoreAfterFinish: true, + beforeSetup: function(effect) { + effect.element.makePositioned(); + effect.element.makeClipping(); + }, + afterFinishInternal: function(effect) { + effect.element.hide(); + effect.element.undoClipping(); + effect.element.undoPositioned(); + effect.element.setStyle({opacity: oldOpacity}); + } + }) + } + }); +} + +Effect.DropOut = function(element) { + element = $(element); + var oldStyle = { + top: element.getStyle('top'), + left: element.getStyle('left'), + opacity: element.getInlineOpacity() }; + return new Effect.Parallel( + [ new Effect.Move(element, {x: 0, y: 100, sync: true }), + new Effect.Opacity(element, { sync: true, to: 0.0 }) ], + Object.extend( + { duration: 0.5, + beforeSetup: function(effect) { + effect.effects[0].element.makePositioned(); + }, + afterFinishInternal: function(effect) { + effect.effects[0].element.hide(); + effect.effects[0].element.undoPositioned(); + effect.effects[0].element.setStyle(oldStyle); + } + }, arguments[1] || {})); +} + +Effect.Shake = function(element) { + element = $(element); + var oldStyle = { + top: element.getStyle('top'), + left: element.getStyle('left') }; + return new Effect.Move(element, + { x: 20, y: 0, duration: 0.05, afterFinishInternal: function(effect) { + new Effect.Move(effect.element, + { x: -40, y: 0, duration: 0.1, afterFinishInternal: function(effect) { + new Effect.Move(effect.element, + { x: 40, y: 0, duration: 0.1, afterFinishInternal: function(effect) { + new Effect.Move(effect.element, + { x: -40, y: 0, duration: 0.1, afterFinishInternal: function(effect) { + new Effect.Move(effect.element, + { x: 40, y: 0, duration: 0.1, afterFinishInternal: function(effect) { + new Effect.Move(effect.element, + { x: -20, y: 0, duration: 0.05, afterFinishInternal: function(effect) { + effect.element.undoPositioned(); + effect.element.setStyle(oldStyle); + }}) }}) }}) }}) }}) }}); +} + +Effect.SlideDown = function(element) { + element = $(element); + element.cleanWhitespace(); + // SlideDown need to have the content of the element wrapped in a container element with fixed height! + var oldInnerBottom = $(element.firstChild).getStyle('bottom'); + var elementDimensions = element.getDimensions(); + return new Effect.Scale(element, 100, Object.extend({ + scaleContent: false, + scaleX: false, + scaleFrom: window.opera ? 0 : 1, + scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width}, + restoreAfterFinish: true, + afterSetup: function(effect) { + effect.element.makePositioned(); + effect.element.firstChild.makePositioned(); + if(window.opera) effect.element.setStyle({top: ''}); + effect.element.makeClipping(); + effect.element.setStyle({height: '0px'}); + effect.element.show(); }, + afterUpdateInternal: function(effect) { + effect.element.firstChild.setStyle({bottom: + (effect.dims[0] - effect.element.clientHeight) + 'px' }); + }, + afterFinishInternal: function(effect) { + effect.element.undoClipping(); + // IE will crash if child is undoPositioned first + if(/MSIE/.test(navigator.userAgent)){ + effect.element.undoPositioned(); + effect.element.firstChild.undoPositioned(); + }else{ + effect.element.firstChild.undoPositioned(); + effect.element.undoPositioned(); + } + effect.element.firstChild.setStyle({bottom: oldInnerBottom}); } + }, arguments[1] || {}) + ); +} + +Effect.SlideUp = function(element) { + element = $(element); + element.cleanWhitespace(); + var oldInnerBottom = $(element.firstChild).getStyle('bottom'); + return new Effect.Scale(element, window.opera ? 0 : 1, + Object.extend({ scaleContent: false, + scaleX: false, + scaleMode: 'box', + scaleFrom: 100, + restoreAfterFinish: true, + beforeStartInternal: function(effect) { + effect.element.makePositioned(); + effect.element.firstChild.makePositioned(); + if(window.opera) effect.element.setStyle({top: ''}); + effect.element.makeClipping(); + effect.element.show(); }, + afterUpdateInternal: function(effect) { + effect.element.firstChild.setStyle({bottom: + (effect.dims[0] - effect.element.clientHeight) + 'px' }); }, + afterFinishInternal: function(effect) { + effect.element.hide(); + effect.element.undoClipping(); + effect.element.firstChild.undoPositioned(); + effect.element.undoPositioned(); + effect.element.setStyle({bottom: oldInnerBottom}); } + }, arguments[1] || {}) + ); +} + +// Bug in opera makes the TD containing this element expand for a instance after finish +Effect.Squish = function(element) { + return new Effect.Scale(element, window.opera ? 1 : 0, + { restoreAfterFinish: true, + beforeSetup: function(effect) { + effect.element.makeClipping(effect.element); }, + afterFinishInternal: function(effect) { + effect.element.hide(effect.element); + effect.element.undoClipping(effect.element); } + }); +} + +Effect.Grow = function(element) { + element = $(element); + var options = Object.extend({ + direction: 'center', + moveTransition: Effect.Transitions.sinoidal, + scaleTransition: Effect.Transitions.sinoidal, + opacityTransition: Effect.Transitions.full + }, arguments[1] || {}); + var oldStyle = { + top: element.style.top, + left: element.style.left, + height: element.style.height, + width: element.style.width, + opacity: element.getInlineOpacity() }; + + var dims = element.getDimensions(); + var initialMoveX, initialMoveY; + var moveX, moveY; + + switch (options.direction) { + case 'top-left': + initialMoveX = initialMoveY = moveX = moveY = 0; + break; + case 'top-right': + initialMoveX = dims.width; + initialMoveY = moveY = 0; + moveX = -dims.width; + break; + case 'bottom-left': + initialMoveX = moveX = 0; + initialMoveY = dims.height; + moveY = -dims.height; + break; + case 'bottom-right': + initialMoveX = dims.width; + initialMoveY = dims.height; + moveX = -dims.width; + moveY = -dims.height; + break; + case 'center': + initialMoveX = dims.width / 2; + initialMoveY = dims.height / 2; + moveX = -dims.width / 2; + moveY = -dims.height / 2; + break; + } + + return new Effect.Move(element, { + x: initialMoveX, + y: initialMoveY, + duration: 0.01, + beforeSetup: function(effect) { + effect.element.hide(); + effect.element.makeClipping(); + effect.element.makePositioned(); + }, + afterFinishInternal: function(effect) { + new Effect.Parallel( + [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }), + new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }), + new Effect.Scale(effect.element, 100, { + scaleMode: { originalHeight: dims.height, originalWidth: dims.width }, + sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true}) + ], Object.extend({ + beforeSetup: function(effect) { + effect.effects[0].element.setStyle({height: '0px'}); + effect.effects[0].element.show(); + }, + afterFinishInternal: function(effect) { + effect.effects[0].element.undoClipping(); + effect.effects[0].element.undoPositioned(); + effect.effects[0].element.setStyle(oldStyle); + } + }, options) + ) + } + }); +} + +Effect.Shrink = function(element) { + element = $(element); + var options = Object.extend({ + direction: 'center', + moveTransition: Effect.Transitions.sinoidal, + scaleTransition: Effect.Transitions.sinoidal, + opacityTransition: Effect.Transitions.none + }, arguments[1] || {}); + var oldStyle = { + top: element.style.top, + left: element.style.left, + height: element.style.height, + width: element.style.width, + opacity: element.getInlineOpacity() }; + + var dims = element.getDimensions(); + var moveX, moveY; + + switch (options.direction) { + case 'top-left': + moveX = moveY = 0; + break; + case 'top-right': + moveX = dims.width; + moveY = 0; + break; + case 'bottom-left': + moveX = 0; + moveY = dims.height; + break; + case 'bottom-right': + moveX = dims.width; + moveY = dims.height; + break; + case 'center': + moveX = dims.width / 2; + moveY = dims.height / 2; + break; + } + + return new Effect.Parallel( + [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }), + new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}), + new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }) + ], Object.extend({ + beforeStartInternal: function(effect) { + effect.effects[0].element.makePositioned(); + effect.effects[0].element.makeClipping(); }, + afterFinishInternal: function(effect) { + effect.effects[0].element.hide(); + effect.effects[0].element.undoClipping(); + effect.effects[0].element.undoPositioned(); + effect.effects[0].element.setStyle(oldStyle); } + }, options) + ); +} + +Effect.Pulsate = function(element) { + element = $(element); + var options = arguments[1] || {}; + var oldOpacity = element.getInlineOpacity(); + var transition = options.transition || Effect.Transitions.sinoidal; + var reverser = function(pos){ return transition(1-Effect.Transitions.pulse(pos)) }; + reverser.bind(transition); + return new Effect.Opacity(element, + Object.extend(Object.extend({ duration: 3.0, from: 0, + afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); } + }, options), {transition: reverser})); +} + +Effect.Fold = function(element) { + element = $(element); + var oldStyle = { + top: element.style.top, + left: element.style.left, + width: element.style.width, + height: element.style.height }; + Element.makeClipping(element); + return new Effect.Scale(element, 5, Object.extend({ + scaleContent: false, + scaleX: false, + afterFinishInternal: function(effect) { + new Effect.Scale(element, 1, { + scaleContent: false, + scaleY: false, + afterFinishInternal: function(effect) { + effect.element.hide(); + effect.element.undoClipping(); + effect.element.setStyle(oldStyle); + } }); + }}, arguments[1] || {})); +}; + +['setOpacity','getOpacity','getInlineOpacity','forceRerendering','setContentZoom', + 'collectTextNodes','collectTextNodesIgnoreClass','childrenWithClassName'].each( + function(f) { Element.Methods[f] = Element[f]; } +); + +Element.Methods.visualEffect = function(element, effect, options) { + s = effect.gsub(/_/, '-').camelize(); + effect_class = s.charAt(0).toUpperCase() + s.substring(1); + new Effect[effect_class](element, options); + return $(element); +}; + +Element.addMethods();
\ No newline at end of file diff --git a/wp-inst/wp-includes/js/scriptaculous/prototype.js b/wp-inst/wp-includes/js/scriptaculous/prototype.js new file mode 100644 index 0000000..0caf9cd --- /dev/null +++ b/wp-inst/wp-includes/js/scriptaculous/prototype.js @@ -0,0 +1,2006 @@ +/* Prototype JavaScript framework, version 1.5.0_rc0 + * (c) 2005 Sam Stephenson <sam@conio.net> + * + * Prototype is freely distributable under the terms of an MIT-style license. + * For details, see the Prototype web site: http://prototype.conio.net/ + * +/*--------------------------------------------------------------------------*/ + +var Prototype = { + Version: '1.5.0_rc0', + ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)', + + emptyFunction: function() {}, + K: function(x) {return x} +} + +var Class = { + create: function() { + return function() { + this.initialize.apply(this, arguments); + } + } +} + +var Abstract = new Object(); + +Object.extend = function(destination, source) { + for (var property in source) { + destination[property] = source[property]; + } + return destination; +} + +Object.inspect = function(object) { + try { + if (object == undefined) return 'undefined'; + if (object == null) return 'null'; + return object.inspect ? object.inspect() : object.toString(); + } catch (e) { + if (e instanceof RangeError) return '...'; + throw e; + } +} + +Function.prototype.bind = function() { + var __method = this, args = $A(arguments), object = args.shift(); + return function() { + return __method.apply(object, args.concat($A(arguments))); + } +} + +Function.prototype.bindAsEventListener = function(object) { + var __method = this; + return function(event) { + return __method.call(object, event || window.event); + } +} + +Object.extend(Number.prototype, { + toColorPart: function() { + var digits = this.toString(16); + if (this < 16) return '0' + digits; + return digits; + }, + + succ: function() { + return this + 1; + }, + + times: function(iterator) { + $R(0, this, true).each(iterator); + return this; + } +}); + +var Try = { + these: function() { + var returnValue; + + for (var i = 0; i < arguments.length; i++) { + var lambda = arguments[i]; + try { + returnValue = lambda(); + break; + } catch (e) {} + } + + return returnValue; + } +} + +/*--------------------------------------------------------------------------*/ + +var PeriodicalExecuter = Class.create(); +PeriodicalExecuter.prototype = { + initialize: function(callback, frequency) { + this.callback = callback; + this.frequency = frequency; + this.currentlyExecuting = false; + + this.registerCallback(); + }, + + registerCallback: function() { + setInterval(this.onTimerEvent.bind(this), this.frequency * 1000); + }, + + onTimerEvent: function() { + if (!this.currentlyExecuting) { + try { + this.currentlyExecuting = true; + this.callback(); + } finally { + this.currentlyExecuting = false; + } + } + } +} +Object.extend(String.prototype, { + gsub: function(pattern, replacement) { + var result = '', source = this, match; + replacement = arguments.callee.prepareReplacement(replacement); + + while (source.length > 0) { + if (match = source.match(pattern)) { + result += source.slice(0, match.index); + result += (replacement(match) || '').toString(); + source = source.slice(match.index + match[0].length); + } else { + result += source, source = ''; + } + } + return result; + }, + + sub: function(pattern, replacement, count) { + replacement = this.gsub.prepareReplacement(replacement); + count = count === undefined ? 1 : count; + + return this.gsub(pattern, function(match) { + if (--count < 0) return match[0]; + return replacement(match); + }); + }, + + scan: function(pattern, iterator) { + this.gsub(pattern, iterator); + return this; + }, + + truncate: function(length, truncation) { + length = length || 30; + truncation = truncation === undefined ? '...' : truncation; + return this.length > length ? + this.slice(0, length - truncation.length) + truncation : this; + }, + + strip: function() { + return this.replace(/^\s+/, '').replace(/\s+$/, ''); + }, + + stripTags: function() { + return this.replace(/<\/?[^>]+>/gi, ''); + }, + + stripScripts: function() { + return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), ''); + }, + + extractScripts: function() { + var matchAll = new RegExp(Prototype.ScriptFragment, 'img'); + var matchOne = new RegExp(Prototype.ScriptFragment, 'im'); + return (this.match(matchAll) || []).map(function(scriptTag) { + return (scriptTag.match(matchOne) || ['', ''])[1]; + }); + }, + + evalScripts: function() { + return this.extractScripts().map(function(script) { return eval(script) }); + }, + + escapeHTML: function() { + var div = document.createElement('div'); + var text = document.createTextNode(this); + div.appendChild(text); + return div.innerHTML; + }, + + unescapeHTML: function() { + var div = document.createElement('div'); + div.innerHTML = this.stripTags(); + return div.childNodes[0] ? div.childNodes[0].nodeValue : ''; + }, + + toQueryParams: function() { + var pairs = this.match(/^\??(.*)$/)[1].split('&'); + return pairs.inject({}, function(params, pairString) { + var pair = pairString.split('='); + params[pair[0]] = pair[1]; + return params; + }); + }, + + toArray: function() { + return this.split(''); + }, + + camelize: function() { + var oStringList = this.split('-'); + if (oStringList.length == 1) return oStringList[0]; + + var camelizedString = this.indexOf('-') == 0 + ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1) + : oStringList[0]; + + for (var i = 1, len = oStringList.length; i < len; i++) { + var s = oStringList[i]; + camelizedString += s.charAt(0).toUpperCase() + s.substring(1); + } + + return camelizedString; + }, + + inspect: function() { + return "'" + this.replace(/\\/g, '\\\\').replace(/'/g, '\\\'') + "'"; + } +}); + +String.prototype.gsub.prepareReplacement = function(replacement) { + if (typeof replacement == 'function') return replacement; + var template = new Template(replacement); + return function(match) { return template.evaluate(match) }; +} + +String.prototype.parseQuery = String.prototype.toQueryParams; + +var Template = Class.create(); +Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/; +Template.prototype = { + initialize: function(template, pattern) { + this.template = template.toString(); + this.pattern = pattern || Template.Pattern; + }, + + evaluate: function(object) { + return this.template.gsub(this.pattern, function(match) { + var before = match[1]; + if (before == '\\') return match[2]; + return before + (object[match[3]] || '').toString(); + }); + } +} + +var $break = new Object(); +var $continue = new Object(); + +var Enumerable = { + each: function(iterator) { + var index = 0; + try { + this._each(function(value) { + try { + iterator(value, index++); + } catch (e) { + if (e != $continue) throw e; + } + }); + } catch (e) { + if (e != $break) throw e; + } + }, + + all: function(iterator) { + var result = true; + this.each(function(value, index) { + result = result && !!(iterator || Prototype.K)(value, index); + if (!result) throw $break; + }); + return result; + }, + + any: function(iterator) { + var result = true; + this.each(function(value, index) { + if (result = !!(iterator || Prototype.K)(value, index)) + throw $break; + }); + return result; + }, + + collect: function(iterator) { + var results = []; + this.each(function(value, index) { + results.push(iterator(value, index)); + }); + return results; + }, + + detect: function (iterator) { + var result; + this.each(function(value, index) { + if (iterator(value, index)) { + result = value; + throw $break; + } + }); + return result; + }, + + findAll: function(iterator) { + var results = []; + this.each(function(value, index) { + if (iterator(value, index)) + results.push(value); + }); + return results; + }, + + grep: function(pattern, iterator) { + var results = []; + this.each(function(value, index) { + var stringValue = value.toString(); + if (stringValue.match(pattern)) + results.push((iterator || Prototype.K)(value, index)); + }) + return results; + }, + + include: function(object) { + var found = false; + this.each(function(value) { + if (value == object) { + found = true; + throw $break; + } + }); + return found; + }, + + inject: function(memo, iterator) { + this.each(function(value, index) { + memo = iterator(memo, value, index); + }); + return memo; + }, + + invoke: function(method) { + var args = $A(arguments).slice(1); + return this.collect(function(value) { + return value[method].apply(value, args); + }); + }, + + max: function(iterator) { + var result; + this.each(function(value, index) { + value = (iterator || Prototype.K)(value, index); + if (result == undefined || value >= result) + result = value; + }); + return result; + }, + + min: function(iterator) { + var result; + this.each(function(value, index) { + value = (iterator || Prototype.K)(value, index); + if (result == undefined || value < result) + result = value; + }); + return result; + }, + + partition: function(iterator) { + var trues = [], falses = []; + this.each(function(value, index) { + ((iterator || Prototype.K)(value, index) ? + trues : falses).push(value); + }); + return [trues, falses]; + }, + + pluck: function(property) { + var results = []; + this.each(function(value, index) { + results.push(value[property]); + }); + return results; + }, + + reject: function(iterator) { + var results = []; + this.each(function(value, index) { + if (!iterator(value, index)) + results.push(value); + }); + return results; + }, + + sortBy: function(iterator) { + return this.collect(function(value, index) { + return {value: value, criteria: iterator(value, index)}; + }).sort(function(left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + }).pluck('value'); + }, + + toArray: function() { + return this.collect(Prototype.K); + }, + + zip: function() { + var iterator = Prototype.K, args = $A(arguments); + if (typeof args.last() == 'function') + iterator = args.pop(); + + var collections = [this].concat(args).map($A); + return this.map(function(value, index) { + return iterator(collections.pluck(index)); + }); + }, + + inspect: function() { + return '#<Enumerable:' + this.toArray().inspect() + '>'; + } +} + +Object.extend(Enumerable, { + map: Enumerable.collect, + find: Enumerable.detect, + select: Enumerable.findAll, + member: Enumerable.include, + entries: Enumerable.toArray +}); +var $A = Array.from = function(iterable) { + if (!iterable) return []; + if (iterable.toArray) { + return iterable.toArray(); + } else { + var results = []; + for (var i = 0; i < iterable.length; i++) + results.push(iterable[i]); + return results; + } +} + +Object.extend(Array.prototype, Enumerable); + +if (!Array.prototype._reverse) + Array.prototype._reverse = Array.prototype.reverse; + +Object.extend(Array.prototype, { + _each: function(iterator) { + for (var i = 0; i < this.length; i++) + iterator(this[i]); + }, + + clear: function() { + this.length = 0; + return this; + }, + + first: function() { + return this[0]; + }, + + last: function() { + return this[this.length - 1]; + }, + + compact: function() { + return this.select(function(value) { + return value != undefined || value != null; + }); + }, + + flatten: function() { + return this.inject([], function(array, value) { + return array.concat(value && value.constructor == Array ? + value.flatten() : [value]); + }); + }, + + without: function() { + var values = $A(arguments); + return this.select(function(value) { + return !values.include(value); + }); + }, + + indexOf: function(object) { + for (var i = 0; i < this.length; i++) + if (this[i] == object) return i; + return -1; + }, + + reverse: function(inline) { + return (inline !== false ? this : this.toArray())._reverse(); + }, + + inspect: function() { + return '[' + this.map(Object.inspect).join(', ') + ']'; + } +}); +var Hash = { + _each: function(iterator) { + for (var key in this) { + var value = this[key]; + if (typeof value == 'function') continue; + + var pair = [key, value]; + pair.key = key; + pair.value = value; + iterator(pair); + } + }, + + keys: function() { + return this.pluck('key'); + }, + + values: function() { + return this.pluck('value'); + }, + + merge: function(hash) { + return $H(hash).inject($H(this), function(mergedHash, pair) { + mergedHash[pair.key] = pair.value; + return mergedHash; + }); + }, + + toQueryString: function() { + return this.map(function(pair) { + return pair.map(encodeURIComponent).join('='); + }).join('&'); + }, + + inspect: function() { + return '#<Hash:{' + this.map(function(pair) { + return pair.map(Object.inspect).join(': '); + }).join(', ') + '}>'; + } +} + +function $H(object) { + var hash = Object.extend({}, object || {}); + Object.extend(hash, Enumerable); + Object.extend(hash, Hash); + return hash; +} +ObjectRange = Class.create(); +Object.extend(ObjectRange.prototype, Enumerable); +Object.extend(ObjectRange.prototype, { + initialize: function(start, end, exclusive) { + this.start = start; + this.end = end; + this.exclusive = exclusive; + }, + + _each: function(iterator) { + var value = this.start; + do { + iterator(value); + value = value.succ(); + } while (this.include(value)); + }, + + include: function(value) { + if (value < this.start) + return false; + if (this.exclusive) + return value < this.end; + return value <= this.end; + } +}); + +var $R = function(start, end, exclusive) { + return new ObjectRange(start, end, exclusive); +} + +var Ajax = { + getTransport: function() { + return Try.these( + function() {return new XMLHttpRequest()}, + function() {return new ActiveXObject('Msxml2.XMLHTTP')}, + function() {return new ActiveXObject('Microsoft.XMLHTTP')} + ) || false; + }, + + activeRequestCount: 0 +} + +Ajax.Responders = { + responders: [], + + _each: function(iterator) { + this.responders._each(iterator); + }, + + register: function(responderToAdd) { + if (!this.include(responderToAdd)) + this.responders.push(responderToAdd); + }, + + unregister: function(responderToRemove) { + this.responders = this.responders.without(responderToRemove); + }, + + dispatch: function(callback, request, transport, json) { + this.each(function(responder) { + if (responder[callback] && typeof responder[callback] == 'function') { + try { + responder[callback].apply(responder, [request, transport, json]); + } catch (e) {} + } + }); + } +}; + +Object.extend(Ajax.Responders, Enumerable); + +Ajax.Responders.register({ + onCreate: function() { + Ajax.activeRequestCount++; + }, + + onComplete: function() { + Ajax.activeRequestCount--; + } +}); + +Ajax.Base = function() {}; +Ajax.Base.prototype = { + setOptions: function(options) { + this.options = { + method: 'post', + asynchronous: true, + contentType: 'application/x-www-form-urlencoded', + parameters: '' + } + Object.extend(this.options, options || {}); + }, + + responseIsSuccess: function() { + return this.transport.status == undefined + || this.transport.status == 0 + || (this.transport.status >= 200 && this.transport.status < 300); + }, + + responseIsFailure: function() { + return !this.responseIsSuccess(); + } +} + +Ajax.Request = Class.create(); +Ajax.Request.Events = + ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete']; + +Ajax.Request.prototype = Object.extend(new Ajax.Base(), { + initialize: function(url, options) { + this.transport = Ajax.getTransport(); + this.setOptions(options); + this.request(url); + }, + + request: function(url) { + var parameters = this.options.parameters || ''; + if (parameters.length > 0) parameters += '&_='; + + try { + this.url = url; + if (this.options.method == 'get' && parameters.length > 0) + this.url += (this.url.match(/\?/) ? '&' : '?') + parameters; + + Ajax.Responders.dispatch('onCreate', this, this.transport); + + this.transport.open(this.options.method, this.url, + this.options.asynchronous); + + if (this.options.asynchronous) { + this.transport.onreadystatechange = this.onStateChange.bind(this); + setTimeout((function() {this.respondToReadyState(1)}).bind(this), 10); + } + + this.setRequestHeaders(); + + var body = this.options.postBody ? this.options.postBody : parameters; + this.transport.send(this.options.method == 'post' ? body : null); + + } catch (e) { + this.dispatchException(e); + } + }, + + setRequestHeaders: function() { + var requestHeaders = + ['X-Requested-With', 'XMLHttpRequest', + 'X-Prototype-Version', Prototype.Version, + 'Accept', 'text/javascript, text/html, application/xml, text/xml, */*']; + + if (this.options.method == 'post') { + requestHeaders.push('Content-type', this.options.contentType); + + /* Force "Connection: close" for Mozilla browsers to work around + * a bug where XMLHttpReqeuest sends an incorrect Content-length + * header. See Mozilla Bugzilla #246651. + */ + if (this.transport.overrideMimeType) + requestHeaders.push('Connection', 'close'); + } + + if (this.options.requestHeaders) + requestHeaders.push.apply(requestHeaders, this.options.requestHeaders); + + for (var i = 0; i < requestHeaders.length; i += 2) + this.transport.setRequestHeader(requestHeaders[i], requestHeaders[i+1]); + }, + + onStateChange: function() { + var readyState = this.transport.readyState; + if (readyState != 1) + this.respondToReadyState(this.transport.readyState); + }, + + header: function(name) { + try { + return this.transport.getResponseHeader(name); + } catch (e) {} + }, + + evalJSON: function() { + try { + return eval('(' + this.header('X-JSON') + ')'); + } catch (e) {} + }, + + evalResponse: function() { + try { + return eval(this.transport.responseText); + } catch (e) { + this.dispatchException(e); + } + }, + + respondToReadyState: function(readyState) { + var event = Ajax.Request.Events[readyState]; + var transport = this.transport, json = this.evalJSON(); + + if (event == 'Complete') { + try { + (this.options['on' + this.transport.status] + || this.options['on' + (this.responseIsSuccess() ? 'Success' : 'Failure')] + || Prototype.emptyFunction)(transport, json); + } catch (e) { + this.dispatchException(e); + } + + if ((this.header('Content-type') || '').match(/^text\/javascript/i)) + this.evalResponse(); + } + + try { + (this.options['on' + event] || Prototype.emptyFunction)(transport, json); + Ajax.Responders.dispatch('on' + event, this, transport, json); + } catch (e) { + this.dispatchException(e); + } + + /* Avoid memory leak in MSIE: clean up the oncomplete event handler */ + if (event == 'Complete') + this.transport.onreadystatechange = Prototype.emptyFunction; + }, + + dispatchException: function(exception) { + (this.options.onException || Prototype.emptyFunction)(this, exception); + Ajax.Responders.dispatch('onException', this, exception); + } +}); + +Ajax.Updater = Class.create(); + +Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), { + initialize: function(container, url, options) { + this.containers = { + success: container.success ? $(container.success) : $(container), + failure: container.failure ? $(container.failure) : + (container.success ? null : $(container)) + } + + this.transport = Ajax.getTransport(); + this.setOptions(options); + + var onComplete = this.options.onComplete || Prototype.emptyFunction; + this.options.onComplete = (function(transport, object) { + this.updateContent(); + onComplete(transport, object); + }).bind(this); + + this.request(url); + }, + + updateContent: function() { + var receiver = this.responseIsSuccess() ? + this.containers.success : this.containers.failure; + var response = this.transport.responseText; + + if (!this.options.evalScripts) + response = response.stripScripts(); + + if (receiver) { + if (this.options.insertion) { + new this.options.insertion(receiver, response); + } else { + Element.update(receiver, response); + } + } + + if (this.responseIsSuccess()) { + if (this.onComplete) + setTimeout(this.onComplete.bind(this), 10); + } + } +}); + +Ajax.PeriodicalUpdater = Class.create(); +Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), { + initialize: function(container, url, options) { + this.setOptions(options); + this.onComplete = this.options.onComplete; + + this.frequency = (this.options.frequency || 2); + this.decay = (this.options.decay || 1); + + this.updater = {}; + this.container = container; + this.url = url; + + this.start(); + }, + + start: function() { + this.options.onComplete = this.updateComplete.bind(this); + this.onTimerEvent(); + }, + + stop: function() { + this.updater.onComplete = undefined; + clearTimeout(this.timer); + (this.onComplete || Prototype.emptyFunction).apply(this, arguments); + }, + + updateComplete: function(request) { + if (this.options.decay) { + this.decay = (request.responseText == this.lastText ? + this.decay * this.options.decay : 1); + + this.lastText = request.responseText; + } + this.timer = setTimeout(this.onTimerEvent.bind(this), + this.decay * this.frequency * 1000); + }, + + onTimerEvent: function() { + this.updater = new Ajax.Updater(this.container, this.url, this.options); + } +}); +function $() { + var results = [], element; + for (var i = 0; i < arguments.length; i++) { + element = arguments[i]; + if (typeof element == 'string') + element = document.getElementById(element); + results.push(Element.extend(element)); + } + return results.length < 2 ? results[0] : results; +} + +document.getElementsByClassName = function(className, parentElement) { + var children = ($(parentElement) || document.body).getElementsByTagName('*'); + return $A(children).inject([], function(elements, child) { + if (child.className.match(new RegExp("(^|\\s)" + className + "(\\s|$)"))) + elements.push(Element.extend(child)); + return elements; + }); +} + +/*--------------------------------------------------------------------------*/ + +if (!window.Element) + var Element = new Object(); + +Element.extend = function(element) { + if (!element) return; + if (_nativeExtensions) return element; + + if (!element._extended && element.tagName && element != window) { + var methods = Element.Methods, cache = Element.extend.cache; + for (property in methods) { + var value = methods[property]; + if (typeof value == 'function') + element[property] = cache.findOrStore(value); + } + } + + element._extended = true; + return element; +} + +Element.extend.cache = { + findOrStore: function(value) { + return this[value] = this[value] || function() { + return value.apply(null, [this].concat($A(arguments))); + } + } +} + +Element.Methods = { + visible: function(element) { + return $(element).style.display != 'none'; + }, + + toggle: function() { + for (var i = 0; i < arguments.length; i++) { + var element = $(arguments[i]); + Element[Element.visible(element) ? 'hide' : 'show'](element); + } + }, + + hide: function() { + for (var i = 0; i < arguments.length; i++) { + var element = $(arguments[i]); + element.style.display = 'none'; + } + }, + + show: function() { + for (var i = 0; i < arguments.length; i++) { + var element = $(arguments[i]); + element.style.display = ''; + } + }, + + remove: function(element) { + element = $(element); + element.parentNode.removeChild(element); + }, + + update: function(element, html) { + $(element).innerHTML = html.stripScripts(); + setTimeout(function() {html.evalScripts()}, 10); + }, + + replace: function(element, html) { + element = $(element); + if (element.outerHTML) { + element.outerHTML = html.stripScripts(); + } else { + var range = element.ownerDocument.createRange(); + range.selectNodeContents(element); + element.parentNode.replaceChild( + range.createContextualFragment(html.stripScripts()), element); + } + setTimeout(function() {html.evalScripts()}, 10); + }, + + getHeight: function(element) { + element = $(element); + return element.offsetHeight; + }, + + classNames: function(element) { + return new Element.ClassNames(element); + }, + + hasClassName: function(element, className) { + if (!(element = $(element))) return; + return Element.classNames(element).include(className); + }, + + addClassName: function(element, className) { + if (!(element = $(element))) return; + return Element.classNames(element).add(className); + }, + + removeClassName: function(element, className) { + if (!(element = $(element))) return; + return Element.classNames(element).remove(className); + }, + + // removes whitespace-only text node children + cleanWhitespace: function(element) { + element = $(element); + for (var i = 0; i < element.childNodes.length; i++) { + var node = element.childNodes[i]; + if (node.nodeType == 3 && !/\S/.test(node.nodeValue)) + Element.remove(node); + } + }, + + empty: function(element) { + return $(element).innerHTML.match(/^\s*$/); + }, + + childOf: function(element, ancestor) { + element = $(element), ancestor = $(ancestor); + while (element = element.parentNode) + if (element == ancestor) return true; + return false; + }, + + scrollTo: function(element) { + element = $(element); + var x = element.x ? element.x : element.offsetLeft, + y = element.y ? element.y : element.offsetTop; + window.scrollTo(x, y); + }, + + getStyle: function(element, style) { + element = $(element); + var value = element.style[style.camelize()]; + if (!value) { + if (document.defaultView && document.defaultView.getComputedStyle) { + var css = document.defaultView.getComputedStyle(element, null); + value = css ? css.getPropertyValue(style) : null; + } else if (element.currentStyle) { + value = element.currentStyle[style.camelize()]; + } + } + + if (window.opera && ['left', 'top', 'right', 'bottom'].include(style)) + if (Element.getStyle(element, 'position') == 'static') value = 'auto'; + + return value == 'auto' ? null : value; + }, + + setStyle: function(element, style) { + element = $(element); + for (var name in style) + element.style[name.camelize()] = style[name]; + }, + + getDimensions: function(element) { + element = $(element); + if (Element.getStyle(element, 'display') != 'none') + return {width: element.offsetWidth, height: element.offsetHeight}; + + // All *Width and *Height properties give 0 on elements with display none, + // so enable the element temporarily + var els = element.style; + var originalVisibility = els.visibility; + var originalPosition = els.position; + els.visibility = 'hidden'; + els.position = 'absolute'; + els.display = ''; + var originalWidth = element.clientWidth; + var originalHeight = element.clientHeight; + els.display = 'none'; + els.position = originalPosition; + els.visibility = originalVisibility; + return {width: originalWidth, height: originalHeight}; + }, + + makePositioned: function(element) { + element = $(element); + var pos = Element.getStyle(element, 'position'); + if (pos == 'static' || !pos) { + element._madePositioned = true; + element.style.position = 'relative'; + // Opera returns the offset relative to the positioning context, when an + // element is position relative but top and left have not been defined + if (window.opera) { + element.style.top = 0; + element.style.left = 0; + } + } + }, + + undoPositioned: function(element) { + element = $(element); + if (element._madePositioned) { + element._madePositioned = undefined; + element.style.position = + element.style.top = + element.style.left = + element.style.bottom = + element.style.right = ''; + } + }, + + makeClipping: function(element) { + element = $(element); + if (element._overflow) return; + element._overflow = element.style.overflow; + if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden') + element.style.overflow = 'hidden'; + }, + + undoClipping: function(element) { + element = $(element); + if (element._overflow) return; + element.style.overflow = element._overflow; + element._overflow = undefined; + } +} + +Object.extend(Element, Element.Methods); + +var _nativeExtensions = false; + +if(!HTMLElement && /Konqueror|Safari|KHTML/.test(navigator.userAgent)) { + var HTMLElement = {} + HTMLElement.prototype = document.createElement('div').__proto__; +} + +Element.addMethods = function(methods) { + Object.extend(Element.Methods, methods || {}); + + if(typeof HTMLElement != 'undefined') { + var methods = Element.Methods, cache = Element.extend.cache; + for (property in methods) { + var value = methods[property]; + if (typeof value == 'function') + HTMLElement.prototype[property] = cache.findOrStore(value); + } + _nativeExtensions = true; + } +} + +Element.addMethods(); + +var Toggle = new Object(); +Toggle.display = Element.toggle; + +/*--------------------------------------------------------------------------*/ + +Abstract.Insertion = function(adjacency) { + this.adjacency = adjacency; +} + +Abstract.Insertion.prototype = { + initialize: function(element, content) { + this.element = $(element); + this.content = content.stripScripts(); + + if (this.adjacency && this.element.insertAdjacentHTML) { + try { + this.element.insertAdjacentHTML(this.adjacency, this.content); + } catch (e) { + var tagName = this.element.tagName.toLowerCase(); + if (tagName == 'tbody' || tagName == 'tr') { + this.insertContent(this.contentFromAnonymousTable()); + } else { + throw e; + } + } + } else { + this.range = this.element.ownerDocument.createRange(); + if (this.initializeRange) this.initializeRange(); + this.insertContent([this.range.createContextualFragment(this.content)]); + } + + setTimeout(function() {content.evalScripts()}, 10); + }, + + contentFromAnonymousTable: function() { + var div = document.createElement('div'); + div.innerHTML = '<table><tbody>' + this.content + '</tbody></table>'; + return $A(div.childNodes[0].childNodes[0].childNodes); + } +} + +var Insertion = new Object(); + +Insertion.Before = Class.create(); +Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), { + initializeRange: function() { + this.range.setStartBefore(this.element); + }, + + insertContent: function(fragments) { + fragments.each((function(fragment) { + this.element.parentNode.insertBefore(fragment, this.element); + }).bind(this)); + } +}); + +Insertion.Top = Class.create(); +Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), { + initializeRange: function() { + this.range.selectNodeContents(this.element); + this.range.collapse(true); + }, + + insertContent: function(fragments) { + fragments.reverse(false).each((function(fragment) { + this.element.insertBefore(fragment, this.element.firstChild); + }).bind(this)); + } +}); + +Insertion.Bottom = Class.create(); +Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), { + initializeRange: function() { + this.range.selectNodeContents(this.element); + this.range.collapse(this.element); + }, + + insertContent: function(fragments) { + fragments.each((function(fragment) { + this.element.appendChild(fragment); + }).bind(this)); + } +}); + +Insertion.After = Class.create(); +Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), { + initializeRange: function() { + this.range.setStartAfter(this.element); + }, + + insertContent: function(fragments) { + fragments.each((function(fragment) { + this.element.parentNode.insertBefore(fragment, + this.element.nextSibling); + }).bind(this)); + } +}); + +/*--------------------------------------------------------------------------*/ + +Element.ClassNames = Class.create(); +Element.ClassNames.prototype = { + initialize: function(element) { + this.element = $(element); + }, + + _each: function(iterator) { + this.element.className.split(/\s+/).select(function(name) { + return name.length > 0; + })._each(iterator); + }, + + set: function(className) { + this.element.className = className; + }, + + add: function(classNameToAdd) { + if (this.include(classNameToAdd)) return; + this.set(this.toArray().concat(classNameToAdd).join(' ')); + }, + + remove: function(classNameToRemove) { + if (!this.include(classNameToRemove)) return; + this.set(this.select(function(className) { + return className != classNameToRemove; + }).join(' ')); + }, + + toString: function() { + return this.toArray().join(' '); + } +} + +Object.extend(Element.ClassNames.prototype, Enumerable); +var Selector = Class.create(); +Selector.prototype = { + initialize: function(expression) { + this.params = {classNames: []}; + this.expression = expression.toString().strip(); + this.parseExpression(); + this.compileMatcher(); + }, + + parseExpression: function() { + function abort(message) { throw 'Parse error in selector: ' + message; } + + if (this.expression == '') abort('empty expression'); + + var params = this.params, expr = this.expression, match, modifier, clause, rest; + while (match = expr.match(/^(.*)\[([a-z0-9_:-]+?)(?:([~\|!]?=)(?:"([^"]*)"|([^\]\s]*)))?\]$/i)) { + params.attributes = params.attributes || []; + params.attributes.push({name: match[2], operator: match[3], value: match[4] || match[5] || ''}); + expr = match[1]; + } + + if (expr == '*') return this.params.wildcard = true; + + while (match = expr.match(/^([^a-z0-9_-])?([a-z0-9_-]+)(.*)/i)) { + modifier = match[1], clause = match[2], rest = match[3]; + switch (modifier) { + case '#': params.id = clause; break; + case '.': params.classNames.push(clause); break; + case '': + case undefined: params.tagName = clause.toUpperCase(); break; + default: abort(expr.inspect()); + } + expr = rest; + } + + if (expr.length > 0) abort(expr.inspect()); + }, + + buildMatchExpression: function() { + var params = this.params, conditions = [], clause; + + if (params.wildcard) + conditions.push('true'); + if (clause = params.id) + conditions.push('element.id == ' + clause.inspect()); + if (clause = params.tagName) + conditions.push('element.tagName.toUpperCase() == ' + clause.inspect()); + if ((clause = params.classNames).length > 0) + for (var i = 0; i < clause.length; i++) + conditions.push('Element.hasClassName(element, ' + clause[i].inspect() + ')'); + if (clause = params.attributes) { + clause.each(function(attribute) { + var value = 'element.getAttribute(' + attribute.name.inspect() + ')'; + var splitValueBy = function(delimiter) { + return value + ' && ' + value + '.split(' + delimiter.inspect() + ')'; + } + + switch (attribute.operator) { + case '=': conditions.push(value + ' == ' + attribute.value.inspect()); break; + case '~=': conditions.push(splitValueBy(' ') + '.include(' + attribute.value.inspect() + ')'); break; + case '|=': conditions.push( + splitValueBy('-') + '.first().toUpperCase() == ' + attribute.value.toUpperCase().inspect() + ); break; + case '!=': conditions.push(value + ' != ' + attribute.value.inspect()); break; + case '': + case undefined: conditions.push(value + ' != null'); break; + default: throw 'Unknown operator ' + attribute.operator + ' in selector'; + } + }); + } + + return conditions.join(' && '); + }, + + compileMatcher: function() { + this.match = new Function('element', 'if (!element.tagName) return false; \ + return ' + this.buildMatchExpression()); + }, + + findElements: function(scope) { + var element; + + if (element = $(this.params.id)) + if (this.match(element)) + if (!scope || Element.childOf(element, scope)) + return [element]; + + scope = (scope || document).getElementsByTagName(this.params.tagName || '*'); + + var results = []; + for (var i = 0; i < scope.length; i++) + if (this.match(element = scope[i])) + results.push(Element.extend(element)); + + return results; + }, + + toString: function() { + return this.expression; + } +} + +function $$() { + return $A(arguments).map(function(expression) { + return expression.strip().split(/\s+/).inject([null], function(results, expr) { + var selector = new Selector(expr); + return results.map(selector.findElements.bind(selector)).flatten(); + }); + }).flatten(); +} +var Field = { + clear: function() { + for (var i = 0; i < arguments.length; i++) + $(arguments[i]).value = ''; + }, + + focus: function(element) { + $(element).focus(); + }, + + present: function() { + for (var i = 0; i < arguments.length; i++) + if ($(arguments[i]).value == '') return false; + return true; + }, + + select: function(element) { + $(element).select(); + }, + + activate: function(element) { + element = $(element); + element.focus(); + if (element.select) + element.select(); + } +} + +/*--------------------------------------------------------------------------*/ + +var Form = { + serialize: function(form) { + var elements = Form.getElements($(form)); + var queryComponents = new Array(); + + for (var i = 0; i < elements.length; i++) { + var queryComponent = Form.Element.serialize(elements[i]); + if (queryComponent) + queryComponents.push(queryComponent); + } + + return queryComponents.join('&'); + }, + + getElements: function(form) { + form = $(form); + var elements = new Array(); + + for (var tagName in Form.Element.Serializers) { + var tagElements = form.getElementsByTagName(tagName); + for (var j = 0; j < tagElements.length; j++) + elements.push(tagElements[j]); + } + return elements; + }, + + getInputs: function(form, typeName, name) { + form = $(form); + var inputs = form.getElementsByTagName('input'); + + if (!typeName && !name) + return inputs; + + var matchingInputs = new Array(); + for (var i = 0; i < inputs.length; i++) { + var input = inputs[i]; + if ((typeName && input.type != typeName) || + (name && input.name != name)) + continue; + matchingInputs.push(input); + } + + return matchingInputs; + }, + + disable: function(form) { + var elements = Form.getElements(form); + for (var i = 0; i < elements.length; i++) { + var element = elements[i]; + element.blur(); + element.disabled = 'true'; + } + }, + + enable: function(form) { + var elements = Form.getElements(form); + for (var i = 0; i < elements.length; i++) { + var element = elements[i]; + element.disabled = ''; + } + }, + + findFirstElement: function(form) { + return Form.getElements(form).find(function(element) { + return element.type != 'hidden' && !element.disabled && + ['input', 'select', 'textarea'].include(element.tagName.toLowerCase()); + }); + }, + + focusFirstElement: function(form) { + Field.activate(Form.findFirstElement(form)); + }, + + reset: function(form) { + $(form).reset(); + } +} + +Form.Element = { + serialize: function(element) { + element = $(element); + var method = element.tagName.toLowerCase(); + var parameter = Form.Element.Serializers[method](element); + + if (parameter) { + var key = encodeURIComponent(parameter[0]); + if (key.length == 0) return; + + if (parameter[1].constructor != Array) + parameter[1] = [parameter[1]]; + + return parameter[1].map(function(value) { + return key + '=' + encodeURIComponent(value); + }).join('&'); + } + }, + + getValue: function(element) { + element = $(element); + var method = element.tagName.toLowerCase(); + var parameter = Form.Element.Serializers[method](element); + + if (parameter) + return parameter[1]; + } +} + +Form.Element.Serializers = { + input: function(element) { + switch (element.type.toLowerCase()) { + case 'submit': + case 'hidden': + case 'password': + case 'text': + return Form.Element.Serializers.textarea(element); + case 'checkbox': + case 'radio': + return Form.Element.Serializers.inputSelector(element); + } + return false; + }, + + inputSelector: function(element) { + if (element.checked) + return [element.name, element.value]; + }, + + textarea: function(element) { + return [element.name, element.value]; + }, + + select: function(element) { + return Form.Element.Serializers[element.type == 'select-one' ? + 'selectOne' : 'selectMany'](element); + }, + + selectOne: function(element) { + var value = '', opt, index = element.selectedIndex; + if (index >= 0) { + opt = element.options[index]; + value = opt.value || opt.text; + } + return [element.name, value]; + }, + + selectMany: function(element) { + var value = []; + for (var i = 0; i < element.length; i++) { + var opt = element.options[i]; + if (opt.selected) + value.push(opt.value || opt.text); + } + return [element.name, value]; + } +} + +/*--------------------------------------------------------------------------*/ + +var $F = Form.Element.getValue; + +/*--------------------------------------------------------------------------*/ + +Abstract.TimedObserver = function() {} +Abstract.TimedObserver.prototype = { + initialize: function(element, frequency, callback) { + this.frequency = frequency; + this.element = $(element); + this.callback = callback; + + this.lastValue = this.getValue(); + this.registerCallback(); + }, + + registerCallback: function() { + setInterval(this.onTimerEvent.bind(this), this.frequency * 1000); + }, + + onTimerEvent: function() { + var value = this.getValue(); + if (this.lastValue != value) { + this.callback(this.element, value); + this.lastValue = value; + } + } +} + +Form.Element.Observer = Class.create(); +Form.Element.Observer.prototype = Object.extend(new Abstract.TimedObserver(), { + getValue: function() { + return Form.Element.getValue(this.element); + } +}); + +Form.Observer = Class.create(); +Form.Observer.prototype = Object.extend(new Abstract.TimedObserver(), { + getValue: function() { + return Form.serialize(this.element); + } +}); + +/*--------------------------------------------------------------------------*/ + +Abstract.EventObserver = function() {} +Abstract.EventObserver.prototype = { + initialize: function(element, callback) { + this.element = $(element); + this.callback = callback; + + this.lastValue = this.getValue(); + if (this.element.tagName.toLowerCase() == 'form') + this.registerFormCallbacks(); + else + this.registerCallback(this.element); + }, + + onElementEvent: function() { + var value = this.getValue(); + if (this.lastValue != value) { + this.callback(this.element, value); + this.lastValue = value; + } + }, + + registerFormCallbacks: function() { + var elements = Form.getElements(this.element); + for (var i = 0; i < elements.length; i++) + this.registerCallback(elements[i]); + }, + + registerCallback: function(element) { + if (element.type) { + switch (element.type.toLowerCase()) { + case 'checkbox': + case 'radio': + Event.observe(element, 'click', this.onElementEvent.bind(this)); + break; + case 'password': + case 'text': + case 'textarea': + case 'select-one': + case 'select-multiple': + Event.observe(element, 'change', this.onElementEvent.bind(this)); + break; + } + } + } +} + +Form.Element.EventObserver = Class.create(); +Form.Element.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), { + getValue: function() { + return Form.Element.getValue(this.element); + } +}); + +Form.EventObserver = Class.create(); +Form.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), { + getValue: function() { + return Form.serialize(this.element); + } +}); +if (!window.Event) { + var Event = new Object(); +} + +Object.extend(Event, { + KEY_BACKSPACE: 8, + KEY_TAB: 9, + KEY_RETURN: 13, + KEY_ESC: 27, + KEY_LEFT: 37, + KEY_UP: 38, + KEY_RIGHT: 39, + KEY_DOWN: 40, + KEY_DELETE: 46, + + element: function(event) { + return event.target || event.srcElement; + }, + + isLeftClick: function(event) { + return (((event.which) && (event.which == 1)) || + ((event.button) && (event.button == 1))); + }, + + pointerX: function(event) { + return event.pageX || (event.clientX + + (document.documentElement.scrollLeft || document.body.scrollLeft)); + }, + + pointerY: function(event) { + return event.pageY || (event.clientY + + (document.documentElement.scrollTop || document.body.scrollTop)); + }, + + stop: function(event) { + if (event.preventDefault) { + event.preventDefault(); + event.stopPropagation(); + } else { + event.returnValue = false; + event.cancelBubble = true; + } + }, + + // find the first node with the given tagName, starting from the + // node the event was triggered on; traverses the DOM upwards + findElement: function(event, tagName) { + var element = Event.element(event); + while (element.parentNode && (!element.tagName || + (element.tagName.toUpperCase() != tagName.toUpperCase()))) + element = element.parentNode; + return element; + }, + + observers: false, + + _observeAndCache: function(element, name, observer, useCapture) { + if (!this.observers) this.observers = []; + if (element.addEventListener) { + this.observers.push([element, name, observer, useCapture]); + element.addEventListener(name, observer, useCapture); + } else if (element.attachEvent) { + this.observers.push([element, name, observer, useCapture]); + element.attachEvent('on' + name, observer); + } + }, + + unloadCache: function() { + if (!Event.observers) return; + for (var i = 0; i < Event.observers.length; i++) { + Event.stopObserving.apply(this, Event.observers[i]); + Event.observers[i][0] = null; + } + Event.observers = false; + }, + + observe: function(element, name, observer, useCapture) { + var element = $(element); + useCapture = useCapture || false; + + if (name == 'keypress' && + (navigator.appVersion.match(/Konqueror|Safari|KHTML/) + || element.attachEvent)) + name = 'keydown'; + + this._observeAndCache(element, name, observer, useCapture); + }, + + stopObserving: function(element, name, observer, useCapture) { + var element = $(element); + useCapture = useCapture || false; + + if (name == 'keypress' && + (navigator.appVersion.match(/Konqueror|Safari|KHTML/) + || element.detachEvent)) + name = 'keydown'; + + if (element.removeEventListener) { + element.removeEventListener(name, observer, useCapture); + } else if (element.detachEvent) { + element.detachEvent('on' + name, observer); + } + } +}); + +/* prevent memory leaks in IE */ +if (navigator.appVersion.match(/\bMSIE\b/)) + Event.observe(window, 'unload', Event.unloadCache, false); +var Position = { + // set to true if needed, warning: firefox performance problems + // NOT neeeded for page scrolling, only if draggable contained in + // scrollable elements + includeScrollOffsets: false, + + // must be called before calling withinIncludingScrolloffset, every time the + // page is scrolled + prepare: function() { + this.deltaX = window.pageXOffset + || document.documentElement.scrollLeft + || document.body.scrollLeft + || 0; + this.deltaY = window.pageYOffset + || document.documentElement.scrollTop + || document.body.scrollTop + || 0; + }, + + realOffset: function(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.scrollTop || 0; + valueL += element.scrollLeft || 0; + element = element.parentNode; + } while (element); + return [valueL, valueT]; + }, + + cumulativeOffset: function(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + element = element.offsetParent; + } while (element); + return [valueL, valueT]; + }, + + positionedOffset: function(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + element = element.offsetParent; + if (element) { + p = Element.getStyle(element, 'position'); + if (p == 'relative' || p == 'absolute') break; + } + } while (element); + return [valueL, valueT]; + }, + + offsetParent: function(element) { + if (element.offsetParent) return element.offsetParent; + if (element == document.body) return element; + + while ((element = element.parentNode) && element != document.body) + if (Element.getStyle(element, 'position') != 'static') + return element; + + return document.body; + }, + + // caches x/y coordinate pair to use with overlap + within: function(element, x, y) { + if (this.includeScrollOffsets) + return this.withinIncludingScrolloffsets(element, x, y); + this.xcomp = x; + this.ycomp = y; + this.offset = this.cumulativeOffset(element); + + return (y >= this.offset[1] && + y < this.offset[1] + element.offsetHeight && + x >= this.offset[0] && + x < this.offset[0] + element.offsetWidth); + }, + + withinIncludingScrolloffsets: function(element, x, y) { + var offsetcache = this.realOffset(element); + + this.xcomp = x + offsetcache[0] - this.deltaX; + this.ycomp = y + offsetcache[1] - this.deltaY; + this.offset = this.cumulativeOffset(element); + + return (this.ycomp >= this.offset[1] && + this.ycomp < this.offset[1] + element.offsetHeight && + this.xcomp >= this.offset[0] && + this.xcomp < this.offset[0] + element.offsetWidth); + }, + + // within must be called directly before + overlap: function(mode, element) { + if (!mode) return 0; + if (mode == 'vertical') + return ((this.offset[1] + element.offsetHeight) - this.ycomp) / + element.offsetHeight; + if (mode == 'horizontal') + return ((this.offset[0] + element.offsetWidth) - this.xcomp) / + element.offsetWidth; + }, + + clone: function(source, target) { + source = $(source); + target = $(target); + target.style.position = 'absolute'; + var offsets = this.cumulativeOffset(source); + target.style.top = offsets[1] + 'px'; + target.style.left = offsets[0] + 'px'; + target.style.width = source.offsetWidth + 'px'; + target.style.height = source.offsetHeight + 'px'; + }, + + page: function(forElement) { + var valueT = 0, valueL = 0; + + var element = forElement; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + + // Safari fix + if (element.offsetParent==document.body) + if (Element.getStyle(element,'position')=='absolute') break; + + } while (element = element.offsetParent); + + element = forElement; + do { + valueT -= element.scrollTop || 0; + valueL -= element.scrollLeft || 0; + } while (element = element.parentNode); + + return [valueL, valueT]; + }, + + clone: function(source, target) { + var options = Object.extend({ + setLeft: true, + setTop: true, + setWidth: true, + setHeight: true, + offsetTop: 0, + offsetLeft: 0 + }, arguments[2] || {}) + + // find page position of source + source = $(source); + var p = Position.page(source); + + // find coordinate system to use + target = $(target); + var delta = [0, 0]; + var parent = null; + // delta [0,0] will do fine with position: fixed elements, + // position:absolute needs offsetParent deltas + if (Element.getStyle(target,'position') == 'absolute') { + parent = Position.offsetParent(target); + delta = Position.page(parent); + } + + // correct by body offsets (fixes Safari) + if (parent == document.body) { + delta[0] -= document.body.offsetLeft; + delta[1] -= document.body.offsetTop; + } + + // set position + if(options.setLeft) target.style.left = (p[0] - delta[0] + options.offsetLeft) + 'px'; + if(options.setTop) target.style.top = (p[1] - delta[1] + options.offsetTop) + 'px'; + if(options.setWidth) target.style.width = source.offsetWidth + 'px'; + if(options.setHeight) target.style.height = source.offsetHeight + 'px'; + }, + + absolutize: function(element) { + element = $(element); + if (element.style.position == 'absolute') return; + Position.prepare(); + + var offsets = Position.positionedOffset(element); + var top = offsets[1]; + var left = offsets[0]; + var width = element.clientWidth; + var height = element.clientHeight; + + element._originalLeft = left - parseFloat(element.style.left || 0); + element._originalTop = top - parseFloat(element.style.top || 0); + element._originalWidth = element.style.width; + element._originalHeight = element.style.height; + + element.style.position = 'absolute'; + element.style.top = top + 'px';; + element.style.left = left + 'px';; + element.style.width = width + 'px';; + element.style.height = height + 'px';; + }, + + relativize: function(element) { + element = $(element); + if (element.style.position == 'relative') return; + Position.prepare(); + + element.style.position = 'relative'; + var top = parseFloat(element.style.top || 0) - (element._originalTop || 0); + var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0); + + element.style.top = top + 'px'; + element.style.left = left + 'px'; + element.style.height = element._originalHeight; + element.style.width = element._originalWidth; + } +} + +// Safari returns margins on body which is incorrect if the child is absolutely +// positioned. For performance reasons, redefine Position.cumulativeOffset for +// KHTML/WebKit only. +if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) { + Position.cumulativeOffset = function(element) { + var valueT = 0, valueL = 0; + do { + valueT += element.offsetTop || 0; + valueL += element.offsetLeft || 0; + if (element.offsetParent == document.body) + if (Element.getStyle(element, 'position') == 'absolute') break; + + element = element.offsetParent; + } while (element); + + return [valueL, valueT]; + } +}
\ No newline at end of file diff --git a/wp-inst/wp-includes/js/scriptaculous/scriptaculous.js b/wp-inst/wp-includes/js/scriptaculous/scriptaculous.js new file mode 100644 index 0000000..f61fc57 --- /dev/null +++ b/wp-inst/wp-includes/js/scriptaculous/scriptaculous.js @@ -0,0 +1,47 @@ +// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +var Scriptaculous = { + Version: '1.6.1', + require: function(libraryName) { + // inserting via DOM fails in Safari 2.0, so brute force approach + document.write('<script type="text/javascript" src="'+libraryName+'"></script>'); + }, + load: function() { + if((typeof Prototype=='undefined') || + (typeof Element == 'undefined') || + (typeof Element.Methods=='undefined') || + parseFloat(Prototype.Version.split(".")[0] + "." + + Prototype.Version.split(".")[1]) < 1.5) + throw("script.aculo.us requires the Prototype JavaScript framework >= 1.5.0"); + + $A(document.getElementsByTagName("script")).findAll( function(s) { + return (s.src && s.src.match(/scriptaculous\.js(\?.*)?$/)) + }).each( function(s) { + var path = s.src.replace(/scriptaculous\.js(\?.*)?$/,''); + var includes = s.src.match(/\?.*load=([a-z,]*)/); + (includes ? includes[1] : 'builder,effects,dragdrop,controls,slider').split(',').each( + function(include) { Scriptaculous.require(path+include+'.js') }); + }); + } +} + +Scriptaculous.load();
\ No newline at end of file diff --git a/wp-inst/wp-includes/js/scriptaculous/slider.js b/wp-inst/wp-includes/js/scriptaculous/slider.js new file mode 100644 index 0000000..c0f1fc0 --- /dev/null +++ b/wp-inst/wp-includes/js/scriptaculous/slider.js @@ -0,0 +1,283 @@ +// Copyright (c) 2005 Marty Haught, Thomas Fuchs +// +// See http://script.aculo.us for more info +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +if(!Control) var Control = {}; +Control.Slider = Class.create(); + +// options: +// axis: 'vertical', or 'horizontal' (default) +// +// callbacks: +// onChange(value) +// onSlide(value) +Control.Slider.prototype = { + initialize: function(handle, track, options) { + var slider = this; + + if(handle instanceof Array) { + this.handles = handle.collect( function(e) { return $(e) }); + } else { + this.handles = [$(handle)]; + } + + this.track = $(track); + this.options = options || {}; + + this.axis = this.options.axis || 'horizontal'; + this.increment = this.options.increment || 1; + this.step = parseInt(this.options.step || '1'); + this.range = this.options.range || $R(0,1); + + this.value = 0; // assure backwards compat + this.values = this.handles.map( function() { return 0 }); + this.spans = this.options.spans ? this.options.spans.map(function(s){ return $(s) }) : false; + this.options.startSpan = $(this.options.startSpan || null); + this.options.endSpan = $(this.options.endSpan || null); + + this.restricted = this.options.restricted || false; + + this.maximum = this.options.maximum || this.range.end; + this.minimum = this.options.minimum || this.range.start; + + // Will be used to align the handle onto the track, if necessary + this.alignX = parseInt(this.options.alignX || '0'); + this.alignY = parseInt(this.options.alignY || '0'); + + this.trackLength = this.maximumOffset() - this.minimumOffset(); + this.handleLength = this.isVertical() ? this.handles[0].offsetHeight : this.handles[0].offsetWidth; + + this.active = false; + this.dragging = false; + this.disabled = false; + + if(this.options.disabled) this.setDisabled(); + + // Allowed values array + this.allowedValues = this.options.values ? this.options.values.sortBy(Prototype.K) : false; + if(this.allowedValues) { + this.minimum = this.allowedValues.min(); + this.maximum = this.allowedValues.max(); + } + + this.eventMouseDown = this.startDrag.bindAsEventListener(this); + this.eventMouseUp = this.endDrag.bindAsEventListener(this); + this.eventMouseMove = this.update.bindAsEventListener(this); + + // Initialize handles in reverse (make sure first handle is active) + this.handles.each( function(h,i) { + i = slider.handles.length-1-i; + slider.setValue(parseFloat( + (slider.options.sliderValue instanceof Array ? + slider.options.sliderValue[i] : slider.options.sliderValue) || + slider.range.start), i); + Element.makePositioned(h); // fix IE + Event.observe(h, "mousedown", slider.eventMouseDown); + }); + + Event.observe(this.track, "mousedown", this.eventMouseDown); + Event.observe(document, "mouseup", this.eventMouseUp); + Event.observe(document, "mousemove", this.eventMouseMove); + + this.initialized = true; + }, + dispose: function() { + var slider = this; + Event.stopObserving(this.track, "mousedown", this.eventMouseDown); + Event.stopObserving(document, "mouseup", this.eventMouseUp); + Event.stopObserving(document, "mousemove", this.eventMouseMove); + this.handles.each( function(h) { + Event.stopObserving(h, "mousedown", slider.eventMouseDown); + }); + }, + setDisabled: function(){ + this.disabled = true; + }, + setEnabled: function(){ + this.disabled = false; + }, + getNearestValue: function(value){ + if(this.allowedValues){ + if(value >= this.allowedValues.max()) return(this.allowedValues.max()); + if(value <= this.allowedValues.min()) return(this.allowedValues.min()); + + var offset = Math.abs(this.allowedValues[0] - value); + var newValue = this.allowedValues[0]; + this.allowedValues.each( function(v) { + var currentOffset = Math.abs(v - value); + if(currentOffset <= offset){ + newValue = v; + offset = currentOffset; + } + }); + return newValue; + } + if(value > this.range.end) return this.range.end; + if(value < this.range.start) return this.range.start; + return value; + }, + setValue: function(sliderValue, handleIdx){ + if(!this.active) { + this.activeHandle = this.handles[handleIdx]; + this.activeHandleIdx = handleIdx; + this.updateStyles(); + } + handleIdx = handleIdx || this.activeHandleIdx || 0; + if(this.initialized && this.restricted) { + if((handleIdx>0) && (sliderValue<this.values[handleIdx-1])) + sliderValue = this.values[handleIdx-1]; + if((handleIdx < (this.handles.length-1)) && (sliderValue>this.values[handleIdx+1])) + sliderValue = this.values[handleIdx+1]; + } + sliderValue = this.getNearestValue(sliderValue); + this.values[handleIdx] = sliderValue; + this.value = this.values[0]; // assure backwards compat + + this.handles[handleIdx].style[this.isVertical() ? 'top' : 'left'] = + this.translateToPx(sliderValue); + + this.drawSpans(); + if(!this.dragging || !this.event) this.updateFinished(); + }, + setValueBy: function(delta, handleIdx) { + this.setValue(this.values[handleIdx || this.activeHandleIdx || 0] + delta, + handleIdx || this.activeHandleIdx || 0); + }, + translateToPx: function(value) { + return Math.round( + ((this.trackLength-this.handleLength)/(this.range.end-this.range.start)) * + (value - this.range.start)) + "px"; + }, + translateToValue: function(offset) { + return ((offset/(this.trackLength-this.handleLength) * + (this.range.end-this.range.start)) + this.range.start); + }, + getRange: function(range) { + var v = this.values.sortBy(Prototype.K); + range = range || 0; + return $R(v[range],v[range+1]); + }, + minimumOffset: function(){ + return(this.isVertical() ? this.alignY : this.alignX); + }, + maximumOffset: function(){ + return(this.isVertical() ? + this.track.offsetHeight - this.alignY : this.track.offsetWidth - this.alignX); + }, + isVertical: function(){ + return (this.axis == 'vertical'); + }, + drawSpans: function() { + var slider = this; + if(this.spans) + $R(0, this.spans.length-1).each(function(r) { slider.setSpan(slider.spans[r], slider.getRange(r)) }); + if(this.options.startSpan) + this.setSpan(this.options.startSpan, + $R(0, this.values.length>1 ? this.getRange(0).min() : this.value )); + if(this.options.endSpan) + this.setSpan(this.options.endSpan, + $R(this.values.length>1 ? this.getRange(this.spans.length-1).max() : this.value, this.maximum)); + }, + setSpan: function(span, range) { + if(this.isVertical()) { + span.style.top = this.translateToPx(range.start); + span.style.height = this.translateToPx(range.end - range.start + this.range.start); + } else { + span.style.left = this.translateToPx(range.start); + span.style.width = this.translateToPx(range.end - range.start + this.range.start); + } + }, + updateStyles: function() { + this.handles.each( function(h){ Element.removeClassName(h, 'selected') }); + Element.addClassName(this.activeHandle, 'selected'); + }, + startDrag: function(event) { + if(Event.isLeftClick(event)) { + if(!this.disabled){ + this.active = true; + + var handle = Event.element(event); + var pointer = [Event.pointerX(event), Event.pointerY(event)]; + if(handle==this.track) { + var offsets = Position.cumulativeOffset(this.track); + this.event = event; + this.setValue(this.translateToValue( + (this.isVertical() ? pointer[1]-offsets[1] : pointer[0]-offsets[0])-(this.handleLength/2) + )); + var offsets = Position.cumulativeOffset(this.activeHandle); + this.offsetX = (pointer[0] - offsets[0]); + this.offsetY = (pointer[1] - offsets[1]); + } else { + // find the handle (prevents issues with Safari) + while((this.handles.indexOf(handle) == -1) && handle.parentNode) + handle = handle.parentNode; + + this.activeHandle = handle; + this.activeHandleIdx = this.handles.indexOf(this.activeHandle); + this.updateStyles(); + + var offsets = Position.cumulativeOffset(this.activeHandle); + this.offsetX = (pointer[0] - offsets[0]); + this.offsetY = (pointer[1] - offsets[1]); + } + } + Event.stop(event); + } + }, + update: function(event) { + if(this.active) { + if(!this.dragging) this.dragging = true; + this.draw(event); + // fix AppleWebKit rendering + if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0); + Event.stop(event); + } + }, + draw: function(event) { + var pointer = [Event.pointerX(event), Event.pointerY(event)]; + var offsets = Position.cumulativeOffset(this.track); + pointer[0] -= this.offsetX + offsets[0]; + pointer[1] -= this.offsetY + offsets[1]; + this.event = event; + this.setValue(this.translateToValue( this.isVertical() ? pointer[1] : pointer[0] )); + if(this.initialized && this.options.onSlide) + this.options.onSlide(this.values.length>1 ? this.values : this.value, this); + }, + endDrag: function(event) { + if(this.active && this.dragging) { + this.finishDrag(event, true); + Event.stop(event); + } + this.active = false; + this.dragging = false; + }, + finishDrag: function(event, success) { + this.active = false; + this.dragging = false; + this.updateFinished(); + }, + updateFinished: function() { + if(this.initialized && this.options.onChange) + this.options.onChange(this.values.length>1 ? this.values : this.value, this); + this.event = null; + } +}
\ No newline at end of file diff --git a/wp-inst/wp-includes/js/scriptaculous/unittest.js b/wp-inst/wp-includes/js/scriptaculous/unittest.js new file mode 100644 index 0000000..d2c2d81 --- /dev/null +++ b/wp-inst/wp-includes/js/scriptaculous/unittest.js @@ -0,0 +1,383 @@ +// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us) +// (c) 2005 Jon Tirsen (http://www.tirsen.com) +// (c) 2005 Michael Schuerig (http://www.schuerig.de/michael/) +// +// Permission is hereby granted, free of charge, to any person obtaining +// a copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to +// permit persons to whom the Software is furnished to do so, subject to +// the following conditions: +// +// The above copyright notice and this permission notice shall be +// included in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + + +// experimental, Firefox-only +Event.simulateMouse = function(element, eventName) { + var options = Object.extend({ + pointerX: 0, + pointerY: 0, + buttons: 0 + }, arguments[2] || {}); + var oEvent = document.createEvent("MouseEvents"); + oEvent.initMouseEvent(eventName, true, true, document.defaultView, + options.buttons, options.pointerX, options.pointerY, options.pointerX, options.pointerY, + false, false, false, false, 0, $(element)); + + if(this.mark) Element.remove(this.mark); + this.mark = document.createElement('div'); + this.mark.appendChild(document.createTextNode(" ")); + document.body.appendChild(this.mark); + this.mark.style.position = 'absolute'; + this.mark.style.top = options.pointerY + "px"; + this.mark.style.left = options.pointerX + "px"; + this.mark.style.width = "5px"; + this.mark.style.height = "5px;"; + this.mark.style.borderTop = "1px solid red;" + this.mark.style.borderLeft = "1px solid red;" + + if(this.step) + alert('['+new Date().getTime().toString()+'] '+eventName+'/'+Test.Unit.inspect(options)); + + $(element).dispatchEvent(oEvent); +}; + +// Note: Due to a fix in Firefox 1.0.5/6 that probably fixed "too much", this doesn't work in 1.0.6 or DP2. +// You need to downgrade to 1.0.4 for now to get this working +// See https://bugzilla.mozilla.org/show_bug.cgi?id=289940 for the fix that fixed too much +Event.simulateKey = function(element, eventName) { + var options = Object.extend({ + ctrlKey: false, + altKey: false, + shiftKey: false, + metaKey: false, + keyCode: 0, + charCode: 0 + }, arguments[2] || {}); + + var oEvent = document.createEvent("KeyEvents"); + oEvent.initKeyEvent(eventName, true, true, window, + options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, + options.keyCode, options.charCode ); + $(element).dispatchEvent(oEvent); +}; + +Event.simulateKeys = function(element, command) { + for(var i=0; i<command.length; i++) { + Event.simulateKey(element,'keypress',{charCode:command.charCodeAt(i)}); + } +}; + +var Test = {} +Test.Unit = {}; + +// security exception workaround +Test.Unit.inspect = Object.inspect; + +Test.Unit.Logger = Class.create(); +Test.Unit.Logger.prototype = { + initialize: function(log) { + this.log = $(log); + if (this.log) { + this._createLogTable(); + } + }, + start: function(testName) { + if (!this.log) return; + this.testName = testName; + this.lastLogLine = document.createElement('tr'); + this.statusCell = document.createElement('td'); + this.nameCell = document.createElement('td'); + this.nameCell.appendChild(document.createTextNode(testName)); + this.messageCell = document.createElement('td'); + this.lastLogLine.appendChild(this.statusCell); + this.lastLogLine.appendChild(this.nameCell); + this.lastLogLine.appendChild(this.messageCell); + this.loglines.appendChild(this.lastLogLine); + }, + finish: function(status, summary) { + if (!this.log) return; + this.lastLogLine.className = status; + this.statusCell.innerHTML = status; + this.messageCell.innerHTML = this._toHTML(summary); + }, + message: function(message) { + if (!this.log) return; + this.messageCell.innerHTML = this._toHTML(message); + }, + summary: function(summary) { + if (!this.log) return; + this.logsummary.innerHTML = this._toHTML(summary); + }, + _createLogTable: function() { + this.log.innerHTML = + '<div id="logsummary"></div>' + + '<table id="logtable">' + + '<thead><tr><th>Status</th><th>Test</th><th>Message</th></tr></thead>' + + '<tbody id="loglines"></tbody>' + + '</table>'; + this.logsummary = $('logsummary') + this.loglines = $('loglines'); + }, + _toHTML: function(txt) { + return txt.escapeHTML().replace(/\n/g,"<br/>"); + } +} + +Test.Unit.Runner = Class.create(); +Test.Unit.Runner.prototype = { + initialize: function(testcases) { + this.options = Object.extend({ + testLog: 'testlog' + }, arguments[1] || {}); + this.options.resultsURL = this.parseResultsURLQueryParameter(); + if (this.options.testLog) { + this.options.testLog = $(this.options.testLog) || null; + } + if(this.options.tests) { + this.tests = []; + for(var i = 0; i < this.options.tests.length; i++) { + if(/^test/.test(this.options.tests[i])) { + this.tests.push(new Test.Unit.Testcase(this.options.tests[i], testcases[this.options.tests[i]], testcases["setup"], testcases["teardown"])); + } + } + } else { + if (this.options.test) { + this.tests = [new Test.Unit.Testcase(this.options.test, testcases[this.options.test], testcases["setup"], testcases["teardown"])]; + } else { + this.tests = []; + for(var testcase in testcases) { + if(/^test/.test(testcase)) { + this.tests.push(new Test.Unit.Testcase(testcase, testcases[testcase], testcases["setup"], testcases["teardown"])); + } + } + } + } + this.currentTest = 0; + this.logger = new Test.Unit.Logger(this.options.testLog); + setTimeout(this.runTests.bind(this), 1000); + }, + parseResultsURLQueryParameter: function() { + return window.location.search.parseQuery()["resultsURL"]; + }, + // Returns: + // "ERROR" if there was an error, + // "FAILURE" if there was a failure, or + // "SUCCESS" if there was neither + getResult: function() { + var hasFailure = false; + for(var i=0;i<this.tests.length;i++) { + if (this.tests[i].errors > 0) { + return "ERROR"; + } + if (this.tests[i].failures > 0) { + hasFailure = true; + } + } + if (hasFailure) { + return "FAILURE"; + } else { + return "SUCCESS"; + } + }, + postResults: function() { + if (this.options.resultsURL) { + new Ajax.Request(this.options.resultsURL, + { method: 'get', parameters: 'result=' + this.getResult(), asynchronous: false }); + } + }, + runTests: function() { + var test = this.tests[this.currentTest]; + if (!test) { + // finished! + this.postResults(); + this.logger.summary(this.summary()); + return; + } + if(!test.isWaiting) { + this.logger.start(test.name); + } + test.run(); + if(test.isWaiting) { + this.logger.message("Waiting for " + test.timeToWait + "ms"); + setTimeout(this.runTests.bind(this), test.timeToWait || 1000); + } else { + this.logger.finish(test.status(), test.summary()); + this.currentTest++; + // tail recursive, hopefully the browser will skip the stackframe + this.runTests(); + } + }, + summary: function() { + var assertions = 0; + var failures = 0; + var errors = 0; + var messages = []; + for(var i=0;i<this.tests.length;i++) { + assertions += this.tests[i].assertions; + failures += this.tests[i].failures; + errors += this.tests[i].errors; + } + return ( + this.tests.length + " tests, " + + assertions + " assertions, " + + failures + " failures, " + + errors + " errors"); + } +} + +Test.Unit.Assertions = Class.create(); +Test.Unit.Assertions.prototype = { + initialize: function() { + this.assertions = 0; + this.failures = 0; + this.errors = 0; + this.messages = []; + }, + summary: function() { + return ( + this.assertions + " assertions, " + + this.failures + " failures, " + + this.errors + " errors" + "\n" + + this.messages.join("\n")); + }, + pass: function() { + this.assertions++; + }, + fail: function(message) { + this.failures++; + this.messages.push("Failure: " + message); + }, + info: function(message) { + this.messages.push("Info: " + message); + }, + error: function(error) { + this.errors++; + this.messages.push(error.name + ": "+ error.message + "(" + Test.Unit.inspect(error) +")"); + }, + status: function() { + if (this.failures > 0) return 'failed'; + if (this.errors > 0) return 'error'; + return 'passed'; + }, + assert: function(expression) { + var message = arguments[1] || 'assert: got "' + Test.Unit.inspect(expression) + '"'; + try { expression ? this.pass() : + this.fail(message); } + catch(e) { this.error(e); } + }, + assertEqual: function(expected, actual) { + var message = arguments[2] || "assertEqual"; + try { (expected == actual) ? this.pass() : + this.fail(message + ': expected "' + Test.Unit.inspect(expected) + + '", actual "' + Test.Unit.inspect(actual) + '"'); } + catch(e) { this.error(e); } + }, + assertEnumEqual: function(expected, actual) { + var message = arguments[2] || "assertEnumEqual"; + try { $A(expected).length == $A(actual).length && + expected.zip(actual).all(function(pair) { return pair[0] == pair[1] }) ? + this.pass() : this.fail(message + ': expected ' + Test.Unit.inspect(expected) + + ', actual ' + Test.Unit.inspect(actual)); } + catch(e) { this.error(e); } + }, + assertNotEqual: function(expected, actual) { + var message = arguments[2] || "assertNotEqual"; + try { (expected != actual) ? this.pass() : + this.fail(message + ': got "' + Test.Unit.inspect(actual) + '"'); } + catch(e) { this.error(e); } + }, + assertNull: function(obj) { + var message = arguments[1] || 'assertNull' + try { (obj==null) ? this.pass() : + this.fail(message + ': got "' + Test.Unit.inspect(obj) + '"'); } + catch(e) { this.error(e); } + }, + assertHidden: function(element) { + var message = arguments[1] || 'assertHidden'; + this.assertEqual("none", element.style.display, message); + }, + assertNotNull: function(object) { + var message = arguments[1] || 'assertNotNull'; + this.assert(object != null, message); + }, + assertInstanceOf: function(expected, actual) { + var message = arguments[2] || 'assertInstanceOf'; + try { + (actual instanceof expected) ? this.pass() : + this.fail(message + ": object was not an instance of the expected type"); } + catch(e) { this.error(e); } + }, + assertNotInstanceOf: function(expected, actual) { + var message = arguments[2] || 'assertNotInstanceOf'; + try { + !(actual instanceof expected) ? this.pass() : + this.fail(message + ": object was an instance of the not expected type"); } + catch(e) { this.error(e); } + }, + _isVisible: function(element) { + element = $(element); + if(!element.parentNode) return true; + this.assertNotNull(element); + if(element.style && Element.getStyle(element, 'display') == 'none') + return false; + + return this._isVisible(element.parentNode); + }, + assertNotVisible: function(element) { + this.assert(!this._isVisible(element), Test.Unit.inspect(element) + " was not hidden and didn't have a hidden parent either. " + ("" || arguments[1])); + }, + assertVisible: function(element) { + this.assert(this._isVisible(element), Test.Unit.inspect(element) + " was not visible. " + ("" || arguments[1])); + }, + benchmark: function(operation, iterations) { + var startAt = new Date(); + (iterations || 1).times(operation); + var timeTaken = ((new Date())-startAt); + this.info((arguments[2] || 'Operation') + ' finished ' + + iterations + ' iterations in ' + (timeTaken/1000)+'s' ); + return timeTaken; + } +} + +Test.Unit.Testcase = Class.create(); +Object.extend(Object.extend(Test.Unit.Testcase.prototype, Test.Unit.Assertions.prototype), { + initialize: function(name, test, setup, teardown) { + Test.Unit.Assertions.prototype.initialize.bind(this)(); + this.name = name; + this.test = test || function() {}; + this.setup = setup || function() {}; + this.teardown = teardown || function() {}; + this.isWaiting = false; + this.timeToWait = 1000; + }, + wait: function(time, nextPart) { + this.isWaiting = true; + this.test = nextPart; + this.timeToWait = time; + }, + run: function() { + try { + try { + if (!this.isWaiting) this.setup.bind(this)(); + this.isWaiting = false; + this.test.bind(this)(); + } finally { + if(!this.isWaiting) { + this.teardown.bind(this)(); + } + } + } + catch(e) { this.error(e); } + } +}); diff --git a/wp-inst/wp-includes/template-functions-links.php b/wp-inst/wp-includes/link-template.php index 16126b1..81f4d7c 100644 --- a/wp-inst/wp-includes/template-functions-links.php +++ b/wp-inst/wp-includes/link-template.php @@ -84,6 +84,11 @@ function get_permalink($id = 0) { } } +// get permalink from post ID +function post_permalink($post_id = 0, $mode = '') { // $mode legacy + return get_permalink($post_id); +} + function get_page_link($id = false) { global $post, $wp_rewrite; @@ -100,6 +105,9 @@ function get_page_link($id = false) { $link = get_settings('home') . "/?page_id=$id"; } + if ( 'page' == get_option('show_on_front') && $id == get_option('page_on_front') ) + $link = get_settings('home'); + return apply_filters('page_link', $link, $id); } diff --git a/wp-inst/wp-includes/pluggable-functions.php b/wp-inst/wp-includes/pluggable.php index 4d6f061..3ef5974 100644 --- a/wp-inst/wp-includes/pluggable-functions.php +++ b/wp-inst/wp-includes/pluggable.php @@ -168,7 +168,7 @@ if ( !function_exists('wp_mail') ) : function wp_mail($to, $subject, $message, $headers = '') { if( $headers == '' ) { $headers = "MIME-Version: 1.0\n" . - "From: " . get_settings('admin_email') . "\n" . + "From: wordpress@" . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME'])) . "\n" . "Content-Type: text/plain; charset=\"" . get_settings('blog_charset') . "\"\n"; } @@ -394,14 +394,14 @@ function wp_notify_postauthor($comment_id, $comment_type='') { $notify_message .= sprintf( __('To delete this comment, visit: %s'), get_settings('siteurl').'/wp-admin/comment.php?action=confirmdeletecomment&p='.$comment->comment_post_ID."&comment=$comment_id" ) . "\r\n"; $notify_message .= sprintf( __('To mark this comment as spam, visit: %s'), get_settings('siteurl').'/wp-admin/comment.php?action=confirmdeletecomment&delete_type=spam&p='.$comment->comment_post_ID."&comment=$comment_id" ) . "\r\n"; - $admin_email = get_settings('admin_email'); + $wp_email = 'wordpress@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME'])); if ( '' == $comment->comment_author ) { - $from = "From: \"$blogname\" <$admin_email>"; + $from = "From: \"$blogname\" <$wp_email>"; if ( '' != $comment->comment_author_email ) $reply_to = "Reply-To: $comment->comment_author_email"; } else { - $from = "From: \"$comment->comment_author\" <$admin_email>"; + $from = "From: \"$comment->comment_author\" <$wp_email>"; if ( '' != $comment->comment_author_email ) $reply_to = "Reply-To: \"$comment->comment_author_email\" <$comment->comment_author_email>"; } diff --git a/wp-inst/wp-includes/template-functions-post.php b/wp-inst/wp-includes/post-template.php index 40e3b32..1c18980 100644 --- a/wp-inst/wp-includes/template-functions-post.php +++ b/wp-inst/wp-includes/post-template.php @@ -1,25 +1,21 @@ <?php -function get_the_password_form() { - $output = '<form action="' . get_settings('siteurl') . '/wp-pass.php" method="post"> - <p>' . __("This post is password protected. To view it please enter your password below:") . '</p> - <p><label>' . __("Password:") . ' <input name="post_password" type="password" size="20" /></label> <input type="submit" name="Submit" value="' . __("Submit") . '" /></p> - </form> - '; - return $output; -} - +// +// "The Loop" post functions +// function the_ID() { global $id; echo $id; } + function get_the_ID() { global $id; return $id; } + function the_title($before = '', $after = '', $echo = true) { $title = get_the_title(); if ( strlen($title) > 0 ) { @@ -42,6 +38,9 @@ function get_the_title($id = 0) { return $title; } +function the_guid( $id = 0 ) { + echo get_the_guid($id); +} function get_the_guid( $id = 0 ) { $post = &get_post($id); @@ -49,12 +48,6 @@ function get_the_guid( $id = 0 ) { return apply_filters('get_the_guid', $post->guid); } - -function the_guid( $id = 0 ) { - echo get_the_guid($id); -} - - function the_content($more_link_text = '(more...)', $stripteaser = 0, $more_file = '') { $content = get_the_content($more_link_text, $stripteaser, $more_file); $content = apply_filters('the_content', $content); @@ -190,59 +183,9 @@ function link_pages($before='<br />', $after='<br />', $next_or_number='number', } -/* -Post-meta: Custom per-post fields. -*/ - - -function get_post_custom( $post_id = 0 ) { - global $id, $post_meta_cache, $wpdb; - - if ( ! $post_id ) - $post_id = $id; - - if ( isset($post_meta_cache[$post_id]) ) - return $post_meta_cache[$post_id]; - - if ( $meta_list = $wpdb->get_results("SELECT post_id, meta_key, meta_value FROM $wpdb->postmeta WHERE post_id = '$post_id' ORDER BY post_id, meta_key", ARRAY_A) ) { - // Change from flat structure to hierarchical: - $post_meta_cache = array(); - foreach ( $meta_list as $metarow ) { - $mpid = $metarow['post_id']; - $mkey = $metarow['meta_key']; - $mval = $metarow['meta_value']; - - // Force subkeys to be array type: - if ( !isset($post_meta_cache[$mpid]) || !is_array($post_meta_cache[$mpid]) ) - $post_meta_cache[$mpid] = array(); - - if ( !isset($post_meta_cache[$mpid]["$mkey"]) || !is_array($post_meta_cache[$mpid]["$mkey"]) ) - $post_meta_cache[$mpid]["$mkey"] = array(); - - // Add a value to the current pid/key: - $post_meta_cache[$mpid][$mkey][] = $mval; - } - return $post_meta_cache[$mpid]; - } -} - - -function get_post_custom_keys() { - $custom = get_post_custom(); - - if ( ! is_array($custom) ) - return; - - if ( $keys = array_keys($custom) ) - return $keys; -} - - -function get_post_custom_values( $key = '' ) { - $custom = get_post_custom(); - - return $custom[$key]; -} +// +// Post-meta: Custom per-post fields. +// function post_custom( $key = '' ) { @@ -274,107 +217,9 @@ function the_meta() { } -/* -Pages -*/ - -function walk_page_tree() { - $walker = new Walker_Page; - $args = func_get_args(); - return call_user_func_array(array(&$walker, 'walk'), $args); -} - -function walk_page_dropdown_tree() { - $walker = new Walker_PageDropdown; - $args = func_get_args(); - return call_user_func_array(array(&$walker, 'walk'), $args); -} - -function &get_page_children($page_id, $pages) { - global $page_cache; - - if ( empty($pages) ) - $pages = &$page_cache; - - $page_list = array(); - foreach ( $pages as $page ) { - if ( $page->post_parent == $page_id ) { - $page_list[] = $page; - if ( $children = get_page_children($page->ID, $pages) ) - $page_list = array_merge($page_list, $children); - } - } - return $page_list; -} - - -function &get_pages($args = '') { - global $wpdb; - - if ( is_array($args) ) - $r = &$args; - else - parse_str($args, $r); - - $defaults = array('child_of' => 0, 'sort_order' => 'ASC', 'sort_column' => 'post_title', - 'hierarchical' => 1, 'exclude' => '', 'include' => '', 'meta_key' => '', 'meta_value' => ''); - $r = array_merge($defaults, $r); - extract($r); - - $inclusions = ''; - if ( !empty($include) ) { - $child_of = 0; //ignore child_of, exclude, meta_key, and meta_value params if using include - $exclude = ''; - $meta_key = ''; - $meta_value = ''; - $incpages = preg_split('/[\s,]+/',$include); - if ( count($incpages) ) { - foreach ( $incpages as $incpage ) { - if (empty($inclusions)) - $inclusions = ' AND ( ID = ' . intval($incpage) . ' '; - else - $inclusions .= ' OR ID = ' . intval($incpage) . ' '; - } - } - } - if (!empty($inclusions)) - $inclusions .= ')'; - - $exclusions = ''; - if ( !empty($exclude) ) { - $expages = preg_split('/[\s,]+/',$exclude); - if ( count($expages) ) { - foreach ( $expages as $expage ) { - if (empty($exclusions)) - $exclusions = ' AND ( ID <> ' . intval($expage) . ' '; - else - $exclusions .= ' AND ID <> ' . intval($expage) . ' '; - } - } - } - if (!empty($exclusions)) - $exclusions .= ')'; - - $query = "SELECT * FROM $wpdb->posts " ; - $query .= ( empty( $meta_key ) ? "" : ", $wpdb->postmeta " ) ; - $query .= " WHERE (post_type = 'page' AND post_status = 'publish') $exclusions $inclusions " ; - $query .= ( empty( $meta_key ) | empty($meta_value) ? "" : " AND ($wpdb->posts.ID = $wpdb->postmeta.post_id AND $wpdb->postmeta.meta_key = '$meta_key' AND $wpdb->postmeta.meta_value = '$meta_value' )" ) ; - $query .= " ORDER BY " . $sort_column . " " . $sort_order ; - - $pages = $wpdb->get_results($query); - $pages = apply_filters('get_pages', $pages, $r); - - if ( empty($pages) ) - return array(); - - // Update cache. - update_page_cache($pages); - - if ( $child_of || $hierarchical ) - $pages = & get_page_children($child_of, $pages); - - return $pages; -} +// +// Pages +// function wp_dropdown_pages($args = '') { if ( is_array($args) ) @@ -383,7 +228,7 @@ function wp_dropdown_pages($args = '') { parse_str($args, $r); $defaults = array('depth' => 0, 'child_of' => 0, 'selected' => 0, 'echo' => 1, - 'name' => 'page_id'); + 'name' => 'page_id', 'show_option_none' => ''); $r = array_merge($defaults, $r); extract($r); @@ -392,6 +237,8 @@ function wp_dropdown_pages($args = '') { if ( ! empty($pages) ) { $output = "<select name='$name'>\n"; + if ( $show_option_none ) + $output .= "\t<option value=''>$show_option_none</option>\n"; $output .= walk_page_dropdown_tree($pages, $depth, $r); $output .= "</select>\n"; } @@ -439,6 +286,26 @@ function wp_list_pages($args = '') { return $output; } +// +// Page helpers +// + +function walk_page_tree() { + $walker = new Walker_Page; + $args = func_get_args(); + return call_user_func_array(array(&$walker, 'walk'), $args); +} + +function walk_page_dropdown_tree() { + $walker = new Walker_PageDropdown; + $args = func_get_args(); + return call_user_func_array(array(&$walker, 'walk'), $args); +} + +// +// Attachments +// + function the_attachment_link($id = 0, $fullsize = false, $max_dims = false) { echo get_the_attachment_link($id, $fullsize, $max_dims); } @@ -561,4 +428,17 @@ function prepend_attachment($content) { return "$p\n$content"; } +// +// Misc +// + +function get_the_password_form() { + $output = '<form action="' . get_settings('siteurl') . '/wp-pass.php" method="post"> + <p>' . __("This post is password protected. To view it please enter your password below:") . '</p> + <p><label>' . __("Password:") . ' <input name="post_password" type="password" size="20" /></label> <input type="submit" name="Submit" value="' . __("Submit") . '" /></p> + </form> + '; + return $output; +} + ?> diff --git a/wp-inst/wp-includes/functions-post.php b/wp-inst/wp-includes/post.php index 7c2e497..ce1a227 100644 --- a/wp-inst/wp-includes/functions-post.php +++ b/wp-inst/wp-includes/post.php @@ -1,10 +1,477 @@ <?php -/**** DB Functions ****/ +// +// Post functions +// + +function get_attached_file($attachment_id) { + return get_post_meta($attachment_id, '_wp_attached_file', true); +} + +function &get_children($post = 0, $output = OBJECT) { + global $post_cache, $wpdb; + + if ( empty($post) ) { + if ( isset($GLOBALS['post']) ) + $post_parent = & $GLOBALS['post']->post_parent; + else + return false; + } elseif ( is_object($post) ) { + $post_parent = $post->post_parent; + } else { + $post_parent = $post; + } + + $post_parent = (int) $post_parent; + + $query = "SELECT * FROM $wpdb->posts WHERE post_parent = $post_parent"; + + $children = $wpdb->get_results($query); + + if ( $children ) { + foreach ( $children as $key => $child ) { + $post_cache[$child->ID] =& $children[$key]; + $kids[$child->ID] =& $children[$key]; + } + } else { + return false; + } + + if ( $output == OBJECT ) { + return $kids; + } elseif ( $output == ARRAY_A ) { + foreach ( $kids as $kid ) + $weeuns[$kid->ID] = get_object_vars($kids[$kid->ID]); + return $weeuns; + } elseif ( $output == ARRAY_N ) { + foreach ( $kids as $kid ) + $babes[$kid->ID] = array_values(get_object_vars($kids[$kid->ID])); + return $babes; + } else { + return $kids; + } +} + +// get extended entry info (<!--more-->) +function get_extended($post) { + list($main,$extended) = explode('<!--more-->', $post, 2); + + // Strip leading and trailing whitespace + $main = preg_replace('/^[\s]*(.*)[\s]*$/','\\1',$main); + $extended = preg_replace('/^[\s]*(.*)[\s]*$/','\\1',$extended); + + return array('main' => $main, 'extended' => $extended); +} + +// Retrieves post data given a post ID or post object. +// Handles post caching. +function &get_post(&$post, $output = OBJECT) { + global $post_cache, $wpdb; + + if ( empty($post) ) { + if ( isset($GLOBALS['post']) ) + $_post = & $GLOBALS['post']; + else + $_post = null; + } elseif ( is_object($post) ) { + if ( 'page' == $post->post_type ) + return get_page($post, $output); + if ( !isset($post_cache[$post->ID]) ) + $post_cache[$post->ID] = &$post; + $_post = & $post_cache[$post->ID]; + } else { + if ( $_post = wp_cache_get($post, 'pages') ) + return get_page($_post, $output); + elseif ( isset($post_cache[$post]) ) + $_post = & $post_cache[$post]; + else { + $query = "SELECT * FROM $wpdb->posts WHERE ID = '$post' LIMIT 1"; + $_post = & $wpdb->get_row($query); + if ( 'page' == $_post->post_type ) + return get_page($_post, $output); + $post_cache[$post] = & $_post; + } + } + + if ( defined(WP_IMPORTING) ) + unset($post_cache); + + if ( $output == OBJECT ) { + return $_post; + } elseif ( $output == ARRAY_A ) { + return get_object_vars($_post); + } elseif ( $output == ARRAY_N ) { + return array_values(get_object_vars($_post)); + } else { + return $_post; + } +} + +// Takes a post ID, returns its mime type. +function get_post_mime_type($ID = '') { + $post = & get_post($ID); + + if ( is_object($post) ) + return $post->post_mime_type; + + return false; +} + +function get_post_status($ID = '') { + $post = get_post($ID); + + if ( is_object($post) ) { + if ( ('attachment' == $post->post_type) && $post->post_parent && ($post->ID != $post->post_parent) ) + return get_post_status($post->post_parent); + else + return $post->post_status; + } + + return false; +} + +function get_post_type($post = false) { + global $wpdb, $posts; + + if ( false === $post ) + $post = $posts[0]; + elseif ( (int) $post ) + $post = get_post($post, OBJECT); + + if ( is_object($post) ) + return $post->post_type; + + return false; +} + +function get_posts($args) { + global $wpdb; + + if ( is_array($args) ) + $r = &$args; + else + parse_str($args, $r); + + $defaults = array('numberposts' => 5, 'offset' => 0, 'category' => '', + 'orderby' => 'post_date', 'order' => 'DESC', 'include' => '', 'exclude' => '', 'meta_key' => '', 'meta_value' =>''); + $r = array_merge($defaults, $r); + extract($r); + + $inclusions = ''; + if ( !empty($include) ) { + $offset = 0; //ignore offset, category, exclude, meta_key, and meta_value params if using include + $category = ''; + $exclude = ''; + $meta_key = ''; + $meta_value = ''; + $incposts = preg_split('/[\s,]+/',$include); + $numberposts = count($incposts); // only the number of posts included + if ( count($incposts) ) { + foreach ( $incposts as $incpost ) { + if (empty($inclusions)) + $inclusions = ' AND ( ID = ' . intval($incpost) . ' '; + else + $inclusions .= ' OR ID = ' . intval($incpost) . ' '; + } + } + } + if (!empty($inclusions)) + $inclusions .= ')'; + + $exclusions = ''; + if ( !empty($exclude) ) { + $exposts = preg_split('/[\s,]+/',$exclude); + if ( count($exposts) ) { + foreach ( $exposts as $expost ) { + if (empty($exclusions)) + $exclusions = ' AND ( ID <> ' . intval($expost) . ' '; + else + $exclusions .= ' AND ID <> ' . intval($expost) . ' '; + } + } + } + if (!empty($exclusions)) + $exclusions .= ')'; + + $query ="SELECT DISTINCT * FROM $wpdb->posts " ; + $query .= ( empty( $category ) ? "" : ", $wpdb->post2cat " ) ; + $query .= ( empty( $meta_key ) ? "" : ", $wpdb->postmeta " ) ; + $query .= " WHERE (post_type = 'post' AND post_status = 'publish') $exclusions $inclusions " ; + $query .= ( empty( $category ) ? "" : "AND ($wpdb->posts.ID = $wpdb->post2cat.post_id AND $wpdb->post2cat.category_id = " . $category. ") " ) ; + $query .= ( empty( $meta_key ) | empty($meta_value) ? "" : " AND ($wpdb->posts.ID = $wpdb->postmeta.post_id AND $wpdb->postmeta.meta_key = '$meta_key' AND $wpdb->postmeta.meta_value = '$meta_value' )" ) ; + $query .= " GROUP BY $wpdb->posts.ID ORDER BY " . $orderby . " " . $order . " LIMIT " . $offset . ',' . $numberposts ; + + $posts = $wpdb->get_results($query); + + update_post_caches($posts); + + return $posts; +} + +// +// Post meta functions +// + +function add_post_meta($post_id, $key, $value, $unique = false) { + global $wpdb, $post_meta_cache; + + if ( $unique ) { + if ( $wpdb->get_var("SELECT meta_key FROM $wpdb->postmeta WHERE meta_key += '$key' AND post_id = '$post_id'") ) { + return false; + } + } + + $original = $value; + if ( is_array($value) || is_object($value) ) + $value = $wpdb->escape(serialize($value)); + + $wpdb->query("INSERT INTO $wpdb->postmeta (post_id,meta_key,meta_value) VALUES ('$post_id','$key','$value')"); + + $post_meta_cache['$post_id'][$key][] = $original; + + return true; +} + +function delete_post_meta($post_id, $key, $value = '') { + global $wpdb, $post_meta_cache; + + if ( empty($value) ) { + $meta_id = $wpdb->get_var("SELECT meta_id FROM $wpdb->postmeta WHERE +post_id = '$post_id' AND meta_key = '$key'"); + } else { + $meta_id = $wpdb->get_var("SELECT meta_id FROM $wpdb->postmeta WHERE +post_id = '$post_id' AND meta_key = '$key' AND meta_value = '$value'"); + } + + if ( !$meta_id ) + return false; + + if ( empty($value) ) { + $wpdb->query("DELETE FROM $wpdb->postmeta WHERE post_id = '$post_id' +AND meta_key = '$key'"); + unset($post_meta_cache['$post_id'][$key]); + } else { + $wpdb->query("DELETE FROM $wpdb->postmeta WHERE post_id = '$post_id' +AND meta_key = '$key' AND meta_value = '$value'"); + $cache_key = $post_meta_cache['$post_id'][$key]; + if ($cache_key) foreach ( $cache_key as $index => $data ) + if ( $data == $value ) + unset($post_meta_cache['$post_id'][$key][$index]); + } + + unset($post_meta_cache['$post_id'][$key]); + + return true; +} + +function get_post_meta($post_id, $key, $single = false) { + global $wpdb, $post_meta_cache; + + if ( isset($post_meta_cache[$post_id][$key]) ) { + if ( $single ) { + return maybe_unserialize( $post_meta_cache[$post_id][$key][0] ); + } else { + return maybe_unserialize( $post_meta_cache[$post_id][$key] ); + } + } + + $metalist = $wpdb->get_results("SELECT meta_value FROM $wpdb->postmeta WHERE post_id = '$post_id' AND meta_key = '$key'", ARRAY_N); + + $values = array(); + if ( $metalist ) { + foreach ($metalist as $metarow) { + $values[] = $metarow[0]; + } + } + + if ( $single ) { + if ( count($values) ) { + $return = maybe_unserialize( $values[0] ); + } else { + return ''; + } + } else { + $return = $values; + } + + return maybe_unserialize($return); +} + +function update_post_meta($post_id, $key, $value, $prev_value = '') { + global $wpdb, $post_meta_cache; + + $original_value = $value; + if ( is_array($value) || is_object($value) ) + $value = $wpdb->escape(serialize($value)); + + $original_prev = $prev_value; + if ( is_array($prev_value) || is_object($prev_value) ) + $prev_value = $wpdb->escape(serialize($prev_value)); + + if (! $wpdb->get_var("SELECT meta_key FROM $wpdb->postmeta WHERE meta_key += '$key' AND post_id = '$post_id'") ) { + return false; + } + + if ( empty($prev_value) ) { + $wpdb->query("UPDATE $wpdb->postmeta SET meta_value = '$value' WHERE +meta_key = '$key' AND post_id = '$post_id'"); + $cache_key = $post_meta_cache['$post_id'][$key]; + if ( !empty($cache_key) ) + foreach ($cache_key as $index => $data) + $post_meta_cache['$post_id'][$key][$index] = $original_value; + } else { + $wpdb->query("UPDATE $wpdb->postmeta SET meta_value = '$value' WHERE +meta_key = '$key' AND post_id = '$post_id' AND meta_value = '$prev_value'"); + $cache_key = $post_meta_cache['$post_id'][$key]; + if ( !empty($cache_key) ) + foreach ($cache_key as $index => $data) + if ( $data == $original_prev ) + $post_meta_cache['$post_id'][$key][$index] = $original_value; + } + + return true; +} + + +function get_post_custom( $post_id = 0 ) { + global $id, $post_meta_cache, $wpdb; + + if ( ! $post_id ) + $post_id = $id; + + if ( isset($post_meta_cache[$post_id]) ) + return $post_meta_cache[$post_id]; + + if ( $meta_list = $wpdb->get_results("SELECT post_id, meta_key, meta_value FROM $wpdb->postmeta WHERE post_id = '$post_id' ORDER BY post_id, meta_key", ARRAY_A) ) { + // Change from flat structure to hierarchical: + $post_meta_cache = array(); + foreach ( $meta_list as $metarow ) { + $mpid = $metarow['post_id']; + $mkey = $metarow['meta_key']; + $mval = $metarow['meta_value']; + + // Force subkeys to be array type: + if ( !isset($post_meta_cache[$mpid]) || !is_array($post_meta_cache[$mpid]) ) + $post_meta_cache[$mpid] = array(); + + if ( !isset($post_meta_cache[$mpid]["$mkey"]) || !is_array($post_meta_cache[$mpid]["$mkey"]) ) + $post_meta_cache[$mpid]["$mkey"] = array(); + + // Add a value to the current pid/key: + $post_meta_cache[$mpid][$mkey][] = $mval; + } + return $post_meta_cache[$mpid]; + } +} + +function get_post_custom_keys( $post_id = 0 ) { + $custom = get_post_custom( $post_id ); + + if ( ! is_array($custom) ) + return; + + if ( $keys = array_keys($custom) ) + return $keys; +} + + +function get_post_custom_values( $key = '', $post_id = 0 ) { + $custom = get_post_custom($post_id); + + return $custom[$key]; +} + +function wp_delete_post($postid = 0) { + global $wpdb, $wp_rewrite; + $postid = (int) $postid; + + if ( !$post = $wpdb->get_row("SELECT * FROM $wpdb->posts WHERE ID = $postid") ) + return $post; + + if ( 'attachment' == $post->post_type ) + return wp_delete_attachment($postid); + + do_action('delete_post', $postid); + + if ( 'publish' == $post->post_status && 'post' == $post->post_type ) { + $categories = wp_get_post_categories($post->ID); + if( is_array( $categories ) ) { + foreach ( $categories as $cat_id ) { + $wpdb->query("UPDATE $wpdb->categories SET category_count = category_count - 1 WHERE cat_ID = '$cat_id'"); + wp_cache_delete($cat_id, 'category'); + } + } + } + + if ( 'page' == $post->post_type ) + $wpdb->query("UPDATE $wpdb->posts SET post_parent = $post->post_parent WHERE post_parent = $postid AND post_type = 'page'"); + + $wpdb->query("DELETE FROM $wpdb->posts WHERE ID = $postid"); + + $wpdb->query("DELETE FROM $wpdb->comments WHERE comment_post_ID = $postid"); + + $wpdb->query("DELETE FROM $wpdb->post2cat WHERE post_id = $postid"); + + $wpdb->query("DELETE FROM $wpdb->postmeta WHERE post_id = $postid"); + + if ( 'page' == $post->type ) { + wp_cache_delete('all_page_ids', 'pages'); + $wp_rewrite->flush_rules(); + } + + return $post; +} + +function wp_get_post_categories($post_ID = 0) { + global $wpdb; + + $post_ID = (int) $post_ID; + + $sql = "SELECT category_id + FROM $wpdb->post2cat + WHERE post_id = '$post_ID' + ORDER BY category_id"; + + $result = $wpdb->get_col($sql); + + if ( !$result ) + $result = array(); + + return array_unique($result); +} + +function wp_get_recent_posts($num = 10) { + global $wpdb; + + // Set the limit clause, if we got a limit + if ($num) { + $limit = "LIMIT $num"; + } + + $sql = "SELECT * FROM $wpdb->posts WHERE post_type = 'post' ORDER BY post_date DESC $limit"; + $result = $wpdb->get_results($sql,ARRAY_A); + + return $result?$result:array(); +} + +function wp_get_single_post($postid = 0, $mode = OBJECT) { + global $wpdb; + + $post = get_post($postid, $mode); + + // Set categories + if($mode == OBJECT) { + $post->post_category = wp_get_post_categories($postid); + } + else { + $post['post_category'] = wp_get_post_categories($postid); + } + + return $post; +} -/* - * generic function for inserting data into the posts table. - */ function wp_insert_post($postarr = array()) { global $wpdb, $wp_rewrite, $allowedtags, $user_ID; @@ -223,217 +690,6 @@ function wp_insert_post($postarr = array()) { return $post_ID; } -function wp_insert_attachment($object, $file = false, $post_parent = 0) { - global $wpdb, $user_ID; - - if ( is_object($object) ) - $object = get_object_vars($object); - - // Export array as variables - extract($object); - - // Get the basics. - $post_content = apply_filters('content_save_pre', $post_content); - $post_excerpt = apply_filters('excerpt_save_pre', $post_excerpt); - $post_title = apply_filters('title_save_pre', $post_title); - $post_category = apply_filters('category_save_pre', $post_category); - $post_name = apply_filters('name_save_pre', $post_name); - $comment_status = apply_filters('comment_status_pre', $comment_status); - $ping_status = apply_filters('ping_status_pre', $ping_status); - $post_mime_type = apply_filters('post_mime_type_pre', $post_mime_type); - - // Make sure we set a valid category - if (0 == count($post_category) || !is_array($post_category)) { - $post_category = array(get_option('default_category')); - } - $post_cat = $post_category[0]; - - if ( empty($post_author) ) - $post_author = $user_ID; - - $post_type = 'attachment'; - $post_status = 'inherit'; - - // Are we updating or creating? - $update = false; - if ( !empty($ID) ) { - $update = true; - $post_ID = $ID; - } - - // Create a valid post name. - if ( empty($post_name) ) - $post_name = sanitize_title($post_title); - else - $post_name = sanitize_title($post_name); - - if (empty($post_date)) - $post_date = current_time('mysql'); - if (empty($post_date_gmt)) - $post_date_gmt = current_time('mysql', 1); - - if ( empty($comment_status) ) { - if ( $update ) - $comment_status = 'closed'; - else - $comment_status = get_settings('default_comment_status'); - } - if ( empty($ping_status) ) - $ping_status = get_settings('default_ping_status'); - if ( empty($post_pingback) ) - $post_pingback = get_option('default_pingback_flag'); - - if ( isset($to_ping) ) - $to_ping = preg_replace('|\s+|', "\n", $to_ping); - else - $to_ping = ''; - - if ( isset($post_parent) ) - $post_parent = (int) $post_parent; - else - $post_parent = 0; - - if ( isset($menu_order) ) - $menu_order = (int) $menu_order; - else - $menu_order = 0; - - if ( !isset($post_password) ) - $post_password = ''; - - if ( isset($to_ping) ) - $to_ping = preg_replace('|\s+|', "\n", $to_ping); - else - $to_ping = ''; - - if ( ! isset($pinged) ) - $pinged = ''; - - if ($update) { - $wpdb->query( - "UPDATE $wpdb->posts SET - post_author = '$post_author', - post_date = '$post_date', - post_date_gmt = '$post_date_gmt', - post_content = '$post_content', - post_content_filtered = '$post_content_filtered', - post_title = '$post_title', - post_excerpt = '$post_excerpt', - post_status = '$post_status', - post_type = '$post_type', - comment_status = '$comment_status', - ping_status = '$ping_status', - post_password = '$post_password', - post_name = '$post_name', - to_ping = '$to_ping', - pinged = '$pinged', - post_modified = '".current_time('mysql')."', - post_modified_gmt = '".current_time('mysql',1)."', - post_parent = '$post_parent', - menu_order = '$menu_order', - post_mime_type = '$post_mime_type', - guid = '$guid' - WHERE ID = $post_ID"); - } else { - $wpdb->query( - "INSERT INTO $wpdb->posts - (post_author, post_date, post_date_gmt, post_content, post_content_filtered, post_title, post_excerpt, post_status, post_type, comment_status, ping_status, post_password, post_name, to_ping, pinged, post_modified, post_modified_gmt, post_parent, menu_order, post_mime_type, guid) - VALUES - ('$post_author', '$post_date', '$post_date_gmt', '$post_content', '$post_content_filtered', '$post_title', '$post_excerpt', '$post_status', '$post_type', '$comment_status', '$ping_status', '$post_password', '$post_name', '$to_ping', '$pinged', '$post_date', '$post_date_gmt', '$post_parent', '$menu_order', '$post_mime_type', '$guid')"); - $post_ID = $wpdb->insert_id; - } - - if ( empty($post_name) ) { - $post_name = sanitize_title($post_title, $post_ID); - $wpdb->query( "UPDATE $wpdb->posts SET post_name = '$post_name' WHERE ID = '$post_ID'" ); - } - - wp_set_post_categories($post_ID, $post_category); - - if ( $file ) - add_post_meta($post_ID, '_wp_attached_file', $file ); - - clean_post_cache($post_ID); - - if ( $update) { - do_action('edit_attachment', $post_ID); - } else { - do_action('add_attachment', $post_ID); - } - - return $post_ID; -} - -function wp_delete_attachment($postid) { - global $wpdb; - $postid = (int) $postid; - - if ( !$post = $wpdb->get_row("SELECT * FROM $wpdb->posts WHERE ID = '$postid'") ) - return $post; - - if ( 'attachment' != $post->post_type ) - return false; - - $meta = get_post_meta($postid, '_wp_attachment_metadata', true); - $file = get_post_meta($postid, '_wp_attached_file', true); - - $wpdb->query("DELETE FROM $wpdb->posts WHERE ID = '$postid'"); - - $wpdb->query("DELETE FROM $wpdb->comments WHERE comment_post_ID = '$postid'"); - - $wpdb->query("DELETE FROM $wpdb->post2cat WHERE post_id = '$postid'"); - - $wpdb->query("DELETE FROM $wpdb->postmeta WHERE post_id = '$postid'"); - - if ( ! empty($meta['thumb']) ) { - // Don't delete the thumb if another attachment uses it - if (! $wpdb->get_row("SELECT meta_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attachment_metadata' AND meta_value LIKE '%".$wpdb->escape($meta['thumb'])."%' AND post_id <> $postid")) { - $thumbfile = str_replace(basename($file), $meta['thumb'], $file); - $thumbfile = apply_filters('wp_delete_file', $thumbfile); - @ unlink($thumbfile); - } - } - - $file = apply_filters('wp_delete_file', $file); - - if ( ! empty($file) ) - @ unlink($file); - - do_action('delete_attachment', $postid); - - return $post; -} - -function wp_get_single_post($postid = 0, $mode = OBJECT) { - global $wpdb; - - $post = get_post($postid, $mode); - - // Set categories - if($mode == OBJECT) { - $post->post_category = wp_get_post_categories($postid); - } - else { - $post['post_category'] = wp_get_post_categories($postid); - } - - return $post; -} - -function wp_get_recent_posts($num = 10) { - global $wpdb; - - // Set the limit clause, if we got a limit - if ($num) { - $limit = "LIMIT $num"; - } - - $sql = "SELECT * FROM $wpdb->posts WHERE post_type = 'post' ORDER BY post_date DESC $limit"; - $result = $wpdb->get_results($sql,ARRAY_A); - - return $result?$result:array(); -} - function wp_update_post($postarr = array()) { global $wpdb; @@ -486,24 +742,6 @@ function wp_publish_post($post_id) { return wp_update_post(array('post_status' => 'publish', 'ID' => $post_id)); } -function wp_get_post_categories($post_ID = 0) { - global $wpdb; - - $post_ID = (int) $post_ID; - - $sql = "SELECT category_id - FROM $wpdb->post2cat - WHERE post_id = '$post_ID' - ORDER BY category_id"; - - $result = $wpdb->get_col($sql); - - if ( !$result ) - $result = array(); - - return array_unique($result); -} - function wp_set_post_categories($post_ID = 0, $post_categories = array()) { global $wpdb; // If $post_categories isn't already an array, make it one: @@ -557,76 +795,59 @@ function wp_set_post_categories($post_ID = 0, $post_categories = array()) { } } // wp_set_post_categories() -function wp_delete_post($postid = 0) { - global $wpdb, $wp_rewrite; - $postid = (int) $postid; - - if ( !$post = $wpdb->get_row("SELECT * FROM $wpdb->posts WHERE ID = $postid") ) - return $post; +// +// Trackback and ping functions +// - if ( 'attachment' == $post->post_type ) - return wp_delete_attachment($postid); +function add_ping($post_id, $uri) { // Add a URI to those already pung + global $wpdb; + $pung = $wpdb->get_var("SELECT pinged FROM $wpdb->posts WHERE ID = $post_id"); + $pung = trim($pung); + $pung = preg_split('/\s/', $pung); + $pung[] = $uri; + $new = implode("\n", $pung); + $new = apply_filters('add_ping', $new); + return $wpdb->query("UPDATE $wpdb->posts SET pinged = '$new' WHERE ID = $post_id"); +} - do_action('delete_post', $postid); +function get_enclosed($post_id) { // Get enclosures already enclosed for a post + global $wpdb; + $custom_fields = get_post_custom( $post_id ); + $pung = array(); + if ( !is_array( $custom_fields ) ) + return $pung; - if ( 'publish' == $post->post_status && 'post' == $post->post_type ) { - $categories = wp_get_post_categories($post->ID); - if( is_array( $categories ) ) { - foreach ( $categories as $cat_id ) { - $wpdb->query("UPDATE $wpdb->categories SET category_count = category_count - 1 WHERE cat_ID = '$cat_id'"); - wp_cache_delete($cat_id, 'category'); - } + foreach ( $custom_fields as $key => $val ) { + if ( 'enclosure' != $key || !is_array( $val ) ) + continue; + foreach( $val as $enc ) { + $enclosure = split( "\n", $enc ); + $pung[] = trim( $enclosure[ 0 ] ); } } - - if ( 'page' == $post->post_type ) - $wpdb->query("UPDATE $wpdb->posts SET post_parent = $post->post_parent WHERE post_parent = $postid AND post_type = 'page'"); - - $wpdb->query("DELETE FROM $wpdb->posts WHERE ID = $postid"); - - $wpdb->query("DELETE FROM $wpdb->comments WHERE comment_post_ID = $postid"); - - $wpdb->query("DELETE FROM $wpdb->post2cat WHERE post_id = $postid"); - - $wpdb->query("DELETE FROM $wpdb->postmeta WHERE post_id = $postid"); - - if ( 'page' == $post->type ) { - wp_cache_delete('all_page_ids', 'pages'); - $wp_rewrite->flush_rules(); - } - - return $post; -} - -/**** /DB Functions ****/ - -/**** Misc ****/ - -// get permalink from post ID -function post_permalink($post_id = 0, $mode = '') { // $mode legacy - return get_permalink($post_id); + $pung = apply_filters('get_enclosed', $pung); + return $pung; } -// Get author's preferred display name -function get_author_name( $auth_id ) { - $authordata = get_userdata( $auth_id ); - - return $authordata->display_name; +function get_pung($post_id) { // Get URIs already pung for a post + global $wpdb; + $pung = $wpdb->get_var("SELECT pinged FROM $wpdb->posts WHERE ID = $post_id"); + $pung = trim($pung); + $pung = preg_split('/\s/', $pung); + $pung = apply_filters('get_pung', $pung); + return $pung; } -// get extended entry info (<!--more-->) -function get_extended($post) { - list($main,$extended) = explode('<!--more-->', $post, 2); - - // Strip leading and trailing whitespace - $main = preg_replace('/^[\s]*(.*)[\s]*$/','\\1',$main); - $extended = preg_replace('/^[\s]*(.*)[\s]*$/','\\1',$extended); - - return array('main' => $main, 'extended' => $extended); +function get_to_ping($post_id) { // Get any URIs in the todo list + global $wpdb; + $to_ping = $wpdb->get_var("SELECT to_ping FROM $wpdb->posts WHERE ID = $post_id"); + $to_ping = trim($to_ping); + $to_ping = preg_split('/\s/', $to_ping, -1, PREG_SPLIT_NO_EMPTY); + $to_ping = apply_filters('get_to_ping', $to_ping); + return $to_ping; } // do trackbacks for a list of urls -// borrowed from edit.php // accepts a comma-separated list of trackback urls and a post id function trackback_url_list($tb_list, $post_id) { if (!empty($tb_list)) { @@ -651,145 +872,113 @@ function trackback_url_list($tb_list, $post_id) { } } -function wp_blacklist_check($author, $email, $url, $comment, $user_ip, $user_agent) { - global $wpdb; +// +// Page functions +// - do_action('wp_blacklist_check', $author, $email, $url, $comment, $user_ip, $user_agent); +function get_all_page_ids() { + global $wpdb; - if ( preg_match_all('/&#(\d+);/', $comment . $author . $url, $chars) ) { - foreach ($chars[1] as $char) { - // If it's an encoded char in the normal ASCII set, reject - if ( 38 == $char ) - continue; // Unless it's & - if ($char < 128) - return true; - } + if ( ! $page_ids = wp_cache_get('all_page_ids', 'pages') ) { + $page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'page'"); + wp_cache_add('all_page_ids', $page_ids, 'pages'); } - $mod_keys = trim( get_settings('blacklist_keys') ); - if ('' == $mod_keys ) - return false; // If moderation keys are empty - $words = explode("\n", $mod_keys ); - - foreach ($words as $word) { - $word = trim($word); - - // Skip empty lines - if ( empty($word) ) { continue; } + return $page_ids; +} - // Do some escaping magic so that '#' chars in the - // spam words don't break things: - $word = preg_quote($word, '#'); - $pattern = "#$word#i"; - if ( preg_match($pattern, $author ) ) return true; - if ( preg_match($pattern, $email ) ) return true; - if ( preg_match($pattern, $url ) ) return true; - if ( preg_match($pattern, $comment ) ) return true; - if ( preg_match($pattern, $user_ip ) ) return true; - if ( preg_match($pattern, $user_agent) ) return true; - } +// Retrieves page data given a page ID or page object. +// Handles page caching. +function &get_page(&$page, $output = OBJECT) { + global $wpdb; - if ( isset($_SERVER['REMOTE_ADDR']) ) { - if ( wp_proxy_check($_SERVER['REMOTE_ADDR']) ) return true; + if ( empty($page) ) { + if ( isset($GLOBALS['page']) ) { + $_page = & $GLOBALS['page']; + wp_cache_add($_page->ID, $_page, 'pages'); + } else { + $_page = null; + } + } elseif ( is_object($page) ) { + if ( 'post' == $page->post_type ) + return get_post($page, $output); + wp_cache_add($page->ID, $page, 'pages'); + $_page = $page; + } else { + if ( isset($GLOBALS['page']) && ($page == $GLOBALS['page']->ID) ) { + $_page = & $GLOBALS['page']; + wp_cache_add($_page->ID, $_page, 'pages'); + } elseif ( $_page = $GLOBALS['post_cache'][$page] ) { + return get_post($page, $output); + } elseif ( $_page = wp_cache_get($page, 'pages') ) { + // Got it. + } else { + $query = "SELECT * FROM $wpdb->posts WHERE ID= '$page' LIMIT 1"; + $_page = & $wpdb->get_row($query); + if ( 'post' == $_page->post_type ) + return get_post($_page, $output); + wp_cache_add($_page->ID, $_page, 'pages'); + } } - return false; -} - -function wp_proxy_check($ipnum) { - if ( get_option('open_proxy_check') && isset($ipnum) ) { - $rev_ip = implode( '.', array_reverse( explode( '.', $ipnum ) ) ); - $lookup = $rev_ip . '.opm.blitzed.org.'; - if ( $lookup != gethostbyname( $lookup ) ) - return true; + if ( $output == OBJECT ) { + return $_page; + } elseif ( $output == ARRAY_A ) { + return get_object_vars($_page); + } elseif ( $output == ARRAY_N ) { + return array_values(get_object_vars($_page)); + } else { + return $_page; } - - return false; } -function do_trackbacks($post_id) { +function get_page_by_path($page_path, $output = OBJECT) { global $wpdb; + $page_path = rawurlencode(urldecode($page_path)); + $page_path = str_replace('%2F', '/', $page_path); + $page_path = str_replace('%20', ' ', $page_path); + $page_paths = '/' . trim($page_path, '/'); + $leaf_path = sanitize_title(basename($page_paths)); + $page_paths = explode('/', $page_paths); + foreach($page_paths as $pathdir) + $full_path .= ($pathdir!=''?'/':'') . sanitize_title($pathdir); + + $pages = $wpdb->get_results("SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_name = '$leaf_path' AND post_type='page'"); + + if ( empty($pages) ) + return NULL; + + foreach ($pages as $page) { + $path = '/' . $leaf_path; + $curpage = $page; + while ($curpage->post_parent != 0) { + $curpage = $wpdb->get_row("SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE ID = '$curpage->post_parent' and post_type='page'"); + $path = '/' . $curpage->post_name . $path; + } - $post = $wpdb->get_row("SELECT * FROM $wpdb->posts WHERE ID = $post_id"); - $to_ping = get_to_ping($post_id); - $pinged = get_pung($post_id); - if ( empty($to_ping) ) { - $wpdb->query("UPDATE $wpdb->posts SET to_ping = '' WHERE ID = '$post_id'"); - return; + if ( $path == $full_path ) + return get_page($page->ID, $output); } - if (empty($post->post_excerpt)) - $excerpt = apply_filters('the_content', $post->post_content); - else - $excerpt = apply_filters('the_excerpt', $post->post_excerpt); - $excerpt = str_replace(']]>', ']]>', $excerpt); - $excerpt = strip_tags($excerpt); - if ( function_exists('mb_strcut') ) // For international trackbacks - $excerpt = mb_strcut($excerpt, 0, 252, get_settings('blog_charset')) . '...'; - else - $excerpt = substr($excerpt, 0, 252) . '...'; - - $post_title = apply_filters('the_title', $post->post_title); - $post_title = strip_tags($post_title); - - if ($to_ping) : foreach ($to_ping as $tb_ping) : - $tb_ping = trim($tb_ping); - if ( !in_array($tb_ping, $pinged) ) { - trackback($tb_ping, $post_title, $excerpt, $post_id); - $pinged[] = $tb_ping; - } else { - $wpdb->query("UPDATE $wpdb->posts SET to_ping = TRIM(REPLACE(to_ping, '$tb_ping', '')) WHERE ID = '$post_id'"); - } - endforeach; endif; + return NULL; } -function get_pung($post_id) { // Get URIs already pung for a post - global $wpdb; - $pung = $wpdb->get_var("SELECT pinged FROM $wpdb->posts WHERE ID = $post_id"); - $pung = trim($pung); - $pung = preg_split('/\s/', $pung); - $pung = apply_filters('get_pung', $pung); - return $pung; -} +function &get_page_children($page_id, $pages) { + global $page_cache; -function get_enclosed($post_id) { // Get enclosures already enclosed for a post - global $wpdb; - $custom_fields = get_post_custom( $post_id ); - $pung = array(); - if ( !is_array( $custom_fields ) ) - return $pung; + if ( empty($pages) ) + $pages = &$page_cache; - foreach ( $custom_fields as $key => $val ) { - if ( 'enclosure' != $key || !is_array( $val ) ) - continue; - foreach( $val as $enc ) { - $enclosure = split( "\n", $enc ); - $pung[] = trim( $enclosure[ 0 ] ); + $page_list = array(); + foreach ( $pages as $page ) { + if ( $page->post_parent == $page_id ) { + $page_list[] = $page; + if ( $children = get_page_children($page->ID, $pages) ) + $page_list = array_merge($page_list, $children); } } - $pung = apply_filters('get_enclosed', $pung); - return $pung; -} - -function get_to_ping($post_id) { // Get any URIs in the todo list - global $wpdb; - $to_ping = $wpdb->get_var("SELECT to_ping FROM $wpdb->posts WHERE ID = $post_id"); - $to_ping = trim($to_ping); - $to_ping = preg_split('/\s/', $to_ping, -1, PREG_SPLIT_NO_EMPTY); - $to_ping = apply_filters('get_to_ping', $to_ping); - return $to_ping; -} - -function add_ping($post_id, $uri) { // Add a URI to those already pung - global $wpdb; - $pung = $wpdb->get_var("SELECT pinged FROM $wpdb->posts WHERE ID = $post_id"); - $pung = trim($pung); - $pung = preg_split('/\s/', $pung); - $pung[] = $uri; - $new = implode("\n", $pung); - $new = apply_filters('add_ping', $new); - return $wpdb->query("UPDATE $wpdb->posts SET pinged = '$new' WHERE ID = $post_id"); + return $page_list; } //fetches the pages returned as a FLAT list, but arranged in order of their hierarchy, i.e., child parents @@ -806,6 +995,90 @@ function get_page_hierarchy($posts, $parent = 0) { return $result; } +function get_page_uri($page_id) { + $page = get_page($page_id); + $uri = urldecode($page->post_name); + + // A page cannot be it's own parent. + if ( $page->post_parent == $page->ID ) + return $uri; + + while ($page->post_parent != 0) { + $page = get_page($page->post_parent); + $uri = urldecode($page->post_name) . "/" . $uri; + } + + return $uri; +} + +function &get_pages($args = '') { + global $wpdb; + + if ( is_array($args) ) + $r = &$args; + else + parse_str($args, $r); + + $defaults = array('child_of' => 0, 'sort_order' => 'ASC', 'sort_column' => 'post_title', + 'hierarchical' => 1, 'exclude' => '', 'include' => '', 'meta_key' => '', 'meta_value' => ''); + $r = array_merge($defaults, $r); + extract($r); + + $inclusions = ''; + if ( !empty($include) ) { + $child_of = 0; //ignore child_of, exclude, meta_key, and meta_value params if using include + $exclude = ''; + $meta_key = ''; + $meta_value = ''; + $incpages = preg_split('/[\s,]+/',$include); + if ( count($incpages) ) { + foreach ( $incpages as $incpage ) { + if (empty($inclusions)) + $inclusions = ' AND ( ID = ' . intval($incpage) . ' '; + else + $inclusions .= ' OR ID = ' . intval($incpage) . ' '; + } + } + } + if (!empty($inclusions)) + $inclusions .= ')'; + + $exclusions = ''; + if ( !empty($exclude) ) { + $expages = preg_split('/[\s,]+/',$exclude); + if ( count($expages) ) { + foreach ( $expages as $expage ) { + if (empty($exclusions)) + $exclusions = ' AND ( ID <> ' . intval($expage) . ' '; + else + $exclusions .= ' AND ID <> ' . intval($expage) . ' '; + } + } + } + if (!empty($exclusions)) + $exclusions .= ')'; + + $query = "SELECT * FROM $wpdb->posts " ; + $query .= ( empty( $meta_key ) ? "" : ", $wpdb->postmeta " ) ; + $query .= " WHERE (post_type = 'page' AND post_status = 'publish') $exclusions $inclusions " ; + $query .= ( empty( $meta_key ) | empty($meta_value) ? "" : " AND ($wpdb->posts.ID = $wpdb->postmeta.post_id AND $wpdb->postmeta.meta_key = '$meta_key' AND $wpdb->postmeta.meta_value = '$meta_value' )" ) ; + $query .= " ORDER BY " . $sort_column . " " . $sort_order ; + + $pages = $wpdb->get_results($query); + $pages = apply_filters('get_pages', $pages, $r); + + if ( empty($pages) ) + return array(); + + // Update cache. + update_page_cache($pages); + + if ( $child_of || $hierarchical ) + $pages = & get_page_children($child_of, $pages); + + return $pages; +} + function generate_page_uri_index() { global $wpdb; @@ -841,249 +1114,189 @@ function generate_page_uri_index() { } } -function get_post_status($ID = '') { - $post = get_post($ID); +// +// Attachment functions +// - if ( is_object($post) ) { - if ( ('attachment' == $post->post_type) && $post->post_parent && ($post->ID != $post->post_parent) ) - return get_post_status($post->post_parent); - else - return $post->post_status; - } +function wp_insert_attachment($object, $file = false, $post_parent = 0) { + global $wpdb, $user_ID; - return false; -} + if ( is_object($object) ) + $object = get_object_vars($object); -function get_post_type($post = false) { - global $wpdb, $posts; + // Export array as variables + extract($object); - if ( false === $post ) - $post = $posts[0]; - elseif ( (int) $post ) - $post = get_post($post, OBJECT); + // Get the basics. + $post_content = apply_filters('content_save_pre', $post_content); + $post_excerpt = apply_filters('excerpt_save_pre', $post_excerpt); + $post_title = apply_filters('title_save_pre', $post_title); + $post_category = apply_filters('category_save_pre', $post_category); + $post_name = apply_filters('name_save_pre', $post_name); + $comment_status = apply_filters('comment_status_pre', $comment_status); + $ping_status = apply_filters('ping_status_pre', $ping_status); + $post_mime_type = apply_filters('post_mime_type_pre', $post_mime_type); - if ( is_object($post) ) - return $post->post_type; + // Make sure we set a valid category + if (0 == count($post_category) || !is_array($post_category)) { + $post_category = array(get_option('default_category')); + } + $post_cat = $post_category[0]; - return false; -} + if ( empty($post_author) ) + $post_author = $user_ID; -// Takes a post ID, returns its mime type. -function get_post_mime_type($ID = '') { - $post = & get_post($ID); + $post_type = 'attachment'; + $post_status = 'inherit'; - if ( is_object($post) ) - return $post->post_mime_type; + // Are we updating or creating? + $update = false; + if ( !empty($ID) ) { + $update = true; + $post_ID = $ID; + } - return false; -} + // Create a valid post name. + if ( empty($post_name) ) + $post_name = sanitize_title($post_title); + else + $post_name = sanitize_title($post_name); -function get_attached_file($attachment_id) { - return get_post_meta($attachment_id, '_wp_attached_file', true); -} + if (empty($post_date)) + $post_date = current_time('mysql'); + if (empty($post_date_gmt)) + $post_date_gmt = current_time('mysql', 1); -function wp_mkdir_p($target) { - // from php.net/mkdir user contributed notes - if (file_exists($target)) { - if (! @ is_dir($target)) - return false; + if ( empty($comment_status) ) { + if ( $update ) + $comment_status = 'closed'; else - return true; + $comment_status = get_settings('default_comment_status'); } + if ( empty($ping_status) ) + $ping_status = get_settings('default_ping_status'); + if ( empty($post_pingback) ) + $post_pingback = get_option('default_pingback_flag'); - // Attempting to create the directory may clutter up our display. - if (@ mkdir($target)) { - $stat = @ stat(dirname($target)); - $dir_perms = $stat['mode'] & 0007777; // Get the permission bits. - @ chmod($target, $dir_perms); - return true; - } else { - if ( is_dir(dirname($target)) ) - return false; - } + if ( isset($to_ping) ) + $to_ping = preg_replace('|\s+|', "\n", $to_ping); + else + $to_ping = ''; - // If the above failed, attempt to create the parent node, then try again. - if (wp_mkdir_p(dirname($target))) - return wp_mkdir_p($target); + if ( isset($post_parent) ) + $post_parent = (int) $post_parent; + else + $post_parent = 0; - return false; -} + if ( isset($menu_order) ) + $menu_order = (int) $menu_order; + else + $menu_order = 0; -// Returns an array containing the current upload directory's path and url, or an error message. -function wp_upload_dir() { - $siteurl = get_settings('siteurl'); - //prepend ABSPATH to $dir and $siteurl to $url if they're not already there - $path = str_replace(ABSPATH, '', trim(get_settings('upload_path'))); - $dir = ABSPATH . $path; - $url = trailingslashit($siteurl) . $path; + if ( !isset($post_password) ) + $post_password = ''; - if ( $dir == ABSPATH ) { //the option was empty - $dir = ABSPATH . 'wp-content/uploads'; - } + if ( isset($to_ping) ) + $to_ping = preg_replace('|\s+|', "\n", $to_ping); + else + $to_ping = ''; - if ( defined('UPLOADS') ) { - $dir = ABSPATH . UPLOADS; - $url = trailingslashit($siteurl) . UPLOADS; - } + if ( ! isset($pinged) ) + $pinged = ''; - if ( get_settings('uploads_use_yearmonth_folders')) { - // Generate the yearly and monthly dirs - $time = current_time( 'mysql' ); - $y = substr( $time, 0, 4 ); - $m = substr( $time, 5, 2 ); - $dir = $dir . "/$y/$m"; - $url = $url . "/$y/$m"; + if ($update) { + $wpdb->query( + "UPDATE $wpdb->posts SET + post_author = '$post_author', + post_date = '$post_date', + post_date_gmt = '$post_date_gmt', + post_content = '$post_content', + post_content_filtered = '$post_content_filtered', + post_title = '$post_title', + post_excerpt = '$post_excerpt', + post_status = '$post_status', + post_type = '$post_type', + comment_status = '$comment_status', + ping_status = '$ping_status', + post_password = '$post_password', + post_name = '$post_name', + to_ping = '$to_ping', + pinged = '$pinged', + post_modified = '".current_time('mysql')."', + post_modified_gmt = '".current_time('mysql',1)."', + post_parent = '$post_parent', + menu_order = '$menu_order', + post_mime_type = '$post_mime_type', + guid = '$guid' + WHERE ID = $post_ID"); + } else { + $wpdb->query( + "INSERT INTO $wpdb->posts + (post_author, post_date, post_date_gmt, post_content, post_content_filtered, post_title, post_excerpt, post_status, post_type, comment_status, ping_status, post_password, post_name, to_ping, pinged, post_modified, post_modified_gmt, post_parent, menu_order, post_mime_type, guid) + VALUES + ('$post_author', '$post_date', '$post_date_gmt', '$post_content', '$post_content_filtered', '$post_title', '$post_excerpt', '$post_status', '$post_type', '$comment_status', '$ping_status', '$post_password', '$post_name', '$to_ping', '$pinged', '$post_date', '$post_date_gmt', '$post_parent', '$menu_order', '$post_mime_type', '$guid')"); + $post_ID = $wpdb->insert_id; } - // Make sure we have an uploads dir - if ( ! wp_mkdir_p( $dir ) ) { - $message = sprintf(__('Unable to create directory %s. Is its parent directory writable by the server?'), $dir); - return array('error' => $message); + if ( empty($post_name) ) { + $post_name = sanitize_title($post_title, $post_ID); + $wpdb->query( "UPDATE $wpdb->posts SET post_name = '$post_name' WHERE ID = '$post_ID'" ); } - $uploads = array('path' => $dir, 'url' => $url, 'error' => false); - return apply_filters('upload_dir', $uploads); -} - -function wp_upload_bits($name, $type, $bits) { - if ( empty($name) ) - return array('error' => "Empty filename"); + wp_set_post_categories($post_ID, $post_category); - $upload = wp_upload_dir(); + if ( $file ) + add_post_meta($post_ID, '_wp_attached_file', $file ); - if ( $upload['error'] !== false ) - return $upload; + clean_post_cache($post_ID); - $number = ''; - $filename = $name; - $path_parts = pathinfo($filename); - $ext = $path_parts['extension']; - if ( empty($ext) ) - $ext = ''; - else - $ext = ".$ext"; - while ( file_exists($upload['path'] . "/$filename") ) { - if ( '' == "$number$ext" ) - $filename = $filename . ++$number . $ext; - else - $filename = str_replace("$number$ext", ++$number . $ext, $filename); + if ( $update) { + do_action('edit_attachment', $post_ID); + } else { + do_action('add_attachment', $post_ID); } - $new_file = $upload['path'] . "/$filename"; - if ( ! wp_mkdir_p( dirname($new_file) ) ) { - $message = sprintf(__('Unable to create directory %s. Is its parent directory writable by the server?'), dirname($new_file)); - return array('error' => $message); - } + return $post_ID; +} - $ifp = @ fopen($new_file, 'wb'); - if ( ! $ifp ) - return array('error' => "Could not write file $new_file."); +function wp_delete_attachment($postid) { + global $wpdb; + $postid = (int) $postid; - $success = @ fwrite($ifp, $bits); - fclose($ifp); - // Set correct file permissions - $stat = @ stat(dirname($new_file)); - $perms = $stat['mode'] & 0007777; - $perms = $perms & 0000666; - @ chmod($new_file, $perms); + if ( !$post = $wpdb->get_row("SELECT * FROM $wpdb->posts WHERE ID = '$postid'") ) + return $post; - // Compute the URL - $url = $upload['url'] . "/$filename"; + if ( 'attachment' != $post->post_type ) + return false; - return array('file' => $new_file, 'url' => $url, 'error' => false); -} + $meta = get_post_meta($postid, '_wp_attachment_metadata', true); + $file = get_post_meta($postid, '_wp_attached_file', true); -function do_all_pings() { - global $wpdb; + $wpdb->query("DELETE FROM $wpdb->posts WHERE ID = '$postid'"); - // Do pingbacks - while ($ping = $wpdb->get_row("SELECT * FROM {$wpdb->posts}, {$wpdb->postmeta} WHERE {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id AND {$wpdb->postmeta}.meta_key = '_pingme' LIMIT 1")) { - $wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE post_id = {$ping->ID} AND meta_key = '_pingme';"); - pingback($ping->post_content, $ping->ID); - } - - // Do Enclosures - while ($enclosure = $wpdb->get_row("SELECT * FROM {$wpdb->posts}, {$wpdb->postmeta} WHERE {$wpdb->posts}.ID = {$wpdb->postmeta}.post_id AND {$wpdb->postmeta}.meta_key = '_encloseme' LIMIT 1")) { - $wpdb->query("DELETE FROM {$wpdb->postmeta} WHERE post_id = {$enclosure->ID} AND meta_key = '_encloseme';"); - do_enclose($enclosure->post_content, $enclosure->ID); - } + $wpdb->query("DELETE FROM $wpdb->comments WHERE comment_post_ID = '$postid'"); + + $wpdb->query("DELETE FROM $wpdb->post2cat WHERE post_id = '$postid'"); + + $wpdb->query("DELETE FROM $wpdb->postmeta WHERE post_id = '$postid'"); - // Do Trackbacks - $trackbacks = $wpdb->get_results("SELECT ID FROM $wpdb->posts WHERE CHAR_LENGTH(TRIM(to_ping)) > 7 AND post_status = 'publish'"); - if ( is_array($trackbacks) ) { - foreach ( $trackbacks as $trackback ) { - do_trackbacks($trackback->ID); + if ( ! empty($meta['thumb']) ) { + // Don't delete the thumb if another attachment uses it + if (! $wpdb->get_row("SELECT meta_id FROM $wpdb->postmeta WHERE meta_key = '_wp_attachment_metadata' AND meta_value LIKE '%".$wpdb->escape($meta['thumb'])."%' AND post_id <> $postid")) { + $thumbfile = str_replace(basename($file), $meta['thumb'], $file); + $thumbfile = apply_filters('wp_delete_file', $thumbfile); + @ unlink($thumbfile); } } - //Do Update Services/Generic Pings - generic_ping(); -} + $file = apply_filters('wp_delete_file', $file); -/** - * Places a textarea according to the current user's preferences, filled with $content. - * Also places a script block that enables tabbing between Title and Content. - * - * @param string Editor contents - * @param string (optional) Previous form field's ID (for tabbing support) - */ -function the_editor($content, $id = 'content', $prev_id = 'title') { - $rows = get_settings('default_post_edit_rows'); - if (($rows < 3) || ($rows > 100)) - $rows = 12; - - $rows = "rows='$rows'"; - - the_quicktags(); - - if ( user_can_richedit() ) - add_filter('the_editor_content', 'wp_richedit_pre'); - - $the_editor = apply_filters('the_editor', "<div><textarea class='mceEditor' $rows cols='40' name='$id' tabindex='2' id='$id'>%s</textarea></div>\n"); - $the_editor_content = apply_filters('the_editor_content', $content); - - printf($the_editor, $the_editor_content); - - ?> - <script type="text/javascript"> - //<!-- - edCanvas = document.getElementById('<?php echo $id; ?>'); - <?php if ( user_can_richedit() ) : ?> - // This code is meant to allow tabbing from Title to Post (TinyMCE). - if ( tinyMCE.isMSIE ) - document.getElementById('<?php echo $prev_id; ?>').onkeydown = function (e) - { - e = e ? e : window.event; - if (e.keyCode == 9 && !e.shiftKey && !e.controlKey && !e.altKey) { - var i = tinyMCE.selectedInstance; - if(typeof i == 'undefined') - return true; - tinyMCE.execCommand("mceStartTyping"); - this.blur(); - i.contentWindow.focus(); - e.returnValue = false; - return false; - } - } - else - document.getElementById('<?php echo $prev_id; ?>').onkeypress = function (e) - { - e = e ? e : window.event; - if (e.keyCode == 9 && !e.shiftKey && !e.controlKey && !e.altKey) { - var i = tinyMCE.selectedInstance; - if(typeof i == 'undefined') - return true; - tinyMCE.execCommand("mceStartTyping"); - this.blur(); - i.contentWindow.focus(); - e.returnValue = false; - return false; - } - } - <?php endif; ?> - //--> - </script> - <?php + if ( ! empty($file) ) + @ unlink($file); + + do_action('delete_attachment', $postid); + + return $post; } ?> diff --git a/wp-inst/wp-includes/query.php b/wp-inst/wp-includes/query.php index 510a7ab..305c7e1 100644 --- a/wp-inst/wp-includes/query.php +++ b/wp-inst/wp-includes/query.php @@ -1037,4 +1037,42 @@ class WP_Query { }
}
+//
+// Private helper functions
+//
+
+// Setup global post data.
+function setup_postdata($post) {
+ global $id, $postdata, $authordata, $day, $page, $pages, $multipage, $more, $numpages, $wp_query;
+ global $pagenow;
+
+ $id = $post->ID;
+
+ $authordata = get_userdata($post->post_author);
+
+ $day = mysql2date('d.m.y', $post->post_date);
+ $currentmonth = mysql2date('m', $post->post_date);
+ $numpages = 1;
+ $page = get_query_var('page');
+ if ( !$page )
+ $page = 1;
+ if ( is_single() || is_page() )
+ $more = 1;
+ $content = $post->post_content;
+ if ( preg_match('/<!--nextpage-->/', $content) ) {
+ if ( $page > 1 )
+ $more = 1;
+ $multipage = 1;
+ $content = str_replace("\n<!--nextpage-->\n", '<!--nextpage-->', $content);
+ $content = str_replace("\n<!--nextpage-->", '<!--nextpage-->', $content);
+ $content = str_replace("<!--nextpage-->\n", '<!--nextpage-->', $content);
+ $pages = explode('<!--nextpage-->', $content);
+ $numpages = count($pages);
+ } else {
+ $pages[0] = $post->post_content;
+ $multipage = 0;
+ }
+ return true;
+}
+
?>
diff --git a/wp-inst/wp-includes/registration-functions.php b/wp-inst/wp-includes/registration.php index a0860bd..f2a00e9 100644 --- a/wp-inst/wp-includes/registration-functions.php +++ b/wp-inst/wp-includes/registration.php @@ -102,7 +102,7 @@ function wp_insert_user($userdata) { update_usermeta( $user_id, 'aim', $aim ); update_usermeta( $user_id, 'yim', $yim ); - if ($update && !empty($role)) { + if ( $update && isset($role) ) { $user = new WP_User($user_id); $user->set_role($role); } diff --git a/wp-inst/wp-includes/rewrite.php b/wp-inst/wp-includes/rewrite.php index 4a6c631..178ee07 100644 --- a/wp-inst/wp-includes/rewrite.php +++ b/wp-inst/wp-includes/rewrite.php @@ -367,7 +367,7 @@ class WP_Rewrite { }
if (empty($this->category_base))
- $this->category_structure = $this->front . 'tag/';
+ $this->category_structure = $this->front . 'category/';
else
$this->category_structure = $this->category_base . '/';
diff --git a/wp-inst/wp-includes/rss-functions.php b/wp-inst/wp-includes/rss.php index 94aa1d7..2f99d3f 100644 --- a/wp-inst/wp-includes/rss-functions.php +++ b/wp-inst/wp-includes/rss.php @@ -389,13 +389,6 @@ function fetch_rss ($url) { return false; } - $parts = parse_url($url); - if ( strstr($parts['host'], 'wordpress.com') && !preg_match('!/(feed|atom|rss|rss2)/?$|/feed/(feed|atom|rss|rss2)/?$|\.xml$!i', $parts['path']) ) - $url = trim($url, '/') . '/feed/'; - - if ( $rss = wp_cache_get($url, 'rss') ) - return $rss; - // if cache is disabled if ( !MAGPIE_CACHE_ON ) { // fetch file, and parse it @@ -476,7 +469,6 @@ function fetch_rss ($url) { } // add object to cache $cache->set( $url, $rss ); - wp_cache_set($url, $rss, 'rss', 3600); return $rss; } } @@ -491,12 +483,10 @@ function fetch_rss ($url) { else { $errormsg .= "(HTTP Response: " . $resp->response_code .')'; } - wp_cache_set($url, $errormsg, 'rss', 3600); } } else { $errormsg = "Unable to retrieve RSS file for unknown reasons."; - wp_cache_set($url, $errormsg, 'rss', 3600); } // else fetch failed @@ -506,7 +496,6 @@ function fetch_rss ($url) { if ( MAGPIE_DEBUG ) { debug("Returning STALE object for $url"); } - wp_cache_set($url, $rss, 'rss', 7200); return $rss; } @@ -521,7 +510,6 @@ function fetch_rss ($url) { function _fetch_remote_file ($url, $headers = "" ) { // Snoopy is an HTTP client in PHP $client = new Snoopy(); - $client->referer = 'http'.($_SERVER['HTTPS']?'s':'').'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']; $client->agent = MAGPIE_USER_AGENT; $client->read_timeout = MAGPIE_FETCH_TIME_OUT; $client->use_gzip = MAGPIE_USE_GZIP; @@ -677,15 +665,20 @@ class RSSCache { \*=======================================================================*/ function set ($url, $rss) { global $wpdb; - $file = $this->file_name( $url ); + $cache_option = 'rss_' . $this->file_name( $url ); + $cache_timestamp = 'rss_' . $this->file_name( $url ) . '_ts'; + + if ( !$wpdb->get_var("SELECT option_name FROM $wpdb->options WHERE option_name = '$cache_option'") ) + add_option($cache_option, '', '', 'no'); + if ( !$wpdb->get_var("SELECT option_name FROM $wpdb->options WHERE option_name = '$cache_timestamp'") ) + add_option($cache_timestamp, '', '', 'no'); - $f = fopen( $file, 'w' ); - fwrite( $f, serialize( $rss ) ); - fclose( $f ); + update_option($cache_option, $rss); + update_option($cache_timestamp, time() ); - return true; + return $cache_option; } - + /*=======================================================================*\ Function: get Purpose: fetch an item from the cache @@ -694,17 +687,17 @@ class RSSCache { \*=======================================================================*/ function get ($url) { $this->ERROR = ""; - $file = $this->file_name( $url ); - - if ( ! $contents = file_get_contents( $file ) ) { + $cache_option = 'rss_' . $this->file_name( $url ); + + if ( ! get_option( $cache_option ) ) { $this->debug( "Cache doesn't contain: $url (cache option: $cache_option)" ); return 0; } - - $rss = unserialize( $contents ); - + + $rss = get_option( $cache_option ); + return $rss; } @@ -717,23 +710,26 @@ class RSSCache { \*=======================================================================*/ function check_cache ( $url ) { $this->ERROR = ""; - $file = $this->file_name( $url ); + $cache_option = $this->file_name( $url ); + $cache_timestamp = 'rss_' . $this->file_name( $url ) . '_ts'; - if ( !file_exists( $file ) ) - return 'MISS'; - - if ( $mtime = filemtime($file) ) { + if ( $mtime = get_option($cache_timestamp) ) { // find how long ago the file was added to the cache // and whether that is longer then MAX_AGE $age = time() - $mtime; if ( $this->MAX_AGE > $age ) { // object exists and is current return 'HIT'; - } else { + } + else { // object exists but is old return 'STALE'; } } + else { + // object does not exist + return 'MISS'; + } } /*=======================================================================*\ @@ -757,7 +753,7 @@ class RSSCache { Output: a file name \*=======================================================================*/ function file_name ($url) { - return '/home/wpcom/cache/rss/' . md5( $url ); + return md5( $url ); } /*=======================================================================*\ diff --git a/wp-inst/wp-includes/user.php b/wp-inst/wp-includes/user.php new file mode 100644 index 0000000..bdf537d --- /dev/null +++ b/wp-inst/wp-includes/user.php @@ -0,0 +1,169 @@ +<?php + +function get_profile($field, $user = false) { + global $wpdb; + if ( !$user ) + $user = $wpdb->escape($_COOKIE[USER_COOKIE]); + return $wpdb->get_var("SELECT $field FROM $wpdb->users WHERE user_login = '$user'"); +} + +function get_usernumposts($userid) { + global $wpdb; + return $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = '$userid' AND post_type = 'post' AND post_status = 'publish'"); +} + +// TODO: xmlrpc only. Maybe move to xmlrpc.php. +function user_pass_ok($user_login,$user_pass) { + global $cache_userdata; + if ( empty($cache_userdata[$user_login]) ) { + $userdata = get_userdatabylogin($user_login); + } else { + $userdata = $cache_userdata[$user_login]; + } + return (md5($user_pass) == $userdata->user_pass); +} + +// +// User option functions +// + +function get_user_option( $option, $user = 0 ) { + global $wpdb; + + if ( empty($user) ) + $user = wp_get_current_user(); + else + $user = get_userdata($user); + + if ( isset( $user->{$wpdb->prefix . $option} ) ) // Blog specific + return $user->{$wpdb->prefix . $option}; + elseif ( isset( $user->{$option} ) ) // User specific and cross-blog + return $user->{$option}; + else // Blog global + return get_option( $option ); +} + +function update_user_option( $user_id, $option_name, $newvalue, $global = false ) { + global $wpdb; + if ( !$global ) + $option_name = $wpdb->prefix . $option_name; + return update_usermeta( $user_id, $option_name, $newvalue ); +} + +// +// User meta functions +// + +function delete_usermeta( $user_id, $meta_key, $meta_value = '' ) { + global $wpdb; + if ( !is_numeric( $user_id ) ) + return false; + $meta_key = preg_replace('|[^a-z0-9_]|i', '', $meta_key); + + if ( is_array($meta_value) || is_object($meta_value) ) + $meta_value = serialize($meta_value); + $meta_value = trim( $meta_value ); + + if ( ! empty($meta_value) ) + $wpdb->query("DELETE FROM $wpdb->usermeta WHERE user_id = '$user_id' AND meta_key = '$meta_key' AND meta_value = '$meta_value'"); + else + $wpdb->query("DELETE FROM $wpdb->usermeta WHERE user_id = '$user_id' AND meta_key = '$meta_key'"); + + $user = get_userdata($user_id); + wp_cache_delete($user_id, 'users'); + wp_cache_delete($user->user_login, 'userlogins'); + + return true; +} + +function get_usermeta( $user_id, $meta_key = '') { + global $wpdb; + $user_id = (int) $user_id; + + if ( !empty($meta_key) ) { + $meta_key = preg_replace('|a-z0-9_|i', '', $meta_key); + $metas = $wpdb->get_results("SELECT meta_key, meta_value FROM $wpdb->usermeta WHERE user_id = '$user_id' AND meta_key = '$meta_key'"); + } else { + $metas = $wpdb->get_results("SELECT meta_key, meta_value FROM $wpdb->usermeta WHERE user_id = '$user_id'"); + } + + if ( empty($metas) ) { + if ( empty($meta_key) ) + return array(); + else + return ''; + } + + foreach ($metas as $index => $meta) { + @ $value = unserialize($meta->meta_value); + if ( $value === FALSE ) + $value = $meta->meta_value; + + $values[] = $value; + } + + if ( count($values) == 1 ) + return $values[0]; + else + return $values; +} + +function update_usermeta( $user_id, $meta_key, $meta_value ) { + global $wpdb; + if ( !is_numeric( $user_id ) ) + return false; + $meta_key = preg_replace('|[^a-z0-9_]|i', '', $meta_key); + + if ( is_array($meta_value) || is_object($meta_value) ) + $meta_value = serialize($meta_value); + $meta_value = trim( $meta_value ); + + if (empty($meta_value)) { + return delete_usermeta($user_id, $meta_key); + } + + $cur = $wpdb->get_row("SELECT * FROM $wpdb->usermeta WHERE user_id = '$user_id' AND meta_key = '$meta_key'"); + if ( !$cur ) { + $wpdb->query("INSERT INTO $wpdb->usermeta ( user_id, meta_key, meta_value ) + VALUES + ( '$user_id', '$meta_key', '$meta_value' )"); + } else if ( $cur->meta_value != $meta_value ) { + $wpdb->query("UPDATE $wpdb->usermeta SET meta_value = '$meta_value' WHERE user_id = '$user_id' AND meta_key = '$meta_key'"); + } else { + return false; + } + + $user = get_userdata($user_id); + wp_cache_delete($user_id, 'users'); + wp_cache_delete($user->user_login, 'userlogins'); + + return true; +} + +// +// Private helper functions +// + +// Setup global user vars. Used by set_current_user() for back compat. +function setup_userdata($user_id = '') { + global $user_login, $userdata, $user_level, $user_ID, $user_email, $user_url, $user_pass_md5, $user_identity; + + if ( '' == $user_id ) + $user = wp_get_current_user(); + else + $user = new WP_User($user_id); + + if ( 0 == $user->ID ) + return; + + $userdata = $user->data; + $user_login = $user->user_login; + $user_level = $user->user_level; + $user_ID = $user->ID; + $user_email = $user->user_email; + $user_url = $user->user_url; + $user_pass_md5 = md5($user->user_pass); + $user_identity = $user->display_name; +} + +?>
\ No newline at end of file diff --git a/wp-inst/wp-includes/wp-db.php b/wp-inst/wp-includes/wp-db.php index 9faa97e..142a3ec 100644 --- a/wp-inst/wp-includes/wp-db.php +++ b/wp-inst/wp-includes/wp-db.php @@ -28,6 +28,7 @@ class wpdb { var $post2cat; var $comments; var $links; + var $link2cat; var $linkcategories; var $options; var $optiontypes; @@ -42,7 +43,7 @@ class wpdb { function wpdb($dbuser, $dbpassword, $dbname, $dbhost) { if( defined( "WP_USE_MULTIPLE_DB" ) && CONSTANT( "WP_USE_MULTIPLE_DB" ) == true ) { - $this->db_connect( $query ); + $this->db_connect(); return true; } diff --git a/wp-inst/wp-includes/wpmu-functions.php b/wp-inst/wp-includes/wpmu-functions.php index 5b7c73f..f96a96e 100644 --- a/wp-inst/wp-includes/wpmu-functions.php +++ b/wp-inst/wp-includes/wpmu-functions.php @@ -166,7 +166,7 @@ function get_user_details( $username ) { return $wpdb->get_row( "SELECT * FROM $wpdb->users WHERE user_login = '$username'" ); } -function get_blog_details( $id ) { +function get_blog_details( $id, $all = true ) { global $wpdb, $wpmuBaseTablePrefix; $details = wp_cache_get( $id, 'blog-details' ); @@ -179,13 +179,16 @@ function get_blog_details( $id ) { if ( !$details ) return false; - $details->blogname = get_blog_option($id, 'blogname'); - $details->siteurl = get_blog_option($id, 'siteurl'); + if( $all == true ) { + $details->blogname = get_blog_option($id, 'blogname'); + $details->siteurl = get_blog_option($id, 'siteurl'); + $details->post_count = get_blog_option($id, 'post_count'); - wp_cache_set( $id, serialize( $details ), 'blog-details' ); + wp_cache_set( $id, serialize( $details ), 'blog-details' ); - $key = md5( $details->domain . $details->path ); - wp_cache_set( $key, serialize( $details ), 'blog-lookup' ); + $key = md5( $details->domain . $details->path ); + wp_cache_set( $key, serialize( $details ), 'blog-lookup' ); + } return $details; } @@ -890,8 +893,8 @@ function wpmu_validate_user_signup($user_name, $user_email) { $errors->add('user_name', __("Sorry, that username already exists!")); // Check if the email address has been used already. - //if ( email_exists($user_email) ) - // $errors->add('user_email', __("Sorry, that email address is already used!")); + if ( email_exists($user_email) ) + $errors->add('user_email', __("Sorry, that email address is already used!")); // Has someone already signed up for this username? // TODO: Check email too? @@ -1093,7 +1096,11 @@ function generate_random_password() { function wpmu_create_user( $user_name, $password, $email) { if ( username_exists($user_name) ) return false; - // Check email too? + + // Check if the email address has been used already. + if ( email_exists($email) ) + return false; + $user_id = wp_create_user( $user_name, $password, $email ); $user = new WP_User($user_id); diff --git a/wp-inst/wp-register.php b/wp-inst/wp-register.php index 1a4dc78..7c8adb3 100644 --- a/wp-inst/wp-register.php +++ b/wp-inst/wp-register.php @@ -1,6 +1,6 @@ <?php require('./wp-config.php'); -require_once( ABSPATH . WPINC . '/registration-functions.php'); +require_once( ABSPATH . WPINC . '/registration.php'); $action = $_REQUEST['action']; if ( !get_settings('users_can_register') ) diff --git a/wp-inst/wp-rss2.php b/wp-inst/wp-rss2.php index 75c1d59..4316ceb 100644 --- a/wp-inst/wp-rss2.php +++ b/wp-inst/wp-rss2.php @@ -47,7 +47,7 @@ $more = 1; <content:encoded><![CDATA[<?php the_excerpt_rss() ?>]]></content:encoded> <?php endif; ?> <?php endif; ?> - <wfw:commentRSS><?php echo comments_rss(); ?></wfw:commentRSS> + <wfw:commentRss><?php echo comments_rss(); ?></wfw:commentRss> <?php rss_enclosure(); ?> <?php do_action('rss2_item'); ?> </item> diff --git a/wp-inst/wp-settings.php b/wp-inst/wp-settings.php index edf5803..5f34e1b 100644 --- a/wp-inst/wp-settings.php +++ b/wp-inst/wp-settings.php @@ -145,22 +145,23 @@ if ( !$db_check && (!strstr($_SERVER['PHP_SELF'], 'install.php') && !defined('WP } $wpdb->show_errors(); -require (ABSPATH . WPINC . '/functions-formatting.php'); -require (ABSPATH . WPINC . '/functions-post.php'); +require (ABSPATH . WPINC . '/formatting.php'); require (ABSPATH . WPINC . '/capabilities.php'); require (ABSPATH . WPINC . '/classes.php'); require (ABSPATH . WPINC . '/query.php'); require (ABSPATH . WPINC . '/theme.php'); -require (ABSPATH . WPINC . '/template-functions-general.php'); -require (ABSPATH . WPINC . '/template-functions-links.php'); -require (ABSPATH . WPINC . '/template-functions-author.php'); -require (ABSPATH . WPINC . '/template-functions-post.php'); +require (ABSPATH . WPINC . '/user.php'); +require (ABSPATH . WPINC . '/general-template.php'); +require (ABSPATH . WPINC . '/link-template.php'); +require (ABSPATH . WPINC . '/author-template.php'); +require (ABSPATH . WPINC . '/post.php'); +require (ABSPATH . WPINC . '/post-template.php'); require (ABSPATH . WPINC . '/category.php'); require (ABSPATH . WPINC . '/category-template.php'); require (ABSPATH . WPINC . '/comment.php'); require (ABSPATH . WPINC . '/comment-template.php'); require (ABSPATH . WPINC . '/rewrite.php'); -require (ABSPATH . WPINC . '/feed-functions.php'); +require (ABSPATH . WPINC . '/feed.php'); require (ABSPATH . WPINC . '/bookmark.php'); require (ABSPATH . WPINC . '/bookmark-template.php'); require (ABSPATH . WPINC . '/kses.php'); @@ -236,7 +237,7 @@ if ( get_settings('active_plugins') ) { } } -require (ABSPATH . WPINC . '/pluggable-functions.php'); +require (ABSPATH . WPINC . '/pluggable.php'); if ( defined('WP_CACHE') && function_exists('wp_cache_postload') ) wp_cache_postload(); diff --git a/wp-inst/wp-signup.php b/wp-inst/wp-signup.php index 4f4017f..6261a5f 100644 --- a/wp-inst/wp-signup.php +++ b/wp-inst/wp-signup.php @@ -19,7 +19,7 @@ require ('wp-config.php'); //graceful_fail('Signups are disabled for a few minutes. Sorry! Please try again soon.');
-require_once( ABSPATH . WPINC . '/registration-functions.php');
+require_once( ABSPATH . WPINC . '/registration.php');
do_action("signup_header");
|