Make WordPress Core

Changes from tags/2.1.3 at r5468 to tags/2.2 at r5480


Ignore:
Location:
tags
Files:
29 added
8 deleted
163 edited

Legend:

Unmodified
Added
Removed
  • tags/2.2/readme.html

    r5468 r5480  
    99<h1 id="logo" style="text-align: center">
    1010    <img alt="WordPress" src="wp-admin/images/wordpress-logo.png" />
    11     <br /> Version 2.1
     11    <br /> Version 2.2
    1212</h1>
    1313<p style="text-align: center">Semantic Personal Publishing Platform</p>
     
    3030<h1>Upgrading</h1>
    3131<p>Before you upgrade anything, make sure you have backup copies of any files you may have modified such as <code>index.php</code>.</p>
    32 <h2>Upgrading from any previous WordPress to 2.1:</h2>
     32<h2>Upgrading from any previous WordPress to 2.2:</h2>
    3333<ol>
    3434    <li>Delete your old WP files, saving ones you've modified.</li>
     
    5252        <dd>If you've looked everywhere and still can't find an answer, the support forums are very active and have a large community ready to help. To help them help you be sure to use a descriptive thread title and describe your question in as much detail as possible.</dd>
    5353    <dt><a href="http://codex.wordpress.org/IRC">WordPress IRC Channel</a></dt>
    54         <dd>Finally, there is an online chat channel that is used for discussion among people who use WordPress and occasionally support topics. The above wiki page should point you in the right direction. (irc.freenode.net #wordpress)</dd>
     54        <dd>Finally, there is an online chat channel that is used for discussion among people who use WordPress and occasionally support topics. The above wiki page should point you in the right direction. (<a href="irc://irc.freenode.net/wordpress">irc.freenode.net #wordpress</a>)</dd>
    5555</dl>
    5656
    5757<h1>System Recommendations</h1>
    5858<ul>
    59     <li>PHP version <strong>4.1</strong> or higher.</li>
     59    <li>PHP version <strong>4.2</strong> or higher.</li>
    6060    <li>MySQL version <strong>4.0</strong> or higher.</li>
    6161    <li>... and a link to <a href="http://wordpress.org/">http://wordpress.org</a> on your site.</li>
     
    6464
    6565<h1>Upgrading from another system</h1>
    66 <p>WordPress can <a href="http://codex.wordpress.org/Importing_from_other_blogging_software">import from a number of systems</a>. First you need to get WordPress installed and working as described above.</p>
     66<p>WordPress can <a href="http://codex.wordpress.org/Importing_Content">import from a number of systems</a>. First you need to get WordPress installed and working as described above.</p>
    6767
    68 <h1>XML-RPC Interface</h1>
    69 <p>You can now post to your WordPress blog with tools like <a href="http://ecto.kung-foo.tv/">Ecto</a>, <a href="http://blogbuddy.sourceforge.net">BlogBuddy</a>, <a href="http://bloggar.com/">Bloggar</a>, <a href="http://www.ubique.ch/wapblogger/">WapBlogger</a> (post from your Wap cellphone!), <a href="http://radio.userland.com">Radio Userland</a> (which means you can use Radio's email-to-blog feature), <a href="http://www.zempt.com/">Zempt</a>, <a href="http://www.newzcrawler.com/">NewzCrawler</a>, and other tools that support the Blogging APIs! :) You can read more about <a href="http://codex.wordpress.org/XML-RPC_Support">XML-RPC support on the Codex</a>.</p>
     68<h1>XML-RPC and Atom Interface</h1>
     69<p>You can now post to your WordPress blog with tools like <a href="http://windowslivewriter.spaces.live.com/">Windows Live Writer</a>, <a href="http://ecto.kung-foo.tv/">Ecto</a>, <a href="http://bloggar.com/">Bloggar</a>, <a href="http://radio.userland.com">Radio Userland</a> (which means you can use Radio's email-to-blog feature), <a href="http://www.newzcrawler.com/">NewzCrawler</a>, and other tools that support the Blogging APIs! :) You can read more about <a href="http://codex.wordpress.org/XML-RPC_Support">XML-RPC support on the Codex</a>.</p>
    7070
    7171<h1>Post via Email</h1>
  • tags/2.2/wp-admin/admin-ajax.php

    r5468 r5480  
    152152    $x->send();
    153153    break;
     154case 'add-comment' :
     155    if ( !current_user_can( 'edit_post', $id ) )
     156        die('-1');
     157    $search = isset($_POST['s']) ? $_POST['s'] : false;
     158    $start = isset($_POST['page']) ? intval($_POST['page']) * 25 : 25;
     159
     160    list($comments, $total) = _wp_get_comment_list( $search, $start, 1 );
     161
     162    if ( !$comments )
     163        die('1');
     164    $x = new WP_Ajax_Response();
     165    foreach ( (array) $comments as $comment ) {
     166        get_comment( $comment );
     167        ob_start();
     168            _wp_comment_list_item( $comment->comment_ID );
     169            $comment_list_item = ob_get_contents();
     170        ob_end_clean();
     171        $x->add( array(
     172            'what' => 'comment',
     173            'id' => $comment->comment_ID,
     174            'data' => $comment_list_item
     175        ) );
     176    }
     177    $x->send();
     178    break;
    154179case 'add-meta' :
    155180    if ( !current_user_can( 'edit_post', $id ) )
     
    227252    $_POST['post_category'] = explode(",", $_POST['catslist']);
    228253    if($_POST['post_type'] == 'page' || empty($_POST['post_category']))
    229         unset($_POST['post_category']); 
    230    
     254        unset($_POST['post_category']);
     255
    231256    if($_POST['post_ID'] < 0) {
    232257        $_POST['temp_ID'] = $_POST['post_ID'];
  • tags/2.2/wp-admin/admin-db.php

    r5468 r5480  
    149149    clean_category_cache($cat_ID);
    150150
     151    if ($update)
     152        do_action('edited_category', $cat_ID);
     153    else
     154        do_action('created_category', $cat_ID);
     155   
    151156    return $cat_ID;
    152157}
     
    416421    $wpdb->query("DELETE FROM $wpdb->link2cat WHERE link_id = '$link_id'");
    417422    return $wpdb->query("DELETE FROM $wpdb->links WHERE link_id = '$link_id'");
     423   
     424    do_action('deleted_link', $link_id);
    418425}
    419426
  • tags/2.2/wp-admin/admin-functions.php

    r5468 r5480  
    2323
    2424    // Check for autosave collisions
     25    $temp_id = false;
    2526    if ( isset($_POST['temp_ID']) ) {
    2627        $temp_id = (int) $_POST['temp_ID'];
     
    3435            $_POST['post_ID'] = $draft_ids[$temp_id];
    3536            unset($_POST['temp_ID']);
    36             relocate_children( $temp_id, $_POST['post_ID'] );
    3737            update_user_option( $user_ID, 'autosave_draft_ids', $draft_ids );
    3838            return edit_post();
     
    113113
    114114    // Reunite any orphaned attachments with their parent
     115    if ( !$draft_ids = get_user_option( 'autosave_draft_ids' ) )
     116        $draft_ids = array();
     117    if ( $draft_temp_id = (int) array_search( $post_ID, $draft_ids ) )
     118        relocate_children( $draft_temp_id, $post_ID );
     119    if ( $temp_id && $temp_id != $draft_temp_id )
     120        relocate_children( $temp_id, $post_ID );
     121
    115122    // Update autosave collision detection
    116123    if ( $temp_id ) {
    117         relocate_children( $temp_id, $post_ID );
    118124        $draft_ids[$temp_id] = $post_ID;
    119125        update_user_option( $user_ID, 'autosave_draft_ids', $draft_ids );
     
    280286    add_meta( $post_ID );
    281287
    282     wp_update_post( $_POST);
     288    wp_update_post( $_POST );
     289
     290    // Reunite any orphaned attachments with their parent
     291    if ( !$draft_ids = get_user_option( 'autosave_draft_ids' ) )
     292        $draft_ids = array();
     293    if ( $draft_temp_id = (int) array_search( $post_ID, $draft_ids ) )
     294        relocate_children( $draft_temp_id, $post_ID );
    283295
    284296    // Now that we have an ID we can fix any attachment anchor hrefs
     
    670682            // No selected categories, strange
    671683            $checked_categories[] = $default;
    672         }   
     684        }
    673685    } else {
    674686        $checked_categories[] = $default;
     
    694706function write_nested_categories( $categories ) {
    695707    foreach ( $categories as $category ) {
    696         echo '<li id="category-', $category['cat_ID'], '"><label for="in-category-', $category['cat_ID'], '" class="selectit"><input value="', $category['cat_ID'], '" type="checkbox" name="post_category[]" id="in-category-', $category['cat_ID'], '"', ($category['checked'] ? ' checked="checked"' : "" ), '/> ', wp_specialchars( $category['cat_name'] ), "</label></li>";
     708        echo '<li id="category-', $category['cat_ID'], '"><label for="in-category-', $category['cat_ID'], '" class="selectit"><input value="', $category['cat_ID'], '" type="checkbox" name="post_category[]" id="in-category-', $category['cat_ID'], '"', ($category['checked'] ? ' checked="checked"' : "" ), '/> ', wp_specialchars( apply_filters('the_category', $category['cat_name'] )), "</label></li>";
    697709
    698710        if ( $category['children'] ) {
     
    726738            // No selected categories, strange
    727739            $checked_categories[] = $default;
    728         }   
     740        }
    729741    } else {
    730742        $checked_categories[] = $default;
     
    757769        $categories = get_categories( 'hide_empty=0' );
    758770
     771    $children = _get_category_hierarchy();
     772
    759773    if ( $categories ) {
    760774        ob_start();
     
    762776            if ( $category->category_parent == $parent) {
    763777                echo "\t" . _cat_row( $category, $level );
    764                 cat_rows( $category->cat_ID, $level +1, $categories );
     778                if ( isset($children[$category->cat_ID]) )
     779                    cat_rows( $category->cat_ID, $level +1, $categories );
    765780            }
    766781        }
    767782        $output = ob_get_contents();
    768783        ob_end_clean();
    769        
     784
    770785        $output = apply_filters('cat_rows', $output);
    771786
     
    786801
    787802        if ( ($category->cat_ID != $default_cat_id ) && ($category->cat_ID != $default_link_cat_id ) )
    788             $edit .= "<td><a href='" . wp_nonce_url( "categories.php?action=delete&amp;cat_ID=$category->cat_ID", 'delete-category_' . $category->cat_ID ) . "' onclick=\"return deleteSomething( 'cat', $category->cat_ID, '" . js_escape(sprintf( __("You are about to delete the category '%s'.\nAll of its posts will go into the default category of '%s'\nAll of its bookmarks will go into the default category of '%s'.\n'OK' to delete, 'Cancel' to stop." ), $category->cat_name, get_catname( $default_cat_id ), get_catname( $default_link_cat_id ) )) . "' );\" class='delete'>".__( 'Delete' )."</a>";
     803            $edit .= "<td><a href='" . wp_nonce_url( "categories.php?action=delete&amp;cat_ID=$category->cat_ID", 'delete-category_' . $category->cat_ID ) . "' onclick=\"return deleteSomething( 'cat', $category->cat_ID, '" . js_escape(sprintf( __("You are about to delete the category '%s'.\nAll posts that were only assigned to this category will be assigned to the '%s' category.\nAll links that were only assigned to this category will be assigned to the '%s' category.\n'OK' to delete, 'Cancel' to stop." ), $category->cat_name, get_catname( $default_cat_id ), get_catname( $default_link_cat_id ) )) . "' );\" class='delete'>".__( 'Delete' )."</a>";
    789804        else
    790805            $edit .= "<td style='text-align:center'>".__( "Default" );
     
    873888    $r .= "</td>\n\t</tr>";
    874889    return $r;
     890}
     891
     892function _wp_get_comment_list( $s = false, $start, $num ) {
     893    global $wpdb;
     894
     895    $start = (int) $start;
     896    $num = (int) $num;
     897
     898    if ( $s ) {
     899        $s = $wpdb->escape($s);
     900        $comments = $wpdb->get_results("SELECT SQL_CALC_FOUND_ROWS * FROM $wpdb->comments WHERE
     901            (comment_author LIKE '%$s%' OR
     902            comment_author_email LIKE '%$s%' OR
     903            comment_author_url LIKE ('%$s%') OR
     904            comment_author_IP LIKE ('%$s%') OR
     905            comment_content LIKE ('%$s%') ) AND
     906            comment_approved != 'spam'
     907            ORDER BY comment_date DESC LIMIT $start, $num");
     908    } else {
     909        $comments = $wpdb->get_results( "SELECT SQL_CALC_FOUND_ROWS * FROM $wpdb->comments WHERE comment_approved = '0' OR comment_approved = '1' ORDER BY comment_date DESC LIMIT $start, $num" );
     910    }
     911
     912    $total = $wpdb->get_var( "SELECT FOUND_ROWS()" );
     913
     914    return array($comments, $total);
     915}
     916
     917function _wp_comment_list_item( $id, $alt = 0 ) {
     918    global $authordata, $comment, $wpdb;
     919    $id = (int) $id;
     920    $comment =& get_comment( $id );
     921    $class = '';
     922    $authordata = get_userdata($wpdb->get_var("SELECT post_author FROM $wpdb->posts WHERE ID = $comment->comment_post_ID"));
     923    $comment_status = wp_get_comment_status($comment->comment_ID);
     924    if ( 'unapproved' == $comment_status )
     925        $class .= ' unapproved';
     926    if ( $alt % 2 )
     927        $class .= ' alternate';
     928    echo "<li id='comment-$comment->comment_ID' class='$class'>";
     929?>
     930<p><strong><?php comment_author(); ?></strong> <?php if ($comment->comment_author_email) { ?>| <?php comment_author_email_link() ?> <?php } if ($comment->comment_author_url && 'http://' != $comment->comment_author_url) { ?> | <?php comment_author_url_link() ?> <?php } ?>| <?php _e('IP:') ?> <a href="http://ws.arin.net/cgi-bin/whois.pl?queryinput=<?php comment_author_IP() ?>"><?php comment_author_IP() ?></a></p>
     931
     932<?php comment_text() ?>
     933
     934<p><?php comment_date(__('M j, g:i A'));  ?> &#8212; [
     935<?php
     936if ( current_user_can('edit_post', $comment->comment_post_ID) ) {
     937    echo " <a href='comment.php?action=editcomment&amp;c=".$comment->comment_ID."'>" .  __('Edit') . '</a>';
     938    echo ' | <a href="' . wp_nonce_url('ocomment.php?action=deletecomment&amp;p=' . $comment->comment_post_ID . '&amp;c=' . $comment->comment_ID, 'delete-comment_' . $comment->comment_ID) . '" onclick="return deleteSomething( \'comment\', ' . $comment->comment_ID . ', \'' . js_escape(sprintf(__("You are about to delete this comment by '%s'.\n'Cancel' to stop, 'OK' to delete."), $comment->comment_author)) . "', theCommentList );\">" . __('Delete') . '</a> ';
     939    if ( ('none' != $comment_status) && ( current_user_can('moderate_comments') ) ) {
     940        echo '<span class="unapprove"> | <a href="' . wp_nonce_url('comment.php?action=unapprovecomment&amp;p=' . $comment->comment_post_ID . '&amp;c=' . $comment->comment_ID, 'unapprove-comment_' . $comment->comment_ID) . '" onclick="return dimSomething( \'comment\', ' . $comment->comment_ID . ', \'unapproved\', theCommentList );">' . __('Unapprove') . '</a> </span>';
     941        echo '<span class="approve"> | <a href="' . wp_nonce_url('comment.php?action=approvecomment&amp;p=' . $comment->comment_post_ID . '&amp;c=' . $comment->comment_ID, 'approve-comment_' . $comment->comment_ID) . '" onclick="return dimSomething( \'comment\', ' . $comment->comment_ID . ', \'unapproved\', theCommentList );">' . __('Approve') . '</a> </span>';
     942    }
     943    echo " | <a href=\"" . wp_nonce_url("comment.php?action=deletecomment&amp;dt=spam&amp;p=" . $comment->comment_post_ID . "&amp;c=" . $comment->comment_ID, 'delete-comment_' . $comment->comment_ID) . "\" onclick=\"return deleteSomething( 'comment-as-spam', $comment->comment_ID, '" . js_escape(sprintf(__("You are about to mark as spam this comment by '%s'.\n'Cancel' to stop, 'OK' to mark as spam."), $comment->comment_author))  . "', theCommentList );\">" . __('Spam') . "</a> ";
     944}
     945$post = get_post($comment->comment_post_ID);
     946$post_title = wp_specialchars( $post->post_title, 'double' );
     947$post_title = ('' == $post_title) ? "# $comment->comment_post_ID" : $post_title;
     948?>
     949 ] &#8212; <a href="<?php echo get_permalink($comment->comment_post_ID); ?>"><?php echo $post_title; ?></a></p>
     950        </li>
     951<?php
    875952}
    876953
     
    11321209            $state = true;
    11331210            foreach ( $markerdata as $n => $markerline ) {
    1134                 if ( strstr( $markerline, "# BEGIN {$marker}" ))
     1211                if (strpos($markerline, '# BEGIN ' . $marker) !== false)
    11351212                    $state = false;
    11361213                if ( $state ) {
     
    11401217                        fwrite( $f, "{$markerline}" );
    11411218                }
    1142                 if ( strstr( $markerline, "# END {$marker}" ) ) {
     1219                if (strpos($markerline, '# END ' . $marker) !== false) {
    11431220                    fwrite( $f, "# BEGIN {$marker}\n" );
    11441221                    if ( is_array( $insertion ))
     
    11781255        $state = false;
    11791256        foreach ( $markerdata as $markerline ) {
    1180             if ( strstr( $markerline, "# END {$marker}" ))
     1257            if (strpos($markerline, '# END ' . $marker) !== false)
    11811258                $state = false;
    11821259            if ( $state )
    11831260                $result[] = $markerline;
    1184             if ( strstr( $markerline, "# BEGIN {$marker}" ))
     1261            if (strpos($markerline, '# BEGIN ' . $marker) !== false)
    11851262                $state = true;
    11861263        }
     
    13051382    if ( isset( $plugin_page ) && isset( $_wp_submenu_nopriv[$parent][$plugin_page] ) )
    13061383        return false;
    1307    
     1384
    13081385    if ( empty( $parent) ) {
    13091386        if ( isset( $_wp_menu_nopriv[$pagenow] ) )
     
    13171394                return false;
    13181395            if ( isset( $plugin_page ) && isset( $_wp_submenu_nopriv[$key][$plugin_page] ) )
    1319             return false;   
     1396            return false;
    13201397        }
    13211398        return true;
     
    14391516                    $parent_file = $_wp_real_parent_file[$parent_file];
    14401517            return $parent_file;
    1441         }           
     1518        }
    14421519    }
    14431520
     
    14461523        if ( isset( $_wp_real_parent_file[$parent_file] ) )
    14471524            $parent_file = $_wp_real_parent_file[$parent_file];
    1448         return $parent_file;       
     1525        return $parent_file;
    14491526    }
    14501527
     
    16601737    }
    16611738
    1662     return array ('Name' => $name, 'Title' => $plugin, 'Description' => $description, 'Author' => $author, 'Version' => $version, 'Template' => $template[1] );
     1739    return array('Name' => $name, 'Title' => $plugin, 'Description' => $description, 'Author' => $author, 'Version' => $version);
    16631740}
    16641741
     
    16771754    if ( $plugins_dir ) {
    16781755        while (($file = $plugins_dir->read() ) !== false ) {
    1679             if ( preg_match( '|^\.+$|', $file ))
     1756            if ( substr($file, 0, 1) == '.' )
    16801757                continue;
    16811758            if ( is_dir( $plugin_root.'/'.$file ) ) {
     
    16831760                if ( $plugins_subdir ) {
    16841761                    while (($subfile = $plugins_subdir->read() ) !== false ) {
    1685                         if ( preg_match( '|^\.+$|', $subfile ))
     1762                        if ( substr($subfile, 0, 1) == '.' )
    16861763                            continue;
    1687                         if ( preg_match( '|\.php$|', $subfile ))
     1764                        if ( substr($subfile, -4) == '.php' )
    16881765                            $plugin_files[] = "$file/$subfile";
    16891766                    }
    16901767                }
    16911768            } else {
    1692                 if ( preg_match( '|\.php$|', $file ))
     1769                if ( substr($file, -4) == '.php' )
    16931770                    $plugin_files[] = $file;
    16941771            }
     
    17551832        ';
    17561833}
    1757 if ( strstr( $_SERVER['HTTP_USER_AGENT'], 'MSIE' ))
     1834
     1835if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false)
    17581836    add_action( 'admin_footer', 'browse_happy' );
    17591837
     
    17701848function get_importers() {
    17711849    global $wp_importers;
    1772 
     1850    uasort($wp_importers, create_function('$a, $b', 'return strcmp($a[0], $b[0]);'));
    17731851    return $wp_importers;
    17741852}
     
    18941972    // Compute the URL
    18951973    $url = $uploads['url'] . "/$filename";
    1896    
     1974
    18971975    $return = apply_filters( 'wp_handle_upload', array( 'file' => $new_file, 'url' => $url, 'type' => $type ) );
    18981976
     
    19161994    $size = strtolower( ini_get( 'upload_max_filesize' ) );
    19171995    $bytes = 0;
    1918     if ( strstr( $size, 'k' ) )
     1996    if (strpos($size, 'k') !== false)
    19191997        $bytes = $size * 1024;
    1920     if ( strstr( $size, 'm' ) )
     1998    if (strpos($size, 'm') !== false)
    19211999        $bytes = $size * 1024 * 1024;
    1922     if ( strstr( $size, 'g' ) )
     2000    if (strpos($size, 'g') !== false)
    19232001        $bytes = $size * 1024 * 1024 * 1024;
    19242002?>
    19252003<form enctype="multipart/form-data" id="import-upload-form" method="post" action="<?php echo attribute_escape($action) ?>">
    19262004<p>
     2005<?php wp_nonce_field('import-upload'); ?>
    19272006<label for="upload"><?php _e( 'Choose a file from your computer:' ); ?></label> (<?php printf( __('Maximum size: %s' ), $size ); ?> )
    19282007<input type="file" id="upload" name="import" size="25" />
     
    20532132    wp_clearcookie();
    20542133    // Set cookies for new paths.
    2055     wp_setcookie( $user_login, $user_pass_md5, true, get_option( 'home' ), get_option( 'siteurl' ));   
     2134    wp_setcookie( $user_login, $user_pass_md5, true, get_option( 'home' ), get_option( 'siteurl' ));
    20562135}
    20572136
     
    20752154    }
    20762155
    2077     imageantialias( $dst, true );
     2156    if (function_exists('imageantialias'))
     2157        imageantialias( $dst, true );
     2158   
    20782159    imagecopyresampled( $dst, $src, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h );
    20792160
     
    21952276            // If no filters change the filename, we'll do a default transformation.
    21962277            if ( basename( $file ) == $thumb = apply_filters( 'thumbnail_filename', basename( $file ) ) )
    2197                 $thumb = preg_replace( '!(\.[^.]+)?$!', __( '.thumbnail' ).'$1', basename( $file ), 1 );
     2278                $thumb = preg_replace( '!(\.[^.]+)?$!', '.thumbnail' . '$1', basename( $file ), 1 );
    21982279
    21992280            $thumbpath = str_replace( basename( $file ), $thumb, $file );
  • tags/2.2/wp-admin/admin-header.php

    r5468 r5480  
    1414?>
    1515<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    16 <html xmlns="http://www.w3.org/1999/xhtml" <?php language_attributes(); ?>>
     16<html xmlns="http://www.w3.org/1999/xhtml" <?php do_action('admin_xml_ns'); ?> <?php language_attributes(); ?>>
    1717<head>
    1818<meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php echo get_option('blog_charset'); ?>" />
     
    4545<body>
    4646<div id="wphead">
    47 <h1><?php echo wptexturize(get_option(('blogname'))); ?> <span>(<a href="<?php echo get_option('home') . '/'; ?>"><?php _e('View site &raquo;') ?></a>)</span></h1>
     47<h1><?php bloginfo('name'); ?> <span>(<a href="<?php echo get_option('home') . '/'; ?>"><?php _e('View site &raquo;') ?></a>)</span></h1>
    4848</div>
    4949<div id="user_info"><p><?php printf(__('Howdy, <strong>%s</strong>.'), $user_identity) ?> [<a href="<?php echo get_option('siteurl'); ?>/wp-login.php?action=logout" title="<?php _e('Log out of this account') ?>"><?php _e('Sign Out'); ?></a>, <a href="profile.php"><?php _e('My Profile'); ?></a>] </p></div>
  • tags/2.2/wp-admin/admin.php

    r5468 r5480  
    55    require_once('../wp-config.php');
    66
    7 if ( get_option('db_version') != $wp_db_version )
    8     wp_die(sprintf(__("Your database is out-of-date.  Please <a href='%s'>upgrade</a>."), get_option('siteurl') . '/wp-admin/upgrade.php'));
    9    
     7if ( get_option('db_version') != $wp_db_version ) {
     8    wp_redirect(get_option('siteurl') . '/wp-admin/upgrade.php?_wp_http_referer=' . urlencode(stripslashes($_SERVER['REQUEST_URI'])));
     9    exit;
     10}
     11
    1012require_once(ABSPATH . 'wp-admin/admin-functions.php');
    1113require_once(ABSPATH . 'wp-admin/admin-db.php');
  • tags/2.2/wp-admin/categories.js

    r5468 r5480  
    33    document.forms.addcat.submit.onclick = function(e) {return killSubmit('theList.ajaxAdder("cat", "addcat");', e); };
    44    theList.addComplete = function(what, where, update, transport) {
    5         var name = getNodeValue(transport.responseXML, 'name');
     5        var name = getNodeValue(transport.responseXML, 'name').unescapeHTML();
    66        var id = transport.responseXML.getElementsByTagName(what)[0].getAttribute('id');
    77        var options = document.forms['addcat'].category_parent.options;
  • tags/2.2/wp-admin/categories.php

    r5468 r5480  
    115115<?php if ( current_user_can('manage_categories') ) : ?>
    116116<div class="wrap">
    117 <p><?php printf(__('<strong>Note:</strong><br />Deleting a category does not delete the posts and links in that category.  Instead, posts in the deleted category are set to the category <strong>%s</strong> and links are set to <strong>%s</strong>.'), get_catname(get_option('default_category')), get_catname(get_option('default_link_category'))) ?></p>
     117<p><?php printf(__('<strong>Note:</strong><br />Deleting a category does not delete the posts and links in that category. Instead, posts that were only assigned to the deleted category are set to the category <strong>%s</strong> and links that were only assigned to the deleted category are set to <strong>%s</strong>.'), apply_filters('the_category', get_catname(get_option('default_category'))), apply_filters('the_category', get_catname(get_option('default_link_category')))) ?></p>
    118118</div>
    119119
  • tags/2.2/wp-admin/custom-header.php

    • Property svn:eol-style set to native
    r5468 r5480  
    1818    function js_includes() {
    1919        wp_enqueue_script('cropper');
    20         wp_enqueue_script('colorpicker');   
     20        wp_enqueue_script('colorpicker');
    2121    }
    2222
     
    2424
    2525        if ( isset( $_POST['textcolor'] ) ) {
     26            check_admin_referer('custom-header');
    2627            if ( 'blank' == $_POST['textcolor'] ) {
    2728                set_theme_mod('header_textcolor', 'blank');
     
    3233            }
    3334        }
    34         if ( isset($_POST['resetheader']) )
     35        if ( isset($_POST['resetheader']) ) {
     36            check_admin_referer('custom-header');
    3537            remove_theme_mods();
     38        }
    3639    ?>
    3740<script type="text/javascript">
     
    116119        pickColor('<?php echo HEADER_TEXTCOLOR; ?>');
    117120    }
    118    
     121
    119122    function hide_text() {
    120123        $('name').style.display = 'none';
     
    127130        Event.observe( $('hidetext'), 'click', show_text );
    128131    }
    129    
     132
    130133    function show_text() {
    131134        $('name').style.display = 'block';
     
    135138        $('textcolor').value = '<?php echo HEADER_TEXTCOLOR; ?>';
    136139        $('hidetext').value = '<?php _e('Hide Text'); ?>';
    137         Event.stopObserving( $('hidetext'), 'click', show_text );   
     140        Event.stopObserving( $('hidetext'), 'click', show_text );
    138141        Event.observe( $('hidetext'), 'click', hide_text );
    139142    }
     
    158161<p><?php _e('This is your header image. You can change the text color or upload and crop a new image.'); ?></p>
    159162
    160 <div id="headimg" style="background: url(<?php header_image() ?>) no-repeat;">
     163<div id="headimg" style="background: url(<?php clean_url(header_image()) ?>) no-repeat;">
    161164<h1><a onclick="return false;" href="<?php bloginfo('url'); ?>" title="<?php bloginfo('name'); ?>" id="name"><?php bloginfo('name'); ?></a></h1>
    162165<div id="desc"><?php bloginfo('description');?></div>
     
    166169<input type="button" value="<?php _e('Hide Text'); ?>" onclick="hide_text()" id="hidetext" />
    167170<input type="button" value="<?php _e('Select a Text Color'); ?>" onclick="colorSelect($('textcolor'), 'pickcolor')" id="pickcolor" /><input type="button" value="<?php _e('Use Original Color'); ?>" onclick="colorDefault()" id="defaultcolor" />
    168 <input type="hidden" name="textcolor" id="textcolor" value="#<?php header_textcolor() ?>" /><input name="submit" type="submit" value="<?php _e('Save Changes'); ?> &raquo;" /></form>
     171<?php wp_nonce_field('custom-header') ?>
     172<input type="hidden" name="textcolor" id="textcolor" value="#<?php attribute_escape(header_textcolor()) ?>" /><input name="submit" type="submit" value="<?php _e('Save Changes'); ?> &raquo;" /></form>
    169173<?php } ?>
    170174
     
    178182<label for="upload"><?php _e('Choose an image from your computer:'); ?></label><br /><input type="file" id="upload" name="import" />
    179183<input type="hidden" name="action" value="save" />
     184<?php wp_nonce_field('custom-header') ?>
    180185<p class="submit">
    181186<input type="submit" value="<?php _e('Upload'); ?> &raquo;" />
     
    190195<p><?php _e('This will restore the original header image and color. You will not be able to retrieve any customizations.') ?></p>
    191196<form method="post" action="<?php echo attribute_escape(add_query_arg('step', 1)) ?>">
     197<?php wp_nonce_field('custom-header'); ?>
    192198<input type="submit" name="resetheader" value="<?php _e('Restore Original Header'); ?>" />
    193199</form>
     
    198204
    199205    function step_2() {
     206        check_admin_referer('custom-header');
    200207        $overrides = array('test_form' => false);
    201208        $file = wp_handle_upload($_FILES['import'], $overrides);
     
    223230
    224231        if ( $width == HEADER_IMAGE_WIDTH && $height == HEADER_IMAGE_HEIGHT ) {
    225             set_theme_mod('header_image', $url);
     232            set_theme_mod('header_image', clean_url($url));
    226233            $header = apply_filters('wp_create_file_in_uploads', $file, $id); // For replication
    227234            return $this->finished();
     
    257264<input type="hidden" name="attachment_id" id="attachment_id" value="<?php echo $id; ?>" />
    258265<input type="hidden" name="oitar" id="oitar" value="<?php echo $oitar; ?>" />
     266<?php wp_nonce_field('custom-header') ?>
    259267<input type="submit" value="<?php _e('Crop Header &raquo;'); ?>" />
    260268</p>
     
    266274
    267275    function step_3() {
     276        check_admin_referer('custom-header');
    268277        if ( $_POST['oitar'] > 1 ) {
    269278            $_POST['x1'] = $_POST['x1'] * $_POST['oitar'];
  • tags/2.2/wp-admin/edit-category-form.php

    r5468 r5480  
    3636            <th scope="row" valign="top"><label for="category_parent"><?php _e('Category parent:') ?></label></th>
    3737            <td>       
    38                 <?php wp_dropdown_categories('hide_empty=0&name=category_parent&selected=' . $category->category_parent . '&hierarchical=1&show_option_none=' . __('None')); ?>
     38                <?php wp_dropdown_categories('hide_empty=0&name=category_parent&orderby=name&selected=' . $category->category_parent . '&hierarchical=1&show_option_none=' . __('None')); ?>
    3939            </td>
    4040        </tr>
  • tags/2.2/wp-admin/edit-comments.js

    r5468 r5480  
    33    if ( !theCommentList )
    44        return false;
     5
     6    theExtraCommentList = new listMan('the-extra-comment-list');
     7    if ( theExtraCommentList ) {
     8        theExtraCommentList.showLink = 0;
     9        theExtraCommentList.altOffset = 1;
     10        if ( theExtraCommentList.theList && theExtraCommentList.theList.childNodes )
     11            var commentNum = $A(theExtraCommentList.theList.childNodes).findAll( function(i) { return Element.visible(i) } ).length;
     12        else
     13            var commentNum = 0;
     14        var urlQ   = document.location.href.split('?');
     15        var params = urlQ[1] ? urlQ[1].toQueryParams() : [];
     16        var search = params['s'] ? params['s'] : '';
     17        var page   = params['apage'] ? params['apage'] : 1;
     18    }
     19
    520    theCommentList.dimComplete = function(what,id,dimClass) {
    621        var m = document.getElementById('awaitmod');
    7         if ( document.getElementById(what + '-' + id).className.match(dimClass) ) m.innerHTML = parseInt(m.innerHTML,10) + 1;
    8         else m.innerHTML = parseInt(m.innerHTML,10) - 1;
     22        if ( document.getElementById(what + '-' + id).className.match(dimClass) )
     23            m.innerHTML = parseInt(m.innerHTML,10) + 1;
     24        else
     25            m.innerHTML = parseInt(m.innerHTML,10) - 1;
    926    }
     27
    1028    theCommentList.delComplete = function(what,id) {
    1129        var m = document.getElementById('awaitmod');
    12         if ( document.getElementById(what + '-' + id).className.match('unapproved') ) m.innerHTML = parseInt(m.innerHTML,10) - 1;
     30        what = what.split('-')[0];
     31        if ( document.getElementById(what + '-' + id).className.match('unapproved') )
     32            m.innerHTML = parseInt(m.innerHTML,10) - 1;
     33        if ( theExtraCommentList && commentNum ) {
     34            var theMover = theExtraCommentList.theList.childNodes[0];
     35            Element.removeClassName(theMover,'alternate');
     36            theCommentList.theList.appendChild(theMover);
     37            theExtraCommentList.inputData += '&page=' + page;
     38            if ( search )
     39                theExtraCommentList.inputData += '&s=' + search; // trust the URL not the search box
     40            theExtraCommentList.addComplete = function() {
     41                if ( theExtraCommentList.theList.childNodes )
     42                    var commentNum = $A(theExtraCommentList.theList.childNodes).findAll( function(i) { return Element.visible(i) } ).length;
     43                else
     44                    var commentNum = 0;
     45            }
     46            theExtraCommentList.ajaxAdder( 'comment', 'ajax-response' ); // Dummy Request
     47        }
    1348    }
     49
    1450    if ( theList ) // the post list: edit.php
    1551        theList.delComplete = function() {
  • tags/2.2/wp-admin/edit-comments.php

    r5468 r5480  
    7676endif;
    7777
    78 if (isset($_GET['s'])) {
    79     $s = $wpdb->escape($_GET['s']);
    80     $comments = $wpdb->get_results("SELECT * FROM $wpdb->comments  WHERE
    81         (comment_author LIKE '%$s%' OR
    82         comment_author_email LIKE '%$s%' OR
    83         comment_author_url LIKE ('%$s%') OR
    84         comment_author_IP LIKE ('%$s%') OR
    85         comment_content LIKE ('%$s%') ) AND
    86         comment_approved != 'spam'
    87         ORDER BY comment_date DESC");
    88 } else {
    89     if ( isset( $_GET['apage'] ) )
    90         $page = (int) $_GET['apage'];
    91     else
    92         $page = 1;
    93     $start = $offset = ( $page - 1 ) * 20;
    94 
    95     $comments = $wpdb->get_results( "SELECT * FROM $wpdb->comments WHERE comment_approved = '0' OR comment_approved = '1' ORDER BY comment_date DESC LIMIT $start, 20" );
    96     $total = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = '0' OR comment_approved = '1'" );
    97 }
    98 ?>
    99 <?php if ( $total > 20 ) {
    100 $total_pages = ceil( $total / 20 );
    101 $r = '';
    102 if ( 1 < $page ) {
    103     $args['apage'] = ( 1 == $page - 1 ) ? FALSE : $page - 1;
    104     $r .=  '<a class="prev" href="' . clean_url(add_query_arg( $args )) . '">&laquo; '. __('Previous Page') .'</a>' . "\n";
    105 }
    106 if ( ( $total_pages = ceil( $total / 20 ) ) > 1 ) {
    107     for ( $page_num = 1; $page_num <= $total_pages; $page_num++ ) :
    108         if ( $page == $page_num ) :
    109             $r .=  "<span>$page_num</span>\n";
    110         else :
    111             $p = false;
    112             if ( $page_num < 3 || ( $page_num >= $page - 3 && $page_num <= $page + 3 ) || $page_num > $total_pages - 3 ) :
    113                 $args['apage'] = ( 1 == $page_num ) ? FALSE : $page_num;
    114                 $r .= '<a class="page-numbers" href="' . clean_url(add_query_arg($args)) . '">' . ( $page_num ) . "</a>\n";
    115                 $in = true;
    116             elseif ( $in == true ) :
    117                 $r .= "...\n";
    118                 $in = false;
    119             endif;
    120         endif;
    121     endfor;
    122 }
    123 if ( ( $page ) * 20 < $total || -1 == $total ) {
    124     $args['apage'] = $page + 1;
    125     $r .=  '<a class="next" href="' . clean_url(add_query_arg($args)) . '">'. __('Next Page') .' &raquo;</a>' . "\n";
    126 }
    127 echo "<p class='pagenav'>$r</p>";
    128 ?>
    129 
    130 <?php } ?>
    131 
    132 <?php
     78if ( isset( $_GET['apage'] ) )
     79    $page = (int) $_GET['apage'];
     80else
     81    $page = 1;
     82$start = $offset = ( $page - 1 ) * 20;
     83
     84list($_comments, $total) = _wp_get_comment_list( isset($_GET['s']) ? $_GET['s'] : false, $start, 25 ); // Grab a few extra
     85
     86$comments = array_slice($_comments, 0, 20);
     87$extra_comments = array_slice($_comments, 20);
     88
     89$page_links = paginate_links( array(
     90    'base' => 'edit-comments.php?%_%',
     91    'format' => 'apage=%#%',
     92    'total' => ceil($total / 20),
     93    'current' => $page
     94));
     95
     96if ( $page_links )
     97    echo "<p class='pagenav'>$page_links</p>";
     98
    13399if ('view' == $mode) {
    134100    if ($comments) {
    135 ?>
    136 <?php
    137 $offset = $offset + 1;
    138 $start = " start='$offset'";
    139 
    140         echo "<ol id='the-comment-list' class='commentlist' $start>";
     101        $offset = $offset + 1;
     102        $start = " start='$offset'";
     103
     104        echo "<ol id='the-comment-list' class='commentlist' $start>\n";
    141105        $i = 0;
    142         foreach ($comments as $comment) {
    143         ++$i; $class = '';
    144         $authordata = get_userdata($wpdb->get_var("SELECT post_author FROM $wpdb->posts WHERE ID = $comment->comment_post_ID"));
    145             $comment_status = wp_get_comment_status($comment->comment_ID);
    146             if ('unapproved' == $comment_status)
    147                 $class .= ' unapproved';
    148             if ($i % 2)
    149                 $class .= ' alternate';
    150             echo "<li id='comment-$comment->comment_ID' class='$class'>";
    151 ?>
    152 <p><strong><?php comment_author() ?></strong> <?php if ($comment->comment_author_email) { ?>| <?php comment_author_email_link() ?> <?php } if ($comment->comment_author_url && 'http://' != $comment->comment_author_url) { ?> | <?php comment_author_url_link() ?> <?php } ?>| <?php _e('IP:') ?> <a href="http://ws.arin.net/cgi-bin/whois.pl?queryinput=<?php comment_author_IP() ?>"><?php comment_author_IP() ?></a></p>
    153 
    154 <?php comment_text() ?>
    155 
    156 <p><?php comment_date('M j, g:i A');  ?> &#8212; [
    157 <?php
    158 if ( current_user_can('edit_post', $comment->comment_post_ID) ) {
    159     echo " <a href='comment.php?action=editcomment&amp;c=".$comment->comment_ID."'>" .  __('Edit') . '</a>';
    160     echo ' | <a href="' . wp_nonce_url('comment.php?action=deletecomment&amp;p=' . $comment->comment_post_ID . '&amp;c=' . $comment->comment_ID, 'delete-comment_' . $comment->comment_ID) . '" onclick="return deleteSomething( \'comment\', ' . $comment->comment_ID . ', \'' . js_escape(sprintf(__("You are about to delete this comment by '%s'.\n'Cancel' to stop, 'OK' to delete."), $comment->comment_author)) . "', theCommentList );\">" . __('Delete') . '</a> ';
    161     if ( ('none' != $comment_status) && ( current_user_can('moderate_comments') ) ) {
    162         echo '<span class="unapprove"> | <a href="' . wp_nonce_url('comment.php?action=unapprovecomment&amp;p=' . $comment->comment_post_ID . '&amp;c=' . $comment->comment_ID, 'unapprove-comment_' . $comment->comment_ID) . '" onclick="return dimSomething( \'comment\', ' . $comment->comment_ID . ', \'unapproved\', theCommentList );">' . __('Unapprove') . '</a> </span>';
    163         echo '<span class="approve"> | <a href="' . wp_nonce_url('comment.php?action=approvecomment&amp;p=' . $comment->comment_post_ID . '&amp;c=' . $comment->comment_ID, 'approve-comment_' . $comment->comment_ID) . '" onclick="return dimSomething( \'comment\', ' . $comment->comment_ID . ', \'unapproved\', theCommentList );">' . __('Approve') . '</a> </span>';
    164     }
    165     echo " | <a href=\"" . wp_nonce_url("comment.php?action=deletecomment&amp;dt=spam&amp;p=" . $comment->comment_post_ID . "&amp;c=" . $comment->comment_ID, 'delete-comment_' . $comment->comment_ID) . "\" onclick=\"return deleteSomething( 'comment-as-spam', $comment->comment_ID, '" . js_escape(sprintf(__("You are about to mark as spam this comment by '%s'.\n'Cancel' to stop, 'OK' to mark as spam."), $comment->comment_author))  . "', theCommentList );\">" . __('Spam') . "</a> ";
    166 }
    167 $post = get_post($comment->comment_post_ID);
    168 $post_title = wp_specialchars( $post->post_title, 'double' );
    169 $post_title = ('' == $post_title) ? "# $comment->comment_post_ID" : $post_title;
    170 ?>
    171  | <a href="<?php echo get_permalink($comment->comment_post_ID); ?>" title="<?php echo $post_title; ?>"><?php _e('View Post') ?></a> ]</p>
    172         </li>
    173 
    174 <?php } // end foreach($comment) ?>
    175 </ol>
     106        foreach ( $comments as $comment ) {
     107            get_comment( $comment ); // Cache it
     108            _wp_comment_list_item( $comment->comment_ID, ++$i );
     109        }
     110        echo "</ol>\n\n";
     111
     112if ( $extra_comments ) : ?>
     113<div id="extra-comments" style="display:none">
     114<ul id="the-extra-comment-list" class="commentlist">
     115<?php
     116    foreach ( $extra_comments as $comment ) {
     117        get_comment( $comment ); // Cache it
     118        _wp_comment_list_item( $comment->comment_ID, ++$i );
     119    }
     120?>
     121</ul>
     122</div>
     123<?php endif; // $extra_comments ?>
    176124
    177125<div id="ajax-response"></div>
     
    243191    } // end if ($comments)
    244192}
    245     ?>
    246 <?php if ( $total > 20 ) {
    247 $total_pages = ceil( $total / 20 );
    248 $r = '';
    249 if ( 1 < $page ) {
    250     $args['apage'] = ( 1 == $page - 1 ) ? FALSE : $page - 1;
    251     $r .=  '<a class="prev" href="' . clean_url(add_query_arg( $args )) . '">&laquo; '. __('Previous Page') .'</a>' . "\n";
    252 }
    253 if ( ( $total_pages = ceil( $total / 20 ) ) > 1 ) {
    254     for ( $page_num = 1; $page_num <= $total_pages; $page_num++ ) :
    255         if ( $page == $page_num ) :
    256             $r .=  "<span>$page_num</span>\n";
    257         else :
    258             $p = false;
    259             if ( $page_num < 3 || ( $page_num >= $page - 3 && $page_num <= $page + 3 ) || $page_num > $total_pages - 3 ) :
    260                 $args['apage'] = ( 1 == $page_num ) ? FALSE : $page_num;
    261                 $r .= '<a class="page-numbers" href="' . clean_url(add_query_arg($args)) . '">' . ( $page_num ) . "</a>\n";
    262                 $in = true;
    263             elseif ( $in == true ) :
    264                 $r .= "...\n";
    265                 $in = false;
    266             endif;
    267         endif;
    268     endfor;
    269 }
    270 if ( ( $page ) * 20 < $total || -1 == $total ) {
    271     $args['apage'] = $page + 1;
    272     $r .=  '<a class="next" href="' . clean_url(add_query_arg($args)) . '">'. __('Next Page') .' &raquo;</a>' . "\n";
    273 }
    274 echo "<p class='pagenav'>$r</p>";
    275 ?>
    276 
    277 <?php } ?>
     193
     194if ( $page_links )
     195    echo "<p class='pagenav'>$page_links</p>";
     196
     197?>
    278198
    279199</div>
  • tags/2.2/wp-admin/edit-form-advanced.php

    r5468 r5480  
    108108<?php if ( current_user_can('edit_posts') ) : ?>
    109109<fieldset id="posttimestampdiv" class="dbx-box">
    110 <h3 class="dbx-handle"><?php _e('Post Timestamp'); ?>:</h3>
     110<h3 class="dbx-handle"><?php _e('Post Timestamp'); ?></h3>
    111111<div class="dbx-content"><?php touch_time(($action == 'edit')); ?></div>
    112112</fieldset>
     
    118118?>
    119119<fieldset id="authordiv" class="dbx-box">
    120 <h3 class="dbx-handle"><?php _e('Post Author'); ?>:</h3>
     120<h3 class="dbx-handle"><?php _e('Post Author'); ?></h3>
    121121<div class="dbx-content">
    122122<select name="post_author_override" id="post_author_override">
     
    145145
    146146<fieldset id="<?php echo user_can_richedit() ? 'postdivrich' : 'postdiv'; ?>">
    147 <legend><?php _e('Post') ?></legend>
     147<legend><?php _e('Post') ?>
     148
     149<?php if ( 'publish' == $post->post_status ) { ?>
     150<a href="<?php echo clean_url(get_permalink($post->ID)); ?>" class="view-link" target="_blank"><?php _e('View &raquo;'); ?></a>
     151<?php } elseif ( 'edit' == $action ) { ?>
     152<a href="<?php echo clean_url(apply_filters('preview_post_link', add_query_arg('preview', 'true', get_permalink($post->ID)))); ?>" class="view-link" target="_blank"><?php _e('Preview &raquo;'); ?></a>
     153<?php } ?>
     154</legend>
    148155
    149156    <?php the_editor($post->post_content); ?>
     
    245252
    246253<?php if ('edit' == $action) : $delete_nonce = wp_create_nonce( 'delete-post_' . $post_ID ); ?>
    247 <input name="deletepost" class="button delete" type="submit" id="deletepost" tabindex="10" value="<?php _e('Delete this post') ?>" <?php echo "onclick=\"if ( confirm('" . js_escape(sprintf(__("You are about to delete this post '%s'\n  'Cancel' to stop, 'OK' to delete."), $post->post_title )) . "') ) { document.forms.post._wpnonce.value = '$delete_nonce'; return true;}return false;\""; ?> />
     254<input name="deletepost" class="button delete" type="submit" id="deletepost" tabindex="10" value="<?php echo ( 'draft' == $post->post_status ) ? __('Delete this draft') : __('Delete this post'); ?>" <?php echo "onclick=\"if ( confirm('" . js_escape(sprintf( ('draft' == $post->post_status) ? __("You are about to delete this draft '%s'\n  'Cancel' to stop, 'OK' to delete.") : __("You are about to delete this post '%s'\n  'Cancel' to stop, 'OK' to delete."), $post->post_title )) . "') ) { document.forms.post._wpnonce.value = '$delete_nonce'; return true;}return false;\""; ?> />
    248255<?php endif; ?>
    249256
  • tags/2.2/wp-admin/edit-form-comment.php

    r5468 r5480  
    3333        <legend><label for="newcomment_author_url"><?php _e('URL:') ?></label></legend>
    3434        <div>
    35           <input type="text" id="newcomment_author_url" name="newcomment_author_url" size="35" value="<?php echo $comment->comment_author_url ?>" tabindex="3" id="URL" />
     35          <input type="text" id="newcomment_author_url" name="newcomment_author_url" size="35" value="<?php echo $comment->comment_author_url ?>" tabindex="3" />
    3636    </div>
    3737</fieldset>
  • tags/2.2/wp-admin/edit-link-form.php

    r5468 r5480  
    2323
    2424    if ('' == $value) {
    25         if ('family' == $class && !strstr($link_rel, 'child') && !strstr($link_rel, 'parent') && !strstr($link_rel, 'sibling') && !strstr($link_rel, 'spouse') && !strstr($link_rel, 'kin')) echo ' checked="checked"';
    26         if ('friendship' == $class && !strstr($link_rel, 'friend') && !strstr($link_rel, 'acquaintance') && !strstr($link_rel, 'contact') ) echo ' checked="checked"';
    27         if ('geographical' == $class && !strstr($link_rel, 'co-resident') && !strstr($link_rel, 'neighbor') ) echo ' checked="checked"';
     25        if ('family' == $class && strpos($link_rel, 'child') === false && strpos($link_rel, 'parent') === false && strpos($link_rel, 'sibling') === false && strpos($link_rel, 'spouse') === false && strpos($link_rel, 'kin') === false) echo ' checked="checked"';
     26        if ('friendship' == $class && strpos($link_rel, 'friend') === false && strpos($link_rel, 'acquaintance') === false && strpos($link_rel, 'contact') === false) echo ' checked="checked"';
     27        if ('geographical' == $class && strpos($link_rel, 'co-resident') === false && strpos($link_rel, 'neighbor') === false) echo ' checked="checked"';
    2828        if ('identity' == $class && in_array('me', $rels) ) echo ' checked="checked"';
    2929    }
  • tags/2.2/wp-admin/edit-page-form.php

    r5468 r5480  
    9999<?php if ( $authors = get_editable_authors( $current_user->id ) ) : // TODO: ROLE SYSTEM ?>
    100100<fieldset id="authordiv" class="dbx-box">
    101 <h3 class="dbx-handle"><?php _e('Page Author'); ?>:</h3>
     101<h3 class="dbx-handle"><?php _e('Page Author'); ?></h3>
    102102<div class="dbx-content">
    103103<select name="post_author_override" id="post_author_override">
     
    132132
    133133<fieldset id="<?php echo user_can_richedit() ? 'postdivrich' : 'postdiv'; ?>">
    134     <legend><?php _e('Page Content') ?></legend>
     134<legend><?php _e('Page Content') ?>
     135
     136<?php if ( 'publish' == $post->post_status ) { ?>
     137<a href="<?php echo clean_url(get_permalink($post->ID)); ?>" style="position: absolute; right: 2em; margin-right: 19em; text-decoration: underline;" target="_blank"><?php _e('View &raquo;'); ?></a>
     138<?php } elseif ( 'edit' == $action ) { ?>
     139<a href="<?php echo clean_url(apply_filters('preview_post_link', add_query_arg('preview', 'true', get_permalink($post->ID)))); ?>" style="position: absolute; right: 2em; margin-right: 19em; text-decoration: underline;" target="_blank"><?php _e('Preview &raquo;'); ?></a>
     140<?php } ?>
     141</legend>
    135142    <?php the_editor($post->post_content); ?>
    136143</fieldset>
  • tags/2.2/wp-admin/edit.php

    r5468 r5480  
    2222        if (0 != $i)
    2323            echo ', ';
    24         $draft->post_title = stripslashes($draft->post_title);
     24        $draft->post_title = apply_filters('the_title', stripslashes($draft->post_title));
    2525        if ($draft->post_title == '')
    2626            $draft->post_title = sprintf(__('Post #%s'), $draft->ID);
     
    2929        }
    3030    ?>
    31     .</p>
     31.</p>
    3232<?php } ?>
    3333
     
    3939        if (0 != $i)
    4040            echo ', ';
    41         $draft->post_title = stripslashes($draft->post_title);
     41        $draft->post_title = apply_filters('the_title', stripslashes($draft->post_title));
    4242        if ($draft->post_title == '')
    4343            $draft->post_title = sprintf(__('Post #%s'), $draft->ID);
     
    6565} else {
    6666    if ( is_single() )
    67         printf(__('Comments on %s'), $post->post_title);
     67        printf(__('Comments on %s'), apply_filters( "the_title", $post->post_title));
    6868    elseif ( ! is_paged() || get_query_var('paged') == 1 )
    6969        _e('Last 15 Posts');
     
    178178    case 'date':
    179179        ?>
    180         <td><?php if ( '0000-00-00 00:00:00' ==$post->post_modified ) _e('Unpublished'); else the_time(_('Y-m-d \<\b\r \/\> g:i:s a')); ?></td>
     180        <td><?php if ( '0000-00-00 00:00:00' ==$post->post_modified ) _e('Unpublished'); else the_time(__('Y-m-d \<\b\r \/\> g:i:s a')); ?></td>
    181181        <?php
    182182        break;
  • tags/2.2/wp-admin/export.php

    r5468 r5480  
    123123    echo '<wp:category_description>' . wxr_cdata($c->category_description) . '</wp:category_description>';
    124124}
    125 ?>
    126 <!-- This is a WordPress eXtended RSS file generated by WordPress as an export of your blog. -->
    127 <!-- It contains information about your blog's posts, comments, and categories. -->
    128 <!-- You may use this file to transfer that content from one site to another. -->
    129 <!-- This file is not intended to serve as a complete backup of your blog. -->
    130 
    131 <!-- To import this information into a WordPress blog follow these steps. -->
    132 <!-- 1. Log into that blog as an administrator. -->
    133 <!-- 2. Go to Manage: Import in the blog's admin panels. -->
    134 <!-- 3. Choose "WordPress" from the list. -->
    135 <!-- 4. Upload this file using the form provided on that page. -->
    136 <!-- 5. You will first be asked to map the authors in this export file to users -->
    137 <!--    on the blog.  For each author, you may choose to map to an -->
    138 <!--    existing user on the blog or to create a new user -->
    139 <!-- 6. WordPress will then import each of the posts, comments, and categories -->
    140 <!--    contained in this file into your blog -->
     125
     126print '<?xml version="1.0" encoding="' . get_bloginfo('charset') . '"?' . ">\n";
     127
     128?>
     129
     130<!--
     131    This is a WordPress eXtended RSS file generated by WordPress as an export of
     132    your blog. It contains information about your blog's posts, comments, and
     133    categories. You may use this file to transfer that content from one site to
     134    another. This file is not intended to serve as a complete backup of your
     135    blog.
     136   
     137    To import this information into a WordPress blog follow these steps:
     138   
     139    1.  Log into that blog as an administrator.
     140    2.  Go to Manage > Import in the blog's admin.
     141    3.  Choose "WordPress" from the list of importers.
     142    4.  Upload this file using the form provided on that page.
     143    5.  You will first be asked to map the authors in this export file to users
     144        on the blog. For each author, you may choose to map an existing user on
     145        the blog or to create a new user.
     146    6.  WordPress will then import each of the posts, comments, and categories
     147        contained in this file onto your blog.
     148-->
    141149
    142150<!-- generator="wordpress/<?php bloginfo_rss('version') ?>" created="<?php echo date('Y-m-d H:m'); ?>"-->
     
    178186<wp:status><?php echo $post->post_status; ?></wp:status>
    179187<wp:post_parent><?php echo $post->post_parent; ?></wp:post_parent>
     188<wp:menu_order><?php echo $post->menu_order; ?></wp:menu_order>
    180189<wp:post_type><?php echo $post->post_type; ?></wp:post_type>
    181190<?php
  • tags/2.2/wp-admin/import.php

    r5468 r5480  
    1818if ($imports_dir) {
    1919    while (($file = $imports_dir->read()) !== false) {
    20         if (preg_match('|^\.+$|', $file))
     20        if ($file{0} == '.') {
    2121            continue;
    22         if (preg_match('|\.php$|', $file))
    23             require_once("$import_root/$file");
     22        } elseif (substr($file, -4) == '.php') {
     23            require_once($import_root . '/' . $file);
     24        }
    2425    }
    2526}
  • tags/2.2/wp-admin/import/blogger.php

    r5468 r5480  
    11<?php
    22
     3define( 'MAX_RESULTS',        50 ); // How many records per GData query
     4define( 'MAX_EXECUTION_TIME', 20 ); // How many seconds to let the script run
     5define( 'STATUS_INTERVAL',     3 ); // How many seconds between status bar updates
     6
    37class Blogger_Import {
    48
    5     var $lump_authors = false;
    6     var $import = array();
    7 
    8     // Shows the welcome screen and the magic iframe.
     9    // Shows the welcome screen and the magic auth link.
    910    function greet() {
    10         $title = __('Import Old Blogger');
    11         $welcome = __('Howdy! This importer allows you to import posts and comments from your Old Blogger account into your WordPress blog.');
    12         $noiframes = __('This feature requires iframe support.');
    13         $warning = js_escape(__('This will delete everything saved by the Blogger importer except your posts and comments. Are you sure you want to do this?'));
    14         $reset = __('Reset this importer');
    15         $incompat = __('Your web server is not properly configured to use this importer. Please enable the CURL extension for PHP and then reload this page.');
    16 
    17         echo "<div class='wrap'><h2>$title</h2><p>$welcome</p>";
    18         echo "<p>" . __('Please note that this importer <em>does not work with new Blogger (using your Google account)</em>.') . "</p>";
    19         if ( function_exists('curl_init') )
    20             echo "<iframe src='admin.php?import=blogger&amp;noheader=true' height='350px' width = '99%'>$noiframes</iframe><p><a href='admin.php?import=blogger&amp;restart=true&amp;noheader=true' onclick='return confirm(\"$warning\")'>$reset</a></p>";
     11        $next_url = get_option('siteurl') . '/wp-admin/index.php?import=blogger&noheader=true';
     12        $auth_url = "https://www.google.com/accounts/AuthSubRequest";
     13        $title = __('Import Blogger');
     14        $welcome = __('Howdy! This importer allows you to import posts and comments from your Blogger account into your WordPress blog.');
     15        $prereqs = __('To use this importer, you must have a Google account, an upgraded (New, was Beta) blog, and it must be on blogspot or a custom domain (not FTP).');
     16        $stepone = __('The first thing you need to do is tell Blogger to let WordPress access your account. You will be sent back here after providing authorization.');
     17        $auth = __('Authorize');
     18
     19        echo "
     20        <div class='wrap'><h2>$title</h2><p>$welcome</p><p>$prereqs</p><p>$stepone</p>
     21            <form action='$auth_url' method='get'>
     22                <p class='submit' style='text-align:left;'>
     23                    <input type='submit' value='$auth' />
     24                    <input type='hidden' name='scope' value='http://www.blogger.com/feeds/' />
     25                    <input type='hidden' name='session' value='1' />
     26                    <input type='hidden' name='secure' value='0' />
     27                    <input type='hidden' name='next' value='$next_url' />
     28                </p>
     29            </form>
     30        </div>\n";
     31    }
     32
     33    function uh_oh($title, $message, $info) {
     34        echo "<div class='wrap'><h2>$title</h2><p>$message</p><pre>$info</pre></div>";
     35    }
     36
     37    function auth() {
     38        // We have a single-use token that must be upgraded to a session token.
     39        $token = preg_replace( '/[^-_0-9a-zA-Z]/', '', $_GET['token'] );
     40        $headers = array(
     41            "GET /accounts/AuthSubSessionToken HTTP/1.0",
     42            "Authorization: AuthSub token=\"$token\""
     43        );
     44        $request = join( "\r\n", $headers ) . "\r\n\r\n";
     45        $sock = $this->_get_auth_sock( );
     46        if ( ! $sock ) return false;
     47        $response = $this->_txrx( $sock, $request );
     48        preg_match( '/token=([-_0-9a-z]+)/i', $response, $matches );
     49        if ( empty( $matches[1] ) ) {
     50            $this->uh_oh(
     51                __( 'Authorization failed' ),
     52                __( 'Something went wrong. If the problem persists, send this info to support:' ),
     53                htmlspecialchars($response)
     54            );
     55            return false;
     56        }
     57        $this->token = $matches[1];
     58
     59        wp_redirect( remove_query_arg( array( 'token', 'noheader' ) ) );
     60    }
     61
     62    function get_token_info() {
     63        $headers = array(
     64            "GET /accounts/AuthSubTokenInfo  HTTP/1.0",
     65            "Authorization: AuthSub token=\"$this->token\""
     66        );
     67        $request = join( "\r\n", $headers ) . "\r\n\r\n";
     68        $sock = $this->_get_auth_sock( );
     69        if ( ! $sock ) return;
     70        $response = $this->_txrx( $sock, $request );
     71        return $this->parse_response($response);
     72    }
     73
     74    function token_is_valid() {
     75        $info = $this->get_token_info();
     76
     77        if ( $info['code'] == 200 )
     78            return true;
     79
     80        return false;
     81    }
     82
     83    function show_blogs($iter = 0) {
     84        if ( empty($this->blogs) ) {
     85            $headers = array(
     86                "GET /feeds/default/blogs HTTP/1.0",
     87                "Host: www2.blogger.com",
     88                "Authorization: AuthSub token=\"$this->token\""
     89            );
     90            $request = join( "\r\n", $headers ) . "\r\n\r\n";
     91            $sock = $this->_get_blogger_sock( );
     92            if ( ! $sock ) return;
     93            $response = $this->_txrx( $sock, $request );
     94
     95            // Quick and dirty XML mining.
     96            list( $headers, $xml ) = explode( "\r\n\r\n", $response );
     97            $p = xml_parser_create();
     98            xml_parse_into_struct($p, $xml, $vals, $index);
     99            xml_parser_free($p);
     100
     101            $this->title = $vals[$index['TITLE'][0]]['value'];
     102
     103            // Give it a few retries... this step often flakes out the first time.
     104            if ( empty( $index['ENTRY'] ) ) {
     105                if ( $iter < 3 ) {
     106                    return $this->show_blogs($iter + 1);
     107                } else {
     108                    $this->uh_oh(
     109                        __('Trouble signing in'),
     110                        __('We were not able to gain access to your account. Try starting over.'),
     111                        ''
     112                    );
     113                    return false;
     114                }
     115            }
     116
     117            foreach ( $index['ENTRY'] as $i ) {
     118                $blog = array();
     119                while ( ( $tag = $vals[$i] ) && ! ( $tag['tag'] == 'ENTRY' && $tag['type'] == 'close' ) ) {
     120                    if ( $tag['tag'] == 'TITLE' ) {
     121                        $blog['title'] = $tag['value'];
     122                    } elseif ( $tag['tag'] == 'SUMMARY' ) {
     123                        $blog['summary'] == $tag['value'];
     124                    } elseif ( $tag['tag'] == 'LINK' ) {
     125                        if ( $tag['attributes']['REL'] == 'alternate' && $tag['attributes']['TYPE'] == 'text/html' ) {
     126                            $parts = parse_url( $tag['attributes']['HREF'] );
     127                            $blog['host'] = $parts['host'];
     128                        } elseif ( $tag['attributes']['REL'] == 'edit' )
     129                            $blog['gateway'] = $tag['attributes']['HREF'];
     130                    }
     131                    ++$i;
     132                }
     133                if ( ! empty ( $blog ) ) {
     134                    $blog['total_posts'] = $this->get_total_results('posts', $blog['host']);
     135                    $blog['total_comments'] = $this->get_total_results('comments', $blog['host']);
     136                    $blog['mode'] = 'init';
     137                    $this->blogs[] = $blog;
     138                }
     139            }
     140
     141            if ( empty( $this->blogs ) ) {
     142                $this->uh_oh(
     143                    __('No blogs found'),
     144                    __('We were able to log in but there were no blogs. Try a different account next time.'),
     145                    ''
     146                );
     147                return false;
     148            }
     149        }
     150//echo '<pre>'.print_r($this,1).'</pre>';
     151        $start    = js_escape( __('Import') );
     152        $continue = js_escape( __('Continue') );
     153        $stop     = js_escape( __('Importing...') );
     154        $authors  = js_escape( __('Set Authors') );
     155        $loadauth = js_escape( __('Preparing author mapping form...') );
     156        $authhead = js_escape( __('Final Step: Author Mapping') );
     157        $nothing  = js_escape( __('Nothing was imported. Had you already imported this blog?') );
     158        $title    = __('Blogger Blogs');
     159        $name     = __('Blog Name');
     160        $url      = __('Blog URL');
     161        $action   = __('The Magic Button');
     162        $posts    = __('Posts');
     163        $comments = __('Comments');
     164        $noscript = __('This feature requires Javascript but it seems to be disabled. Please enable Javascript and then reload this page. Don\'t worry, you can turn it back off when you\'re done.');
     165
     166        $interval = STATUS_INTERVAL * 1000;
     167
     168        foreach ( $this->blogs as $i => $blog ) {
     169            if ( $blog['mode'] == 'init' )
     170                $value = $start;
     171            elseif ( $blog['mode'] == 'posts' || $blog['mode'] == 'comments' )
     172                $value = $continue;
     173            else
     174                $value = $authors;
     175            $blogtitle = js_escape( $blog['title'] );
     176            $pdone = isset($blog['posts_done']) ? (int) $blog['posts_done'] : 0;
     177            $cdone = isset($blog['comments_done']) ? (int) $blog['comments_done'] : 0;
     178            $init .= "blogs[$i]=new blog($i,'$blogtitle','{$blog['mode']}'," . $this->get_js_status($i) . ');';
     179            $pstat = "<div class='ind' id='pind$i'>&nbsp;</div><div id='pstat$i' class='stat'>$pdone/{$blog['total_posts']}</div>";
     180            $cstat = "<div class='ind' id='cind$i'>&nbsp;</div><div id='cstat$i' class='stat'>$cdone/{$blog['total_comments']}</div>";
     181            $rows .= "<tr id='blog$i'><td class='blogtitle'>$blogtitle</td><td class='bloghost'>{$blog['host']}</td><td class='bar'>$pstat</td><td class='bar'>$cstat</td><td class='submit'><input type='submit' id='submit$i' value='$value' /><input type='hidden' name='blog' value='$i' /></td></tr>\n";
     182        }
     183
     184        echo "<div class='wrap'><h2>$title</h2><noscript>$noscript</noscript><table cellpadding='5px'><thead><td>$name</td><td>$url</td><td>$posts</td><td>$comments</td><td>$action</td></thead>\n$rows</table></form></div>";
     185        echo "
     186        <script type='text/javascript'>
     187            var strings = {cont:'$continue',stop:'$stop',stopping:'$stopping',authors:'$authors',nothing:'$nothing'};
     188            var blogs = {};
     189            function blog(i, title, mode, status){
     190                this.blog   = i;
     191                this.mode   = mode;
     192                this.title  = title;
     193                this.status = status;
     194                this.button = document.getElementById('submit'+this.blog);
     195            };
     196            blog.prototype = {
     197                start: function() {
     198                    this.cont = true;
     199                    this.kick();
     200                    this.check();
     201                },
     202                kick: function() {
     203                    ++this.kicks;
     204                    var i = this.blog;
     205                    jQuery.post('admin.php?import=blogger&noheader=true',{blog:this.blog},function(text,result){blogs[i].kickd(text,result)});
     206                },
     207                check: function() {
     208                    ++this.checks;
     209                    var i = this.blog;
     210                    jQuery.post('admin.php?import=blogger&noheader=true&status=true',{blog:this.blog},function(text,result){blogs[i].checkd(text,result)});
     211                },
     212                kickd: function(text, result) {
     213                    if ( result == 'error' ) {
     214                        // TODO: exception handling
     215                        if ( this.cont )
     216                            setTimeout('blogs['+this.blog+'].kick()', 1000);
     217                    } else {
     218                        if ( text == 'done' ) {
     219                            this.stop();
     220                            this.done();
     221                        } else if ( text == 'nothing' ) {
     222                            this.stop();
     223                            this.nothing();
     224                        } else if ( text == 'continue' ) {
     225                            this.kick();
     226                        } else if ( this.mode = 'stopped' )
     227                            jQuery(this.button).attr('value', strings.cont);
     228                    }
     229                    --this.kicks;
     230                },
     231                checkd: function(text, result) {
     232                    if ( result == 'error' ) {
     233                        // TODO: exception handling
     234                    } else {
     235                        eval('this.status='+text);
     236                        jQuery('#pstat'+this.blog).empty().append(this.status.p1+'/'+this.status.p2);
     237                        jQuery('#cstat'+this.blog).empty().append(this.status.c1+'/'+this.status.c2);
     238                        this.update();
     239                        if ( this.cont || this.kicks > 0 )
     240                            setTimeout('blogs['+this.blog+'].check()', $interval);
     241                    }
     242                    --this.checks;
     243                },
     244                update: function() {
     245                    jQuery('#pind'+this.blog).width(((this.status.p1>0&&this.status.p2>0)?(this.status.p1/this.status.p2*jQuery('#pind'+this.blog).parent().width()):1)+'px');
     246                    jQuery('#cind'+this.blog).width(((this.status.c1>0&&this.status.c2>0)?(this.status.c1/this.status.c2*jQuery('#cind'+this.blog).parent().width()):1)+'px');
     247                },
     248                stop: function() {
     249                    this.cont = false;
     250                },
     251                done: function() {
     252                    this.mode = 'authors';
     253                    jQuery(this.button).attr('value', strings.authors);
     254                },
     255                nothing: function() {
     256                    this.mode = 'nothing';
     257                    jQuery(this.button).remove();
     258                    alert(strings.nothing);
     259                },
     260                getauthors: function() {
     261                    if ( jQuery('div.wrap').length > 1 )
     262                        jQuery('div.wrap').gt(0).remove();
     263                    jQuery('div.wrap').empty().append('<h2>$authhead</h2><h3>' + this.title + '</h3>');
     264                    jQuery('div.wrap').append('<p id=\"auth\">$loadauth</p>');
     265                    jQuery('p#auth').load('index.php?import=blogger&noheader=true&authors=1',{blog:this.blog});
     266                },
     267                init: function() {
     268                    this.update();
     269                    var i = this.blog;
     270                    jQuery(this.button).bind('click', function(){return blogs[i].click();});
     271                    this.kicks = 0;
     272                    this.checks = 0;
     273                },
     274                click: function() {
     275                    if ( this.mode == 'init' || this.mode == 'stopped' || this.mode == 'posts' || this.mode == 'comments' ) {
     276                        this.mode = 'started';
     277                        this.start();
     278                        jQuery(this.button).attr('value', strings.stop);
     279                    } else if ( this.mode == 'started' ) {
     280                        return false; // let it run...
     281                        this.mode = 'stopped';
     282                        this.stop();
     283                        if ( this.checks > 0 || this.kicks > 0 ) {
     284                            this.mode = 'stopping';
     285                            jQuery(this.button).attr('value', strings.stopping);
     286                        } else {
     287                            jQuery(this.button).attr('value', strings.cont);
     288                        }
     289                    } else if ( this.mode == 'authors' ) {
     290                        document.location = 'index.php?import=blogger&authors=1&blog='+this.blog;
     291                        //this.mode = 'authors2';
     292                        //this.getauthors();
     293                    }
     294                    return false;
     295                }
     296            };
     297            $init
     298            jQuery.each(blogs, function(i, me){me.init();});
     299        </script>\n";
     300    }
     301
     302    // Handy function for stopping the script after a number of seconds.
     303    function have_time() {
     304        global $importer_started;
     305        if ( time() - $importer_started > MAX_EXECUTION_TIME )
     306            die('continue');
     307        return true;
     308    }
     309
     310    function get_total_results($type, $host) {
     311        $headers = array(
     312            "GET /feeds/$type/default?max-results=1&start-index=2 HTTP/1.0",
     313            "Host: $host",
     314            "Authorization: AuthSub token=\"$this->token\""
     315        );
     316        $request = join( "\r\n", $headers ) . "\r\n\r\n";
     317        $sock = $this->_get_blogger_sock( $host );
     318        if ( ! $sock ) return;
     319        $response = $this->_txrx( $sock, $request );
     320        $response = $this->parse_response( $response );
     321        $parser = xml_parser_create();
     322        xml_parse_into_struct($parser, $response['body'], $struct, $index);
     323        xml_parser_free($parser);
     324        $total_results = $struct[$index['OPENSEARCH:TOTALRESULTS'][0]]['value'];
     325        return (int) $total_results;
     326    }
     327
     328    function import_blog($blogID) {
     329        global $importing_blog;
     330        $importing_blog = $blogID;
     331
     332        if ( isset($_GET['authors']) )
     333            return print($this->get_author_form());
     334
     335        header('Content-Type: text/plain');
     336
     337        if ( isset($_GET['status']) )
     338            die($this->get_js_status());
     339
     340        if ( isset($_GET['saveauthors']) )
     341            die($this->save_authors());
     342
     343        $blog = $this->blogs[$blogID];
     344        $total_results = $this->get_total_results('posts', $blog['host']);
     345        $this->blogs[$importing_blog]['total_posts'] = $total_results;
     346
     347        $start_index = $total_results - MAX_RESULTS + 1;
     348
     349        if ( isset( $this->blogs[$importing_blog]['posts_start_index'] ) )
     350            $start_index = (int) $this->blogs[$importing_blog]['posts_start_index'];
     351        elseif ( $total_results > MAX_RESULTS )
     352            $start_index = $total_results - MAX_RESULTS + 1;
    21353        else
    22             echo "<p>$incompat</p>";
    23         echo "</div>\n";
    24     }
    25 
    26     // Deletes saved data and redirect.
     354            $start_index = 1;
     355
     356        // This will be positive until we have finished importing posts
     357        if ( $start_index > 0 ) {
     358            // Grab all the posts
     359            $this->blogs[$importing_blog]['mode'] = 'posts';
     360            $query = "start-index=$start_index&max-results=" . MAX_RESULTS;
     361            do {
     362                $index = $struct = $entries = array();
     363                $headers = array(
     364                    "GET /feeds/posts/default?$query HTTP/1.0",
     365                    "Host: {$blog['host']}",
     366                    "Authorization: AuthSub token=\"$this->token\""
     367                );
     368                $request = join( "\r\n", $headers ) . "\r\n\r\n";
     369                $sock = $this->_get_blogger_sock( $blog['host'] );
     370                if ( ! $sock ) return; // TODO: Error handling
     371                $response = $this->_txrx( $sock, $request );
     372
     373                $response = $this->parse_response( $response );
     374
     375                // Extract the entries and send for insertion
     376                preg_match_all( '/<entry[^>]*>.*?<\/entry>/s', $response['body'], $matches );
     377                if ( count( $matches[0] ) ) {
     378                    $entries = array_reverse($matches[0]);
     379                    foreach ( $entries as $entry ) {
     380                        $entry = "<feed>$entry</feed>";
     381                        $AtomParser = new AtomParser();
     382                        $AtomParser->parse( $entry );
     383                        $this->import_post($AtomParser->entry);
     384                        unset($AtomParser);
     385                    }
     386                } else break;
     387
     388                // Get the 'previous' query string which we'll use on the next iteration
     389                $query = '';
     390                $links = preg_match_all('/<link([^>]*)>/', $response['body'], $matches);
     391                if ( count( $matches[1] ) )
     392                    foreach ( $matches[1] as $match )
     393                        if ( preg_match('/rel=.previous./', $match) )
     394                            $query = html_entity_decode( preg_replace('/^.*href=[\'"].*\?(.+)[\'"].*$/', '$1', $match) );
     395
     396                if ( $query ) {
     397                    parse_str($query, $q);
     398                    $this->blogs[$importing_blog]['posts_start_index'] = (int) $q['start-index'];
     399                } else
     400                    $this->blogs[$importing_blog]['posts_start_index'] = 0;
     401                $this->save_vars();
     402            } while ( !empty( $query ) && $this->have_time() );
     403        }
     404
     405        $total_results = $this->get_total_results( 'comments', $blog['host'] );
     406        $this->blogs[$importing_blog]['total_comments'] = $total_results;
     407
     408        if ( isset( $this->blogs[$importing_blog]['comments_start_index'] ) )
     409            $start_index = (int) $this->blogs[$importing_blog]['comments_start_index'];
     410        elseif ( $total_results > MAX_RESULTS )
     411            $start_index = $total_results - MAX_RESULTS + 1;
     412        else
     413            $start_index = 1;
     414
     415        if ( $start_index > 0 ) {
     416            // Grab all the comments
     417            $this->blogs[$importing_blog]['mode'] = 'comments';
     418            $query = "start-index=$start_index&max-results=" . MAX_RESULTS;
     419            do {
     420                $index = $struct = $entries = array();
     421                $headers = array(
     422                    "GET /feeds/comments/default?$query HTTP/1.0",
     423                    "Host: {$blog['host']}",
     424                    "Authorization: AuthSub token=\"$this->token\""
     425                );
     426                $request = join( "\r\n", $headers ) . "\r\n\r\n";
     427                $sock = $this->_get_blogger_sock( $blog['host'] );
     428                if ( ! $sock ) return; // TODO: Error handling
     429                $response = $this->_txrx( $sock, $request );
     430
     431                $response = $this->parse_response( $response );
     432
     433                // Extract the comments and send for insertion
     434                preg_match_all( '/<entry[^>]*>.*?<\/entry>/s', $response['body'], $matches );
     435                if ( count( $matches[0] ) ) {
     436                    $entries = array_reverse( $matches[0] );
     437                    foreach ( $entries as $entry ) {
     438                        $entry = "<feed>$entry</feed>";
     439                        $AtomParser = new AtomParser();
     440                        $AtomParser->parse( $entry );
     441                        $this->import_comment($AtomParser->entry);
     442                        unset($AtomParser);
     443                    }
     444                }
     445
     446                // Get the 'previous' query string which we'll use on the next iteration
     447                $query = '';
     448                $links = preg_match_all('/<link([^>]*)>/', $response['body'], $matches);
     449                if ( count( $matches[1] ) )
     450                    foreach ( $matches[1] as $match )
     451                        if ( preg_match('/rel=.previous./', $match) )
     452                            $query = html_entity_decode( preg_replace('/^.*href=[\'"].*\?(.+)[\'"].*$/', '$1', $match) );
     453
     454                parse_str($query, $q);
     455
     456                $this->blogs[$importing_blog]['comments_start_index'] = (int) $q['start-index'];
     457                $this->save_vars();
     458            } while ( !empty( $query ) && $this->have_time() );
     459        }
     460        $this->blogs[$importing_blog]['mode'] = 'authors';
     461        $this->save_vars();
     462        if ( !$this->blogs[$importing_blog]['posts_done'] && !$this->blogs[$importing_blog]['comments_done'] )
     463            die('nothing');
     464        do_action('import_done', 'blogger');
     465        die('done');
     466    }
     467
     468    function convert_date( $date ) {
     469        preg_match('#([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.[0-9]+)?(Z|[\+|\-][0-9]{2,4}){0,1}#', $date, $date_bits);
     470        $offset = iso8601_timezone_to_offset( $date_bits[7] );
     471        $timestamp = gmmktime($date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1]);
     472        $timestamp -= $offset; // Convert from Blogger local time to GMT
     473        $timestamp += get_option('gmt_offset') * 3600; // Convert from GMT to WP local time
     474        return gmdate('Y-m-d H:i:s', $timestamp);
     475    }
     476
     477    function no_apos( $string ) {
     478        return str_replace( '&apos;', "'", $string);
     479    }
     480
     481    function min_whitespace( $string ) {
     482        return preg_replace( '|\s+|', ' ', $string );
     483    }
     484
     485    function import_post( $entry ) {
     486        global $wpdb, $importing_blog;
     487
     488        // The old permalink is all Blogger gives us to link comments to their posts.
     489        if ( isset( $entry->draft ) )
     490            $rel = 'self';
     491        else
     492            $rel = 'alternate';
     493        foreach ( $entry->links as $link ) {
     494            if ( $link['rel'] == $rel ) {
     495                $parts = parse_url( $link['href'] );
     496                $entry->old_permalink = $parts['path'];
     497                break;
     498            }
     499        }
     500
     501        $post_date    = $this->convert_date( $entry->published );
     502        $post_content = trim( addslashes( $this->no_apos( html_entity_decode( $entry->content ) ) ) );
     503        $post_title   = trim( addslashes( $this->no_apos( $this->min_whitespace( $entry->title ) ) ) );
     504        $post_status  = isset( $entry->draft ) ? 'draft' : 'publish';
     505
     506        // Clean up content
     507        $post_content = preg_replace('|<(/?[A-Z]+)|e', "'<' . strtolower('$1')", $post_content);
     508        $post_content = str_replace('<br>', '<br />', $post_content);
     509        $post_content = str_replace('<hr>', '<hr />', $post_content);
     510
     511        // Checks for duplicates
     512        if (
     513            isset( $this->blogs[$importing_blog]['posts'][$entry->old_permalink] ) ||
     514            post_exists( $post_title, $post_content, $post_date )
     515        ) {
     516            ++$this->blogs[$importing_blog]['posts_skipped'];
     517        } else {
     518            $post = compact('post_date', 'post_content', 'post_title', 'post_status');
     519
     520            $post_id = wp_insert_post($post);
     521
     522            wp_create_categories( array_map( 'addslashes', $entry->categories ), $post_id );
     523
     524            $author = $this->no_apos( strip_tags( $entry->author ) );
     525
     526            add_post_meta( $post_id, 'blogger_blog', $this->blogs[$importing_blog]['host'], true );
     527            add_post_meta( $post_id, 'blogger_author', $author, true );
     528            add_post_meta( $post_id, 'blogger_permalink', $entry->old_permalink, true );
     529
     530            $this->blogs[$importing_blog]['posts'][$entry->old_permalink] = $post_id;
     531            ++$this->blogs[$importing_blog]['posts_done'];
     532        }
     533        $this->save_vars();
     534    }
     535
     536    function import_comment( $entry ) {
     537        global $importing_blog;
     538
     539        // Drop the #fragment and we have the comment's old post permalink.
     540        foreach ( $entry->links as $link ) {
     541            if ( $link['rel'] == 'alternate' ) {
     542                $parts = parse_url( $link['href'] );
     543                $entry->old_permalink = $parts['fragment'];
     544                $entry->old_post_permalink = $parts['path'];
     545                break;
     546            }
     547        }
     548
     549        $comment_post_ID = (int) $this->blogs[$importing_blog]['posts'][$entry->old_post_permalink];
     550        preg_match('#<name>(.+?)</name>.*(?:\<uri>(.+?)</uri>)?#', $entry->author, $matches);
     551        $comment_author  = addslashes( $this->no_apos( strip_tags( (string) $matches[1] ) ) );
     552        $comment_author_url = addslashes( $this->no_apos( strip_tags( (string) $matches[2] ) ) );
     553        $comment_date    = $this->convert_date( $entry->updated );
     554        $comment_content = addslashes( $this->no_apos( html_entity_decode( $entry->content ) ) );
     555
     556        // Clean up content
     557        $comment_content = preg_replace('|<(/?[A-Z]+)|e', "'<' . strtolower('$1')", $comment_content);
     558        $comment_content = str_replace('<br>', '<br />', $comment_content);
     559        $comment_content = str_replace('<hr>', '<hr />', $comment_content);
     560
     561        // Checks for duplicates
     562        if (
     563            isset( $this->blogs[$importing_blog]['comments'][$entry->old_permalink] ) ||
     564            comment_exists( $comment_author, $comment_date )
     565        ) {
     566            ++$this->blogs[$importing_blog]['comments_skipped'];
     567        } else {
     568            $comment = compact('comment_post_ID', 'comment_author', 'comment_author_url', 'comment_date', 'comment_content');
     569
     570            $comment_id = wp_insert_comment($comment);
     571
     572            $this->blogs[$importing_blog]['comments'][$entry->old_permalink] = $comment_id;
     573
     574            ++$this->blogs[$importing_blog]['comments_done'];
     575        }
     576        $this->save_vars();
     577    }
     578
     579    function get_js_status($blog = false) {
     580        global $importing_blog;
     581        if ( $blog === false )
     582            $blog = $this->blogs[$importing_blog];
     583        else
     584            $blog = $this->blogs[$blog];
     585        $p1 = isset( $blog['posts_done'] ) ? (int) $blog['posts_done'] : 0;
     586        $p2 = isset( $blog['total_posts'] ) ? (int) $blog['total_posts'] : 0;
     587        $c1 = isset( $blog['comments_done'] ) ? (int) $blog['comments_done'] : 0;
     588        $c2 = isset( $blog['total_comments'] ) ? (int) $blog['total_comments'] : 0;
     589        return "{p1:$p1,p2:$p2,c1:$c1,c2:$c2}";
     590    }
     591
     592    function get_author_form($blog = false) {
     593        global $importing_blog, $wpdb, $current_user;
     594        if ( $blog === false )
     595            $blog = & $this->blogs[$importing_blog];
     596        else
     597            $blog = & $this->blogs[$blog];
     598
     599        if ( !isset( $blog['authors'] ) ) {
     600            $post_ids = array_values($blog['posts']);
     601            $authors = (array) $wpdb->get_col("SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key = 'blogger_author' AND post_id IN (" . join( ',', $post_ids ) . ")");
     602            $blog['authors'] = array_map(null, $authors, array_fill(0, count($authors), $current_user->ID));
     603            $this->save_vars();
     604        }
     605
     606        $directions = __('All posts were imported with the current user as author. Use this form to move each Blogger user\'s posts to a different WordPress user. You may <a href="users.php">add users</a> and then return to this page and complete the user mapping. This form may be used as many times as you like until you activate the "Restart" function below.');
     607        $heading = __('Author mapping');
     608        $blogtitle = "{$blog['title']} ({$blog['host']})";
     609        $mapthis = __('Blogger username');
     610        $tothis = __('WordPress login');
     611        $submit = js_escape( __('Save Changes &raquo;') );
     612
     613        foreach ( $blog['authors'] as $i => $author )
     614            $rows .= "<tr><td><label for='authors[$i]'>{$author[0]}</label></td><td><select name='authors[$i]' id='authors[$i]'>" . $this->get_user_options($author[1]) . "</select></td></tr>";
     615
     616        return "<div class='wrap'><h2>$heading</h2><h3>$blogtitle</h3><p>$directions</p><form action='index.php?import=blogger&noheader=true&saveauthors=1' method='post'><input type='hidden' name='blog' value='$importing_blog' /><table cellpadding='5'><thead><td>$mapthis</td><td>$tothis</td></thead>$rows<tr><td></td><td class='submit'><input type='submit' class='authorsubmit' value='$submit' /></td></tr></table></form></div>";
     617    }
     618
     619    function get_user_options($current) {
     620        global $wpdb, $importer_users;
     621        if ( ! isset( $importer_users ) )
     622            $importer_users = (array) get_users_of_blog();
     623
     624        foreach ( $importer_users as $user ) {
     625            $sel = ( $user->user_id == $current ) ? " selected='selected'" : '';
     626            $options .= "<option value='$user->user_id'$sel>$user->display_name</option>";
     627        }
     628
     629        return $options;
     630    }
     631
     632    function save_authors() {
     633        global $importing_blog, $wpdb;
     634        $authors = (array) $_POST['authors'];
     635
     636        $host = $this->blogs[$importing_blog]['host'];
     637
     638        // Get an array of posts => authors
     639        $post_ids = (array) $wpdb->get_col("SELECT post_id FROM $wpdb->postmeta WHERE meta_key = 'blogger_blog' AND meta_value = '$host'");
     640        $post_ids = join( ',', $post_ids );
     641        $results = (array) $wpdb->get_results("SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = 'blogger_author' AND post_id IN ($post_ids)");
     642        foreach ( $results as $row )
     643            $authors_posts[$row->post_id] = $row->meta_value;
     644
     645        foreach ( $authors as $author => $user_id ) {
     646            $user_id = (int) $user_id;
     647
     648            // Skip authors that haven't been changed
     649            if ( $user_id == $this->blogs[$importing_blog]['authors'][$author][1] )
     650                continue;
     651
     652            // Get a list of the selected author's posts
     653            $post_ids = (array) array_keys( $authors_posts, $this->blogs[$importing_blog]['authors'][$author][0] );
     654            $post_ids = join( ',', $post_ids);
     655
     656            $wpdb->query("UPDATE $wpdb->posts SET post_author = $user_id WHERE id IN ($post_ids)");
     657            $this->blogs[$importing_blog]['authors'][$author][1] = $user_id;
     658        }
     659        $this->save_vars();
     660
     661        wp_redirect('edit.php');
     662    }
     663
     664    function _get_auth_sock() {
     665        // Connect to https://www.google.com
     666        if ( !$sock = @ fsockopen('ssl://www.google.com', 443, $errno, $errstr) ) {
     667            $this->uh_oh(
     668                __('Could not connect to https://www.google.com'),
     669                __('There was a problem opening a secure connection to Google. This is what went wrong:'),
     670                "$errstr ($errno)"
     671            );
     672            return false;
     673        }
     674        return $sock;
     675    }
     676
     677    function _get_blogger_sock($host = 'www2.blogger.com') {
     678        if ( !$sock = @ fsockopen($host, 80, $errno, $errstr) ) {
     679            $this->uh_oh(
     680                sprintf( __('Could not connect to %s'), $host ),
     681                __('There was a problem opening a connection to Blogger. This is what went wrong:'),
     682                "$errstr ($errno)"
     683            );
     684            return false;
     685        }
     686        return $sock;
     687    }
     688
     689    function _txrx( $sock, $request ) {
     690        fwrite( $sock, $request );
     691        while ( ! feof( $sock ) )
     692            $response .= @ fread ( $sock, 8192 );
     693        fclose( $sock );
     694        return $response;
     695    }
     696
     697    function revoke($token) {
     698        $headers = array(
     699            "GET /accounts/AuthSubRevokeToken HTTP/1.0",
     700            "Authorization: AuthSub token=\"$token\""
     701        );
     702        $request = join( "\r\n", $headers ) . "\r\n\r\n";
     703        $sock = $this->_get_auth_sock( );
     704        if ( ! $sock ) return false;
     705        $this->_txrx( $sock, $request );
     706    }
     707
    27708    function restart() {
    28         delete_option('import-blogger');
    29         wp_redirect("admin.php?import=blogger");
    30         die();
    31     }
    32 
    33     // Generates a string that will make the page reload in a specified interval.
    34     function refresher($msec) {
    35         if ( $msec )
    36             return "<html><head><script type='text/javascript'>window.onload=setTimeout('window.location.reload()', $msec);</script>\n</head>\n<body>\n";
    37         else
    38             return "<html><head><script type='text/javascript'>window.onload=window.location.reload();</script>\n</head>\n<body>\n";
     709        global $wpdb;
     710        $options = get_option( 'blogger_importer' );
     711
     712        if ( isset( $options['token'] ) )
     713            $this->revoke( $options['token'] );
     714
     715        delete_option('blogger_importer');
     716        $wpdb->query("DELETE FROM $wpdb->postmeta WHERE meta_key = 'blogger_author'");
     717        wp_redirect('?import=blogger');
    39718    }
    40719
     
    63742    }
    64743
    65     // Prints a form for the user to enter Blogger creds.
    66     function login_form($text='') {
    67         echo '<h1>' . __('Log in to Blogger') . "</h1>\n$text\n";
    68         echo '<form method="post" action="admin.php?import=blogger&amp;noheader=true&amp;step=0"><table><tr><td>' . __('Username') . ':</td><td><input type="text" name="user" /></td></tr><tr><td>' . __('Password') . ':</td><td><input type="password" name="pass" /></td><td><input type="submit" value="' . __('Start') . '" /></td></tr></table></form>';
    69         die;
    70     }
    71 
    72     // Sends creds to Blogger, returns the session cookies an array of headers.
    73     function login_blogger($user, $pass) {
    74         $_url = 'http://www.blogger.com/login.do';
    75         $params = "username=$user&password=$pass";
    76         $ch = curl_init();
    77         curl_setopt($ch, CURLOPT_POST,1);
    78         curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
    79         curl_setopt($ch, CURLOPT_URL,$_url);
    80         curl_setopt($ch, CURLOPT_USERAGENT, 'Blogger Exporter');
    81         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
    82         curl_setopt($ch, CURLOPT_HEADER,1);
    83         curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    84         $response = curl_exec ($ch);
    85 
    86         $response = $this->parse_response($response);
    87 
    88         sleep(1);
    89 
    90         return $response['cookies'];
    91     }
    92 
    93     // Requests page from Blogger, returns the response array.
    94     function get_blogger($url, $header = '', $user=false, $pass=false) {
    95         $ch = curl_init();
    96         if ($user && $pass) curl_setopt($ch, CURLOPT_USERPWD,"{$user}:{$pass}");
    97         curl_setopt($ch, CURLOPT_URL,$url);
    98         curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    99         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    100         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    101         curl_setopt($ch, CURLOPT_USERAGENT, 'Blogger Exporter');
    102         curl_setopt($ch, CURLOPT_HEADER,1);
    103         if (is_array($header)) curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    104         $response = curl_exec ($ch);
    105 
    106         $response = $this->parse_response($response);
    107         $response['url'] = $url;
    108 
    109         if (curl_errno($ch)) {
    110             print curl_error($ch);
    111         } else {
    112             curl_close($ch);
    113         }
    114 
    115         return $response;
    116     }
    117 
    118     // Posts data to Blogger, returns response array.
    119     function post_blogger($url, $header = false, $paramary = false, $parse=true) {
    120         $params = '';
    121         if ( is_array($paramary) ) {
    122             foreach($paramary as $key=>$value)
    123                 if($key && $value != '')
    124                     $params.=$key."=".urlencode(stripslashes($value))."&";
    125         }
    126         if ($user && $pass) $params .= "username=$user&password=$pass";
    127         $params = trim($params,'&');
    128         $ch = curl_init();
    129         curl_setopt($ch, CURLOPT_POST,1);
    130         curl_setopt($ch, CURLOPT_POSTFIELDS,$params);
    131         if ($user && $pass) curl_setopt($ch, CURLOPT_USERPWD,"{$user}:{$pass}");
    132         curl_setopt($ch, CURLOPT_URL,$url);
    133         curl_setopt($ch, CURLOPT_USERAGENT, 'Blogger Exporter');
    134         curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    135         curl_setopt($ch, CURLOPT_HEADER,$parse);
    136         curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    137         if ($header) curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    138         $response = curl_exec ($ch);
    139 
    140         if ($parse) {
    141             $response = $this->parse_response($response);
    142             $response['url'] = $url;
    143             return $response;
    144         }
    145 
    146         return $response;
    147     }
    148 
    149     // Prints the list of blogs for import.
    150     function show_blogs() {
    151         global $import;
    152         echo '<h1>' . __('Selecting a Blog') . "</h1>\n<ul>";
    153         foreach ( $this->import['blogs'] as $blog ) {
    154             if (9 == $blog['nextstep']) $status = "100%";
    155             elseif (8 == $blog['nextstep']) $status = "90%";
    156             elseif (7 == $blog['nextstep']) $status = "82.5%";
    157             elseif (6 == $blog['nextstep']) $status = "75%";
    158             elseif (5 == $blog['nextstep']) $status = "57%";
    159             elseif (4 == $blog['nextstep']) $status = "28%";
    160             elseif (3 == $blog['nextstep']) $status = "14%";
    161             else $status = "0%";
    162             echo "\t<li><a href='admin.php?import=blogger&amp;noheader=true&amp;blog={$blog['id']}'>{$blog['title']}</a> $status</li>\n";
    163         }
    164         die("</ul>\n");
    165     }
    166 
    167     // Publishes.
    168     function publish_blogger($i, $text) {
    169         $head = $this->refresher(2000) . "<h1>$text</h1>\n";
    170         if ( ! strstr($this->import['blogs'][$_GET['blog']]['publish'][$i], 'http') ) {
    171             // First call. Start the publish process with a fresh set of cookies.
    172             $this->import['cookies'] = $this->login_blogger($this->import['user'], $this->import['pass']);
    173             update_option('import-blogger', $this->import);
    174             $paramary = array('blogID' => $_GET['blog'], 'all' => '1', 'republishAll' => 'Republish Entire Blog', 'publish' => '1', 'redirectUrl' => "/publish.do?blogID={$_GET['blog']}&inprogress=true");
    175 
    176             $response = $this->post_blogger("http://www.blogger.com/publish.do?blogID={$_GET['blog']}", $this->import['cookies'], $paramary);
    177             if ( $response['code'] == '302' ) {
    178                 $url = str_replace('publish.g', 'publish-body.g', $response['header']['Location']);
    179                 $this->import['blogs'][$_GET['blog']]['publish'][$i] = $url;
    180                 update_option('import-blogger', $this->import);
    181                 $response = $this->get_blogger($url, $this->import['cookies']);
    182                 preg_match('#<p class="progressIndicator">.*</p>#U', $response['body'], $matches);
    183                 $progress = $matches[0];
    184                 die($head . $progress);
    185             } else {
    186                 $this->import['blogs'][$_GET['blog']]['publish'][$i] = false;
    187                 update_option('import-blogger', $this->import);
    188                 die($head);
    189             }
    190         } else {
    191             // Subsequent call. Keep checking status until Blogger reports publish complete.
    192             $url = $this->import['blogs'][$_GET['blog']]['publish'][$i];
    193             $response = $this->get_blogger($url, $this->import['cookies']);
    194             if ( preg_match('#<p class="progressIndicator">.*</p>#U', $response['body'], $matches) ) {
    195                 $progress = $matches[0];
    196                 if ( strstr($progress, '100%') ) {
    197                     $this->set_next_step($i);
    198                     $progress .= '<p>'.__('Moving on...').'</p>';
    199                 }
    200                 die($head . $progress);
    201             } else {
    202                 $this->import['blogs'][$_GET['blog']]['publish'][$i] = false;
    203                 update_option('import-blogger', $this->import);
    204                 die("$head<p>" . __('Trying again...') . '</p>');
    205             }
    206         }
    207     }
    208 
    209     // Sets next step, saves options
    210     function set_next_step($step) {
    211         $this->import['blogs'][$_GET['blog']]['nextstep'] = $step;
    212         update_option('import-blogger', $this->import);
    213     }
    214 
    215     // Redirects to next step
    216     function do_next_step() {
    217         wp_redirect("admin.php?import=blogger&noheader=true&blog={$_GET['blog']}");
    218         die();
    219     }
    220 
    221     // Step 0: Do Blogger login, get blogid/title pairs.
    222     function do_login() {
    223         if ( ( ! $this->import['user'] && ! is_array($this->import['cookies']) ) ) {
    224             // The user must provide a Blogger username and password.
    225             if ( ! ( $_POST['user'] && $_POST['pass'] ) ) {
    226                 $this->login_form(__('The script will log into your Blogger account, change some settings so it can read your blog, and restore the original settings when it\'s done. Here\'s what you do:').'</p><ol><li>'.__('Back up your Blogger template.').'</li><li>'.__('Back up any other Blogger settings you might need later.').'</li><li>'.__('Log out of Blogger').'</li><li>'.__('Log in <em>here</em> with your Blogger username and password.').'</li><li>'.__('On the next screen, click one of your Blogger blogs.').'</li><li>'.__('Do not close this window or navigate away until the process is complete.').'</li></ol>');
    227             }
    228 
    229             // Try logging in. If we get an array of cookies back, we at least connected.
    230             $this->import['cookies'] = $this->login_blogger($_POST['user'], $_POST['pass']);
    231             if ( !is_array( $this->import['cookies'] ) ) {
    232                 $this->login_form(__('Login failed. Please enter your credentials again.'));
    233             }
    234 
    235             // Save the password so we can log the browser in when it's time to publish.
    236             $this->import['pass'] = $_POST['pass'];
    237             $this->import['user'] = $_POST['user'];
    238 
    239             // Get the Blogger welcome page and scrape the blog numbers and names from it
    240             $response = $this->get_blogger('http://www.blogger.com/home', $this->import['cookies']);
    241             if (! stristr($response['body'], 'signed in as') ) $this->login_form(__('Login failed. Please re-enter your username and password.'));
    242             $blogsary = array();
    243             preg_match_all('#posts\.g\?blogID=(\d+)">([^<]+)</a>#U', $response['body'], $blogsary);
    244             if ( ! count( $blogsary[1] < 1 ) )
    245                 wp_die(__('No blogs found for this user.'));
    246             $this->import['blogs'] = array();
    247             $template = '<MainPage><br /><br /><br /><p>'.__('Are you looking for %title%? It is temporarily out of service. Please try again in a few minutes. Meanwhile, discover <a href="http://wordpress.org/">a better blogging tool</a>.').'</p><BloggerArchives><a class="archive" href="<$BlogArchiveURL$>"><$BlogArchiveName$></a><br /></BloggerArchives></MainPage><ArchivePage><Blogger><wordpresspost><$BlogItemDateTime$>|W|P|<$BlogItemAuthorNickname$>|W|P|<$BlogItemBody$>|W|P|<$BlogItemNumber$>|W|P|<$BlogItemTitle$>|W|P|<$BlogItemAuthorEmail$><BlogItemCommentsEnabled><BlogItemComments><wordpresscomment><$BlogCommentDateTime$>|W|P|<$BlogCommentAuthor$>|W|P|<$BlogCommentBody$></BlogItemComments></BlogItemCommentsEnabled></Blogger></ArchivePage>';
    248             foreach ( $blogsary[1] as $key => $id ) {
    249                 // Define the required Blogger options.
    250                 $blog_opts = array(
    251                     'blog-options-basic' => false,
    252                     'blog-options-archiving' => array('archiveFrequency' => 'm'),
    253                     'blog-publishing' => array('publishMode'=>'0', 'blogID' => "$id", 'subdomain' => mt_rand().mt_rand(), 'pingWeblogs' => 'false'),
    254                     'blog-formatting' => array('timeStampFormat' => '0', 'encoding'=>'UTF-8', 'convertLineBreaks'=>'false', 'floatAlignment'=>'false'),
    255                     'blog-comments' => array('commentsTimeStampFormat' => '0'),
    256                     'template-edit' => array( 'templateText' =>  str_replace('%title%', trim($blogsary[2][$key]), $template) )
    257                 );
    258 
    259                 // Build the blog options array template
    260                 foreach ($blog_opts as $blog_opt => $modify)
    261                     $new_opts["$blog_opt"] = array('backup'=>false, 'modify' => $modify, 'error'=>false);
    262 
    263                 $this->import['blogs']["$id"] = array(
    264                     'id' => $id,
    265                     'title' => trim($blogsary[2][$key]),
    266                     'options' => $new_opts,
    267                     'url' => false,
    268                     'publish_cookies' => false,
    269                     'published' => false,
    270                     'archives' => false,
    271                     'lump_authors' => false,
    272                     'newusers' => array(),
    273                     'nextstep' => 2
    274                 );
    275             }
    276             update_option('import-blogger', $this->import);
    277             wp_redirect("admin.php?import=blogger&noheader=true&step=1");
    278         }
    279         die();
    280     }
    281 
    282     // Step 1: Select one of the blogs belonging to the user logged in.
    283     function select_blog() {
    284         if ( is_array($this->import['blogs']) ) {
    285             $this->show_blogs();
    286             die();
    287         } else {
    288             $this->restart();
    289         }
    290     }
    291 
    292     // Step 2: Backup the Blogger options pages, updating some of them.
    293     function backup_settings() {
    294         $output.= '<h1>'.__('Backing up Blogger options')."</h1>\n";
    295         $form = false;
    296         foreach ($this->import['blogs'][$_GET['blog']]['options'] as $blog_opt => $optary) {
    297             if ( $blog_opt == $_GET['form'] ) {
    298                 // Save the posted form data
    299                 $this->import['blogs'][$_GET['blog']]['options']["$blog_opt"]['backup'] = $_POST;
    300                 update_option('import-blogger',$this->import);
    301 
    302                 // Post the modified form data to Blogger
    303                 if ( $optary['modify'] ) {
    304                     $posturl = "http://www.blogger.com/{$blog_opt}.do";
    305                     $headers = array_merge($this->import['blogs'][$_GET['blog']]['options']["$blog_opt"]['cookies'], $this->import['cookies']);
    306                     if ( 'blog-publishing' == $blog_opt ) {
    307                         if ( $_POST['publishMode'] > 0 ) {
    308                             $response = $this->get_blogger("http://www.blogger.com/blog-publishing.g?blogID={$_GET['blog']}&publishMode=0", $headers);
    309                             if ( $response['code'] >= 400 )
    310                                 wp_die('<h2>'.__('Failed attempt to change publish mode from FTP to BlogSpot.').'</h2><pre>' . addslashes(print_r($headers, 1)) . addslashes(print_r($response, 1)) . '</pre>');
    311                             $this->import['blogs'][$_GET['blog']]['url'] = 'http://' . $optary['modify']['subdomain'] . '.blogspot.com/';
    312                             sleep(2);
    313                         } else {
    314                             $this->import['blogs'][$_GET['blog']]['url'] = 'http://' . $_POST['subdomain'] . '.blogspot.com/';
    315                             update_option('import-blogger', $this->import);
    316                             $output .= "<del><p>$blog_opt</p></del>\n";
    317                             continue;
    318                         }
    319                         $paramary = $optary['modify'];
    320                     } else {
    321                         $paramary = array_merge($_POST, $optary['modify']);
    322                     }
    323                     $response = $this->post_blogger($posturl, $headers, $paramary);
    324                     if ( $response['code'] >= 400 || strstr($response['body'], 'There are errors on this form') )
    325                         wp_die('<p>'.__('Error on form submission. Retry or reset the importer.').'</p>' . addslashes(print_r($response, 1)));
    326                 }
    327                 $output .= "<del><p>$blog_opt</p></del>\n";
    328             } elseif ( is_array($this->import['blogs'][$_GET['blog']]['options']["$blog_opt"]['backup']) ) {
    329                 // This option set has already been backed up.
    330                 $output .= "<del><p>$blog_opt</p></del>\n";
    331             } elseif ( ! $form ) {
    332                 // This option page needs to be downloaded and given to the browser for submission back to this script.
    333                 $response = $this->get_blogger("http://www.blogger.com/{$blog_opt}.g?blogID={$_GET['blog']}", $this->import['cookies']);
    334                 $this->import['blogs'][$_GET['blog']]['options']["$blog_opt"]['cookies'] = $response['cookies'];
    335                 update_option('import-blogger',$this->import);
    336                 $body = $response['body'];
    337                 $body = preg_replace("|\<!DOCTYPE.*\<body[^>]*>|ms","",$body);
    338                 $body = preg_replace("|/?{$blog_opt}.do|","admin.php?import=blogger&amp;noheader=true&amp;step=2&amp;blog={$_GET['blog']}&amp;form={$blog_opt}",$body);
    339                 $body = str_replace("name='submit'","name='supermit'",$body);
    340                 $body = str_replace('name="submit"','name="supermit"',$body);
    341                 $body = str_replace('</body>','',str_replace('</html>','',$body));
    342                 $form = "<div style='height:0px;width:0px;overflow:hidden;'>";
    343                 $form.= $body;
    344                 $form.= "</div><script type='text/javascript'>forms=document.getElementsByTagName('form');for(i=0;i<forms.length;i++){if(forms[i].action.search('{$blog_opt}')){forms[i].submit();break;}}</script>";
    345                 $output.= '<p>'.sprintf(__('<strong>%s</strong> in progress, please wait...'), $blog_opt)."</p>\n";
    346             } else {
    347                 $output.= "<p>$blog_opt</p>\n";
    348             }
    349         }
    350         if ( $form )
    351             die($output . $form);
    352 
    353         $this->set_next_step(4);
    354         $this->do_next_step();
    355     }
    356 
    357     // Step 3: Cancelled :-)
    358 
    359     // Step 4: Publish with the new template and settings.
    360     function publish_blog() {
    361         $this->publish_blogger(5, __('Publishing with new template and options'));
    362     }
    363 
    364     // Step 5: Get the archive URLs from the new blog.
    365     function get_archive_urls() {
    366         $bloghtml = $this->get_blogger($this->import['blogs'][$_GET['blog']]['url']);
    367         if (! strstr($bloghtml['body'], '<a class="archive"') )
    368             wp_die(__('Your Blogger blog did not take the new template or did not respond.'));
    369         preg_match_all('#<a class="archive" href="([^"]*)"#', $bloghtml['body'], $archives);
    370         foreach ($archives[1] as $archive) {
    371             $this->import['blogs'][$_GET['blog']]['archives'][$archive] = false;
    372         }
    373         $this->set_next_step(6);
    374         $this->do_next_step();
    375     }
    376 
    377     // Step 6: Get each monthly archive, import it, mark it done.
    378     function get_archive() {
    379         global $wpdb;
    380         $output = '<h2>'.__('Importing Blogger archives into WordPress').'</h2>';
    381         $did_one = false;
    382         $post_array = $posts = array();
    383         foreach ( $this->import['blogs'][$_GET['blog']]['archives'] as $url => $status ) {
    384             $archivename = substr(basename($url),0,7);
    385             if ( $status || $did_one ) {
    386                 $foo = 'bar';
    387                 // Do nothing.
    388             } else {
    389                 // Import the selected month
    390                 $postcount = 0;
    391                 $skippedpostcount = 0;
    392                 $commentcount = 0;
    393                 $skippedcommentcount = 0;
    394                 $status = __('in progress...');
    395                 $this->import['blogs'][$_GET['blog']]['archives']["$url"] = $status;
    396                 update_option('import-blogger', $import);
    397                 $archive = $this->get_blogger($url);
    398                 if ( $archive['code'] > 200 )
    399                     continue;
    400                 $posts = explode('<wordpresspost>', $archive['body']);
    401                 for ($i = 1; $i < count($posts); $i = $i + 1) {
    402                     $postparts = explode('<wordpresscomment>', $posts[$i]);
    403                     $postinfo = explode('|W|P|', $postparts[0]);
    404                     $post_date = $postinfo[0];
    405                     $post_content = $postinfo[2];
    406                     // Don't try to re-use the original numbers
    407                     // because the new, longer numbers are too
    408                     // big to handle as ints.
    409                     //$post_number = $postinfo[3];
    410                     $post_title = ( $postinfo[4] != '' ) ? $postinfo[4] : $postinfo[3];
    411                     $post_author_name = $wpdb->escape(trim($postinfo[1]));
    412                     $post_author_email = $postinfo[5] ? $postinfo[5] : 'user@wordpress.org';
    413 
    414                     if ( $this->lump_authors ) {
    415                         // Ignore Blogger authors. Use the current user_ID for all posts imported.
    416                         $post_author = $GLOBALS['user_ID'];
    417                     } else {
    418                         // Add a user for each new author encountered.
    419                         if (! username_exists($post_author_name) ) {
    420                             $user_login = $wpdb->escape($post_author_name);
    421                             $user_email = $wpdb->escape($post_author_email);
    422                             $user_password = substr(md5(uniqid(microtime())), 0, 6);
    423                             $result = wp_create_user( $user_login, $user_password, $user_email );
    424                             $status.= sprintf(__('Registered user <strong>%s</strong>.'), $user_login);
    425                             $this->import['blogs'][$_GET['blog']]['newusers'][] = $user_login;
    426                         }
    427                         $userdata = get_userdatabylogin( $post_author_name );
    428                         $post_author = $userdata->ID;
    429                     }
    430                     $post_date = explode(' ', $post_date);
    431                     $post_date_Ymd = explode('/', $post_date[0]);
    432                     $postyear = $post_date_Ymd[2];
    433                     $postmonth = zeroise($post_date_Ymd[0], 2);
    434                     $postday = zeroise($post_date_Ymd[1], 2);
    435                     $post_date_His = explode(':', $post_date[1]);
    436                     $posthour = zeroise($post_date_His[0], 2);
    437                     $postminute = zeroise($post_date_His[1], 2);
    438                     $postsecond = zeroise($post_date_His[2], 2);
    439 
    440                     if (($post_date[2] == 'PM') && ($posthour != '12'))
    441                         $posthour = $posthour + 12;
    442                     else if (($post_date[2] == 'AM') && ($posthour == '12'))
    443                         $posthour = '00';
    444 
    445                     $post_date = "$postyear-$postmonth-$postday $posthour:$postminute:$postsecond";
    446 
    447                     $post_content = addslashes($post_content);
    448                     $post_content = str_replace(array('<br>','<BR>','<br/>','<BR/>','<br />','<BR />'), "\n", $post_content); // the XHTML touch... ;)
    449 
    450                     $post_title = addslashes($post_title);
    451 
    452                     $post_status = 'publish';
    453 
    454                     if ( $ID = post_exists($post_title, '', $post_date) ) {
    455                         $post_array[$i]['ID'] = $ID;
    456                         $skippedpostcount++;
    457                     } else {
    458                         $post_array[$i]['post'] = compact('post_author', 'post_content', 'post_title', 'post_category', 'post_author', 'post_date', 'post_status');
    459                         $post_array[$i]['comments'] = false;
    460                     }
    461 
    462                     // Import any comments attached to this post.
    463                     if ($postparts[1]) :
    464                     for ($j = 1; $j < count($postparts); $j = $j + 1) {
    465                         $commentinfo = explode('|W|P|', $postparts[$j]);
    466                         $comment_date = explode(' ', $commentinfo[0]);
    467                         $comment_date_Ymd = explode('/', $comment_date[0]);
    468                         $commentyear = $comment_date_Ymd[2];
    469                         $commentmonth = zeroise($comment_date_Ymd[0], 2);
    470                         $commentday = zeroise($comment_date_Ymd[1], 2);
    471                         $comment_date_His = explode(':', $comment_date[1]);
    472                         $commenthour = zeroise($comment_date_His[0], 2);
    473                         $commentminute = zeroise($comment_date_His[1], 2);
    474                         $commentsecond = '00';
    475                         if (($comment_date[2] == 'PM') && ($commenthour != '12'))
    476                             $commenthour = $commenthour + 12;
    477                         else if (($comment_date[2] == 'AM') && ($commenthour == '12'))
    478                             $commenthour = '00';
    479                         $comment_date = "$commentyear-$commentmonth-$commentday $commenthour:$commentminute:$commentsecond";
    480                         $comment_author = addslashes(strip_tags($commentinfo[1]));
    481                         if ( strpos($commentinfo[1], 'a href') ) {
    482                             $comment_author_parts = explode('&quot;', htmlentities($commentinfo[1]));
    483                             $comment_author_url = $comment_author_parts[1];
    484                         } else $comment_author_url = '';
    485                         $comment_content = $commentinfo[2];
    486                         $comment_content = str_replace(array('<br>','<BR>','<br/>','<BR/>','<br />','<BR />'), "\n", $comment_content);
    487                         $comment_approved = 1;
    488                         if ( comment_exists($comment_author, $comment_date) ) {
    489                             $skippedcommentcount++;
    490                         } else {
    491                             $comment = compact('comment_author', 'comment_author_url', 'comment_date', 'comment_content', 'comment_approved');
    492                             $post_array[$i]['comments'][$j] = wp_filter_comment($comment);
    493                         }
    494                         $commentcount++;
    495                     }
    496                     endif;
    497                     $postcount++;
    498                 }
    499                 if ( count($post_array) ) {
    500                     krsort($post_array);
    501                     foreach($post_array as $post) {
    502                         if ( ! $comment_post_ID = $post['ID'] )
    503                             $comment_post_ID = wp_insert_post($post['post']);
    504                         if ( $post['comments'] ) {
    505                             foreach ( $post['comments'] as $comment ) {
    506                                 $comment['comment_post_ID'] = $comment_post_ID;
    507                                 wp_insert_comment($comment);
    508                             }
    509                         }
    510                     }
    511                 }
    512                 $status = sprintf(__('%s post(s) parsed, %s skipped...'), $postcount,  $skippedpostcount).' '.
    513                     sprintf(__('%s comment(s) parsed, %s skipped...'), $commentcount, $skippedcommentcount).' '.
    514                     ' <strong>'.__('Done').'</strong>';
    515                 $import = $this->import;
    516                 $import['blogs'][$_GET['blog']]['archives']["$url"] = $status;
    517                 update_option('import-blogger', $import);
    518                 $did_one = true;
    519             }
    520             $output.= "<p>$archivename $status</p>\n";
    521         }
    522         if ( ! $did_one )
    523             $this->set_next_step(7);
    524         die( $this->refresher(1000) . $output );
    525     }
    526 
    527     // Step 7: Restore the backed-up settings to Blogger
    528     function restore_settings() {
    529         $output = '<h1>'.__('Restoring your Blogger options')."</h1>\n";
    530         $did_one = false;
    531         // Restore options in reverse order.
    532         if ( ! $this->import['reversed'] ) {
    533             $this->import['blogs'][$_GET['blog']]['options'] = array_reverse($this->import['blogs'][$_GET['blog']]['options'], true);
    534             $this->import['reversed'] = true;
    535             update_option('import-blogger', $this->import);
    536         }
    537         foreach ( $this->import['blogs'][$_GET['blog']]['options'] as $blog_opt => $optary ) {
    538             if ( $did_one ) {
    539                 $output .= "<p>$blog_opt</p>\n";
    540             } elseif ( $optary['restored'] || ! $optary['modify'] ) {
    541                 $output .= "<p><del>$blog_opt</del></p>\n";
    542             } else {
    543                 $posturl = "http://www.blogger.com/{$blog_opt}.do";
    544                 $headers = array_merge($this->import['blogs'][$_GET['blog']]['options']["$blog_opt"]['cookies'], $this->import['cookies']);
    545                 if ( 'blog-publishing' == $blog_opt) {
    546                     if ( $optary['backup']['publishMode'] > 0 ) {
    547                         $response = $this->get_blogger("http://www.blogger.com/blog-publishing.g?blogID={$_GET['blog']}&publishMode={$optary['backup']['publishMode']}", $headers);
    548                         sleep(2);
    549                         if ( $response['code'] >= 400 )
    550                             wp_die('<h1>'.__('Error restoring publishMode').'</h1><p>'.__('Please tell the devs.').'</p>' . addslashes(print_r($response, 1)) );
    551                     }
    552                 }
    553                 if ( $optary['backup'] != $optary['modify'] ) {
    554                     $response = $this->post_blogger($posturl, $headers, $optary['backup']);
    555                     if ( $response['code'] >= 400 || strstr($response['body'], 'There are errors on this form') ) {
    556                         $this->import['blogs'][$_GET['blog']]['options']["$blog_opt"]['error'] = true;
    557                         update_option('import-blogger', $this->import);
    558                         $output .= sprintf(__('%s failed. Trying again.'), "<p><strong>$blog_opt</strong> ").'</p>';
    559                     } else {
    560                         $this->import['blogs'][$_GET['blog']]['options']["$blog_opt"]['restored'] = true;
    561                         update_option('import-blogger', $this->import);
    562                         $output .= sprintf(__('%s restored.'), "<p><strong>$blog_opt</strong> ").'</p>';
    563                     }
    564                 }
    565                 $did_one = true;
    566             }
    567         }
    568 
    569         if ( $did_one ) {
    570             die( $this->refresher(1000) . $output );
    571         } elseif ( $this->import['blogs'][$_GET['blog']]['options']['blog-publishing']['backup']['publishMode'] > 0 ) {
    572             $this->set_next_step(9);
    573         } else {
    574             $this->set_next_step(8);
    575         }
    576 
    577         $this->do_next_step();
    578     }
    579 
    580     // Step 8: Republish, all back to normal
    581     function republish_blog() {
    582         $this->publish_blogger(9, __('Publishing with original template and options'));
    583     }
    584 
    585744    // Step 9: Congratulate the user
    586745    function congrats() {
     746        $blog = (int) $_GET['blog'];
    587747        echo '<h1>'.__('Congratulations!').'</h1><p>'.__('Now that you have imported your Blogger blog into WordPress, what are you going to do? Here are some suggestions:').'</p><ul><li>'.__('That was hard work! Take a break.').'</li>';
    588748        if ( count($this->import['blogs']) > 1 )
    589749            echo '<li>'.__('In case you haven\'t done it already, you can import the posts from your other blogs:'). $this->show_blogs() . '</li>';
    590         if ( $n = count($this->import['blogs'][$_GET['blog']]['newusers']) )
     750        if ( $n = count($this->import['blogs'][$blog]['newusers']) )
    591751            echo '<li>'.sprintf(__('Go to <a href="%s" target="%s">Authors &amp; Users</a>, where you can modify the new user(s) or delete them. If you want to make all of the imported posts yours, you will be given that option when you delete the new authors.'), 'users.php', '_parent').'</li>';
    592         echo '<li>'.__('For security, click the link below to reset this importer. That will clear your Blogger credentials and options from the database.').'</li>';
     752        echo '<li>'.__('For security, click the link below to reset this importer.').'</li>';
    593753        echo '</ul>';
    594754    }
     
    596756    // Figures out what to do, then does it.
    597757    function start() {
    598         if ( $_GET['restart'] == 'true' ) {
     758        if ( isset($_POST['restart']) )
    599759            $this->restart();
    600         }
    601 
    602         if ( isset($_GET['noheader']) ) {
    603             header('Content-Type: text/html; charset=utf-8');
    604 
    605             $this->import = get_option('import-blogger');
    606 
    607             if ( false === $this->import ) {
    608                 $step = 0;
    609             } elseif ( isset($_GET['step']) ) {
    610                 $step = (int) $_GET['step'];
    611             } elseif ( isset($_GET['blog']) && isset($this->import['blogs'][$_GET['blog']]['nextstep']) ) {
    612                 $step = $this->import['blogs'][$_GET['blog']]['nextstep'];
    613             } elseif ( is_array($this->import['blogs']) ) {
    614                 $step = 1;
     760
     761        $options = get_option('blogger_importer');
     762
     763        if ( is_array($options) )
     764            foreach ( $options as $key => $value )
     765                $this->$key = $value;
     766
     767        if ( isset( $_REQUEST['blog'] ) ) {
     768            $blog = is_array($_REQUEST['blog']) ? array_shift( array_keys( $_REQUEST['blog'] ) ) : $_REQUEST['blog'];
     769            $blog = (int) $blog;
     770            $this->import_blog( $blog );
     771        } elseif ( isset($_GET['token']) )
     772            $this->auth();
     773        elseif ( $this->token && $this->token_is_valid() )
     774            $this->show_blogs();
     775        else
     776            $this->greet();
     777
     778        $saved = $this->save_vars();
     779
     780        if ( $saved && !isset($_GET['noheader']) ) {
     781            $restart = __('Restart');
     782            $message = __('We have saved some information about your Blogger account in your WordPress database. Clearing this information will allow you to start over. Restarting will not affect any posts you have already imported. If you attempt to re-import a blog, duplicate posts and comments will be skipped.');
     783            $submit = __('Clear account information');
     784            echo "<div class='wrap'><h2>$restart</h2><p>$message</p><form method='post' action='?import=blogger&noheader=true'><p class='submit' style='text-align:left;'><input type='submit' value='$submit' name='restart' /></p></form></div>";
     785        }
     786    }
     787
     788    function save_vars() {
     789        $vars = get_object_vars($this);
     790        update_option( 'blogger_importer', $vars );
     791
     792        return !empty($vars);
     793    }
     794
     795    function admin_head() {
     796?>
     797<style type="text/css">
     798td { text-align: center; line-height: 2em;}
     799thead td { font-weight: bold; }
     800.bar {
     801    width: 200px;
     802    text-align: left;
     803    line-height: 2em;
     804    padding: 0px;
     805}
     806.ind {
     807    position: absolute;
     808    background-color: #83B4D8;
     809    width: 1px;
     810    z-index: 9;
     811}
     812.stat {
     813    z-index: 10;
     814    position: relative;
     815    text-align: center;
     816}
     817.submit {
     818    text-align: center !important;
     819}
     820</style>
     821<?php
     822    }
     823
     824    function Blogger_Import() {
     825        global $importer_started;
     826        $importer_started = time();
     827        if ( isset( $_GET['import'] ) && $_GET['import'] == 'blogger' ) {
     828            wp_enqueue_script('jquery');
     829            add_action('admin_head', array(&$this, 'admin_head'));
     830        }
     831    }
     832}
     833
     834$blogger_import = new Blogger_Import();
     835
     836register_importer('blogger', __('Blogger'), __('Import posts, comments, and users from a Blogger blog'), array ($blogger_import, 'start'));
     837
     838class AtomEntry {
     839    var $links = array();
     840    var $categories = array();
     841}
     842
     843class AtomParser {
     844
     845    var $ATOM_CONTENT_ELEMENTS = array('content','summary','title','subtitle','rights');
     846    var $ATOM_SIMPLE_ELEMENTS = array('id','updated','published','draft','author');
     847
     848    var $depth = 0;
     849    var $indent = 2;
     850    var $in_content;
     851    var $ns_contexts = array();
     852    var $ns_decls = array();
     853    var $is_xhtml = false;
     854    var $skipped_div = false;
     855
     856    var $entry;
     857
     858    function AtomParser() {
     859
     860        $this->entry = new AtomEntry();
     861        $this->map_attrs_func = create_function('$k,$v', 'return "$k=\"$v\"";');
     862        $this->map_xmlns_func = create_function('$p,$n', '$xd = "xmlns"; if(strlen($n[0])>0) $xd .= ":{$n[0]}"; return "{$xd}=\"{$n[1]}\"";');
     863    }
     864
     865    function parse($xml) {
     866
     867        global $app_logging;
     868        array_unshift($this->ns_contexts, array());
     869
     870        $parser = xml_parser_create_ns();
     871        xml_set_object($parser, $this);
     872        xml_set_element_handler($parser, "start_element", "end_element");
     873        xml_parser_set_option($parser,XML_OPTION_CASE_FOLDING,0);
     874        xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,0);
     875        xml_set_character_data_handler($parser, "cdata");
     876        xml_set_default_handler($parser, "_default");
     877        xml_set_start_namespace_decl_handler($parser, "start_ns");
     878        xml_set_end_namespace_decl_handler($parser, "end_ns");
     879
     880        $contents = "";
     881
     882        xml_parse($parser, $xml);
     883
     884        xml_parser_free($parser);
     885
     886        return true;
     887    }
     888
     889    function start_element($parser, $name, $attrs) {
     890
     891        $tag = array_pop(split(":", $name));
     892
     893        array_unshift($this->ns_contexts, $this->ns_decls);
     894
     895        $this->depth++;
     896
     897        if(!empty($this->in_content)) {
     898            $attrs_prefix = array();
     899
     900            // resolve prefixes for attributes
     901            foreach($attrs as $key => $value) {
     902                $attrs_prefix[$this->ns_to_prefix($key)] = $this->xml_escape($value);
     903            }
     904            $attrs_str = join(' ', array_map($this->map_attrs_func, array_keys($attrs_prefix), array_values($attrs_prefix)));
     905            if(strlen($attrs_str) > 0) {
     906                $attrs_str = " " . $attrs_str;
     907            }
     908
     909            $xmlns_str = join(' ', array_map($this->map_xmlns_func, array_keys($this->ns_contexts[0]), array_values($this->ns_contexts[0])));
     910            if(strlen($xmlns_str) > 0) {
     911                $xmlns_str = " " . $xmlns_str;
     912            }
     913
     914            // handle self-closing tags (case: a new child found right-away, no text node)
     915            if(count($this->in_content) == 2) {
     916                array_push($this->in_content, ">");
     917            }
     918         
     919            array_push($this->in_content, "<". $this->ns_to_prefix($name) ."{$xmlns_str}{$attrs_str}");
     920        } else if(in_array($tag, $this->ATOM_CONTENT_ELEMENTS) || in_array($tag, $this->ATOM_SIMPLE_ELEMENTS)) {
     921            $this->in_content = array();
     922            $this->is_xhtml = $attrs['type'] == 'xhtml';
     923            array_push($this->in_content, array($tag,$this->depth));
     924        } else if($tag == 'link') {
     925            array_push($this->entry->links, $attrs);
     926        } else if($tag == 'category') {
     927            array_push($this->entry->categories, $attrs['term']);
     928        }
     929
     930        $this->ns_decls = array();
     931    }
     932
     933    function end_element($parser, $name) {
     934
     935        $tag = array_pop(split(":", $name));
     936
     937        if(!empty($this->in_content)) {
     938            if($this->in_content[0][0] == $tag &&
     939            $this->in_content[0][1] == $this->depth) {
     940                array_shift($this->in_content);
     941                if($this->is_xhtml) {
     942                    $this->in_content = array_slice($this->in_content, 2, count($this->in_content)-3);
     943                }
     944                $this->entry->$tag = join('',$this->in_content);
     945                $this->in_content = array();
    615946            } else {
    616                 $step = 0;
    617             }
    618 //echo "Step $step.";
    619 //wp_die('<pre>'.print_r($this->import,1).'</pre');
    620             switch ($step) {
    621                 case 0 :
    622                     $this->do_login();
    623                     break;
    624                 case 1 :
    625                     $this->select_blog();
    626                     break;
    627                 case 2 :
    628                     $this->backup_settings();
    629                     break;
    630                 case 3 :
    631                     $this->wait_for_blogger();
    632                     break;
    633                 case 4 :
    634                     $this->publish_blog();
    635                     break;
    636                 case 5 :
    637                     $this->get_archive_urls();
    638                     break;
    639                 case 6 :
    640                     $this->get_archive();
    641                     break;
    642                 case 7 :
    643                     $this->restore_settings();
    644                     break;
    645                 case 8 :
    646                     $this->republish_blog();
    647                     break;
    648                 case 9 :
    649                     $this->congrats();
    650                     break;
    651             }
    652             die;
    653 
    654         } else {
    655             $this->greet();
    656         }
    657     }
    658 
    659     function Blogger_Import() {
    660         // This space intentionally left blank.
     947                $endtag = $this->ns_to_prefix($name);
     948                if (strpos($this->in_content[count($this->in_content)-1], '<' . $endtag) !== false) {
     949                    array_push($this->in_content, "/>");
     950                } else {
     951                    array_push($this->in_content, "</$endtag>");
     952                }
     953            }
     954        }
     955
     956        array_shift($this->ns_contexts);
     957
     958        #print str_repeat(" ", $this->depth * $this->indent) . "end_element('$name')" ."\n";
     959
     960        $this->depth--;
     961    }
     962
     963    function start_ns($parser, $prefix, $uri) {
     964        #print str_repeat(" ", $this->depth * $this->indent) . "starting: " . $prefix . ":" . $uri . "\n";
     965        array_push($this->ns_decls, array($prefix,$uri));
     966    }
     967
     968    function end_ns($parser, $prefix) {
     969        #print str_repeat(" ", $this->depth * $this->indent) . "ending: #" . $prefix . "#\n";
     970    }
     971
     972    function cdata($parser, $data) {
     973        #print str_repeat(" ", $this->depth * $this->indent) . "data: #" . $data . "#\n";
     974        if(!empty($this->in_content)) {
     975            // handle self-closing tags (case: text node found, need to close element started)
     976            if (strpos($this->in_content[count($this->in_content)-1], '<') !== false) {
     977                array_push($this->in_content, ">");
     978            }
     979            array_push($this->in_content, $this->xml_escape($data));
     980        }
     981    }
     982
     983    function _default($parser, $data) {
     984        # when does this gets called?
     985    }
     986
     987
     988    function ns_to_prefix($qname) {
     989        $components = split(":", $qname);
     990        $name = array_pop($components);
     991
     992        if(!empty($components)) {
     993            $ns = join(":",$components);
     994            foreach($this->ns_contexts as $context) {
     995                foreach($context as $mapping) {
     996                    if($mapping[1] == $ns && strlen($mapping[0]) > 0) {
     997                        return "$mapping[0]:$name";
     998                    }
     999                }
     1000            }
     1001        }
     1002        return $name;
     1003    }
     1004
     1005    function xml_escape($string)
     1006    {
     1007             return str_replace(array('&','"',"'",'<','>'),
     1008                array('&amp;','&quot;','&apos;','&lt;','&gt;'),
     1009                $string );
    6611010    }
    6621011}
    6631012
    664 $blogger_import = new Blogger_Import();
    665 
    666 register_importer('blogger', __('Old Blogger'), __('Import posts, comments, and users from an Old Blogger blog'), array ($blogger_import, 'start'));
    667 
    6681013?>
  • tags/2.2/wp-admin/import/dotclear.php

    r5468 r5480  
    148148        echo '<p>'.__('Your DotClear Configuration settings are as follows:').'</p>';
    149149        echo '<form action="admin.php?import=dotclear&amp;step=1" method="post">';
     150        wp_nonce_field('import-dotclear');
    150151        $this->db_form();
    151         echo '<p class="submit"><input type="submit" name="submit" value="'.__('Import Categories').' &raquo;" /></p>';
     152        echo '<p class="submit"><input type="submit" name="submit" value="'.attribute_escape(__('Import Categories &raquo;')).'" /></p>';
    152153        echo '</form></div>';
    153154    }
     
    559560
    560561        echo '<form action="admin.php?import=dotclear&amp;step=2" method="post">';
    561         printf('<input type="submit" name="submit" value="%s" />', __('Import Users'));
     562        wp_nonce_field('import-dotclear');
     563        printf('<input type="submit" name="submit" value="%s" />', attribute_escape(__('Import Users')));
    562564        echo '</form>';
    563565
     
    571573
    572574        echo '<form action="admin.php?import=dotclear&amp;step=3" method="post">';
    573         printf('<input type="submit" name="submit" value="%s" />', __('Import Posts'));
     575        wp_nonce_field('import-dotclear');
     576        printf('<input type="submit" name="submit" value="%s" />', attribute_escape(__('Import Posts')));
    574577        echo '</form>';
    575578    }
     
    582585
    583586        echo '<form action="admin.php?import=dotclear&amp;step=4" method="post">';
    584         printf('<input type="submit" name="submit" value="%s" />', __('Import Comments'));
     587        wp_nonce_field('import-dotclear');
     588        printf('<input type="submit" name="submit" value="%s" />', attribute_escape(__('Import Comments')));
    585589        echo '</form>';
    586590    }
     
    593597
    594598        echo '<form action="admin.php?import=dotclear&amp;step=5" method="post">';
    595         printf('<input type="submit" name="submit" value="%s" />', __('Import Links'));
     599        wp_nonce_field('import-dotclear');
     600        printf('<input type="submit" name="submit" value="%s" />', attribute_escape(__('Import Links')));
    596601        echo '</form>';
    597602    }
     
    605610
    606611        echo '<form action="admin.php?import=dotclear&amp;step=6" method="post">';
    607         printf('<input type="submit" name="submit" value="%s" />', __('Finish'));
     612        wp_nonce_field('import-dotclear');
     613        printf('<input type="submit" name="submit" value="%s" />', attribute_escape(__('Finish')));
    608614        echo '</form>';
    609615    }
     
    668674        if ( $step > 0 )
    669675        {
     676            check_admin_referer('import-dotclear');
     677
    670678            if($_POST['dbuser'])
    671679            {
    672680                if(get_option('dcuser'))
    673681                    delete_option('dcuser');
    674                 add_option('dcuser',$_POST['dbuser']);
     682                add_option('dcuser', sanitize_user($_POST['dbuser'], true));
    675683            }
    676684            if($_POST['dbpass'])
     
    678686                if(get_option('dcpass'))
    679687                    delete_option('dcpass');
    680                 add_option('dcpass',$_POST['dbpass']);
     688                add_option('dcpass', sanitize_user($_POST['dbpass'], true));
    681689            }
    682690
     
    685693                if(get_option('dcname'))
    686694                    delete_option('dcname');
    687                 add_option('dcname',$_POST['dbname']);
     695                add_option('dcname', sanitize_user($_POST['dbname'], true));
    688696            }
    689697            if($_POST['dbhost'])
     
    691699                if(get_option('dchost'))
    692700                    delete_option('dchost');
    693                 add_option('dchost',$_POST['dbhost']);
     701                add_option('dchost', sanitize_user($_POST['dbhost'], true));
    694702            }
    695703            if($_POST['dccharset'])
     
    697705                if(get_option('dccharset'))
    698706                    delete_option('dccharset');
    699                 add_option('dccharset',$_POST['dccharset']);
     707                add_option('dccharset', sanitize_user($_POST['dccharset'], true));
    700708            }
    701709            if($_POST['dbprefix'])
     
    703711                if(get_option('dcdbprefix'))
    704712                    delete_option('dcdbprefix');
    705                 add_option('dcdbprefix',$_POST['dbprefix']);
     713                add_option('dcdbprefix', sanitize_user($_POST['dbprefix'], true));
    706714            }
    707715
  • tags/2.2/wp-admin/import/greymatter.php

    r5468 r5480  
    3535<input type="hidden" name="import" value="greymatter" />
    3636<input type="hidden" name="step" value="1" />
     37<?php wp_nonce_field('import-greymatter'); ?>
    3738<h3><?php _e('Second step: GreyMatter details:') ?></h3>
    3839<p><table cellpadding="0">
     
    8889
    8990        if (!chdir($archivespath))
    90             wp_die(sprintf(__("Wrong path, %s\ndoesn't exist\non the server"), $archivespath));
     91            wp_die(__("Wrong path, the path to the GM entries does not exist on the server"));
    9192
    9293        if (!chdir($gmpath))
    93             wp_die(sprintf(__("Wrong path, %s\ndoesn't exist\non the server"), $gmpath));
    94            
     94            wp_die(__("Wrong path, the path to the GM files does not exist on the server"));
     95
     96        $lastentry = (int) $lastentry;
     97
    9598        $this->header();
    9699?>
     
    129132        $user_id = wp_insert_user($user_info);
    130133        $this->gmnames[$userdata[0]] = $user_id;
    131        
     134
    132135        printf('<li>'.__('user %s...').' <strong>'.__('Done').'</strong></li>', "<em>$user_login</em>");
    133136    }
     
    214217                    $user_url=$wpdb->escape("");
    215218                    $user_joindate=$wpdb->escape($user_joindate);
    216                    
     219
    217220                    $user_info = array("user_login"=>$user_login, "user_pass"=>$pass1, "user_nickname"=>$user_nickname, "user_email"=>$user_email, "user_url"=>$user_url, "user_ip"=>$user_ip, "user_domain"=>$user_domain, "user_browser"=>$user_browser, "dateYMDhour"=>$user_joindate, "user_level"=>0, "user_idmode"=>"nickname");
    218221                    $user_id = wp_insert_user($user_info);
    219222                    $this->gmnames[$postinfo[1]] = $user_id;
    220                    
     223
    221224                    echo ': ';
    222225                    printf(__('registered deleted user %s at level 0 '), "<em>$user_login</em>");
    223226                }
    224            
     227
    225228                if (array_key_exists($postinfo[1], $this->gmnames)) {
    226229                    $post_author = $this->gmnames[$postinfo[1]];
     
    228231                    $post_author = $user_id;
    229232                }
    230            
     233
    231234                $postdata = compact('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_excerpt', 'post_status', 'comment_status', 'ping_status', 'post_modified', 'post_modified_gmt');
    232235                $post_ID = wp_insert_post($postdata);
     
    298301                break;
    299302            case 1:
     303                check_admin_referer('import-greymatter');
    300304                $this->import();
    301305                break;
  • tags/2.2/wp-admin/import/livejournal.php

    r5468 r5480  
    154154                break;
    155155            case 1 :
     156                check_admin_referer('import-upload');
    156157                $this->import();
    157158                break;
  • tags/2.2/wp-admin/import/mt.php

    r5468 r5480  
    148148        echo '<ol id="authors">';
    149149        echo '<form action="?import=mt&amp;step=2&amp;id=' . $this->id . '" method="post">';
     150        wp_nonce_field('import-mt');
    150151        $j = -1;
    151152        foreach ($authors as $author) {
     
    418419                break;
    419420            case 1 :
     421                check_admin_referer('import-upload');
    420422                $this->select_authors();
    421423                break;
    422424            case 2:
     425                check_admin_referer('import-mt');
    423426                $this->import();
    424427                break;
  • tags/2.2/wp-admin/import/rss.php

    r5468 r5480  
    157157                break;
    158158            case 1 :
     159                check_admin_referer('import-upload');
    159160                $this->import();
    160161                break;
  • tags/2.2/wp-admin/import/textpattern.php

    r5468 r5480  
    5757        echo '<p>'.__('Your Textpattern Configuration settings are as follows:').'</p>';
    5858        echo '<form action="admin.php?import=textpattern&amp;step=1" method="post">';
     59        wp_nonce_field('import-textpattern');
    5960        $this->db_form();
    60         echo '<p class="submit"><input type="submit" name="submit" value="'.__('Import Categories').' &raquo;" /></p>';
     61        echo '<p class="submit"><input type="submit" name="submit" value="'.attribute_escape(__('Import Categories &raquo;')).'" /></p>';
    6162        echo '</form>';
    6263        echo '</div>';
     
    484485
    485486        echo '<form action="admin.php?import=textpattern&amp;step=2" method="post">';
    486         printf('<input type="submit" name="submit" value="%s" />', __('Import Users'));
     487        wp_nonce_field('import-textpattern');
     488        printf('<input type="submit" name="submit" value="%s" />', attribute_escape(__('Import Users')));
    487489        echo '</form>';
    488490
     
    496498
    497499        echo '<form action="admin.php?import=textpattern&amp;step=3" method="post">';
    498         printf('<input type="submit" name="submit" value="%s" />', __('Import Posts'));
     500        wp_nonce_field('import-textpattern');
     501        printf('<input type="submit" name="submit" value="%s" />', attribute_escape(__('Import Posts')));
    499502        echo '</form>';
    500503    }
     
    507510
    508511        echo '<form action="admin.php?import=textpattern&amp;step=4" method="post">';
    509         printf('<input type="submit" name="submit" value="%s" />', __('Import Comments'));
     512        wp_nonce_field('import-textpattern');
     513        printf('<input type="submit" name="submit" value="%s" />', attribute_escape(__('Import Comments')));
    510514        echo '</form>';
    511515    }
     
    518522
    519523        echo '<form action="admin.php?import=textpattern&amp;step=5" method="post">';
    520         printf('<input type="submit" name="submit" value="%s" />', __('Import Links'));
     524        wp_nonce_field('import-textpattern');
     525        printf('<input type="submit" name="submit" value="%s" />', attribute_escape(__('Import Links')));
    521526        echo '</form>';
    522527    }
     
    530535
    531536        echo '<form action="admin.php?import=textpattern&amp;step=6" method="post">';
    532         printf('<input type="submit" name="submit" value="%s" />', __('Finish'));
     537        wp_nonce_field('import-textpattern');
     538        printf('<input type="submit" name="submit" value="%s" />', attribute_escape(__('Finish')));
    533539        echo '</form>';
    534540    }
     
    591597        if ( $step > 0 )
    592598        {
     599            check_admin_referer('import-textpattern');
     600
    593601            if($_POST['dbuser'])
    594602            {
    595603                if(get_option('txpuser'))
    596604                    delete_option('txpuser');
    597                 add_option('txpuser',$_POST['dbuser']);
     605                add_option('txpuser', sanitize_user($_POST['dbuser'], true));
    598606            }
    599607            if($_POST['dbpass'])
     
    601609                if(get_option('txppass'))
    602610                    delete_option('txppass');
    603                 add_option('txppass',$_POST['dbpass']);
     611                add_option('txppass',  sanitize_user($_POST['dbpass'], true));
    604612            }
    605613
     
    608616                if(get_option('txpname'))
    609617                    delete_option('txpname');
    610                 add_option('txpname',$_POST['dbname']);
     618                add_option('txpname',  sanitize_user($_POST['dbname'], true));
    611619            }
    612620            if($_POST['dbhost'])
     
    614622                if(get_option('txphost'))
    615623                    delete_option('txphost');
    616                 add_option('txphost',$_POST['dbhost']);
     624                add_option('txphost',  sanitize_user($_POST['dbhost'], true));
    617625            }
    618626            if($_POST['dbprefix'])
     
    620628                if(get_option('tpre'))
    621629                    delete_option('tpre');
    622                 add_option('tpre',$_POST['dbprefix']);
     630                add_option('tpre',  sanitize_user($_POST['dbprefix']));
    623631            }
    624632
  • tags/2.2/wp-admin/import/wordpress.php

    r5468 r5480  
    44
    55    var $posts = array ();
     6    var $posts_processed = array ();
     7    // Array of arrays. [[0] => XML fragment, [1] => New post ID]
    68    var $file;
    79    var $id;
     
    3436
    3537    function get_tag( $string, $tag ) {
     38        global $wpdb;
    3639        preg_match("|<$tag.*?>(.*?)</$tag>|is", $string, $return);
    37         $return = addslashes( trim( $return[1] ) );
     40        $return = $wpdb->escape( trim( $return[1] ) );
    3841        return $return;
    3942    }
     
    6366            $user_id = username_exists($this->newauthornames[$this->j]); //check if the new author name defined by the user is a pre-existing wp user
    6467            if (!$user_id) { //banging my head against the desk now.
    65                 if ($newauthornames[$this->j] == 'left_blank') { //check if the user does not want to change the authorname
     68                if ($this->newauthornames[$this->j] == 'left_blank') { //check if the user does not want to change the authorname
    6669                    $user_id = wp_create_user($author, $pass);
    6770                    $this->newauthornames[$this->j] = $author; //now we have a name, in the place of left_blank.
     
    8285    function get_entries() {
    8386        set_magic_quotes_runtime(0);
    84         $importdata = file($this->file); // Read the file into an array
    85         $importdata = implode('', $importdata); // squish it
    86         $importdata = preg_replace("/(\r\n|\n|\r)/", "\n", $importdata);
    87         preg_match_all('|<item>(.*?)</item>|is', $importdata, $this->posts);
    88         $this->posts = $this->posts[1];
    89         preg_match_all('|<wp:category>(.*?)</wp:category>|is', $importdata, $this->categories);
    90         $this->categories = $this->categories[1];
     87        $importdata = array_map('rtrim', file($this->file)); // Read the file into an array
     88
     89        $this->posts = array();
     90        $this->categories = array();
     91        $num = 0;
     92        $doing_entry = false;
     93        foreach ($importdata as $importline) {
     94            if ( false !== strpos($importline, '<wp:category>') ) {
     95                preg_match('|<wp:category>(.*?)</wp:category>|is', $importline, $category);
     96                $this->categories[] = $category[1];
     97                continue;
     98            }
     99            if ( false !== strpos($importline, '<item>') ) {
     100                $this->posts[$num] = '';
     101                $doing_entry = true;
     102                continue;   
     103            }
     104            if ( false !== strpos($importline, '</item>') ) {
     105                $num++;
     106                $doing_entry = false;
     107                continue;   
     108            }
     109            if ( $doing_entry ) {
     110                $this->posts[$num] .= $importline . "\n";
     111            }
     112        }
     113
     114        foreach ($this->posts as $post) {
     115            $post_ID = (int) $this->get_tag( $post, 'wp:post_id' );
     116            if ($post_ID) {
     117                $this->posts_processed[$post_ID][0] = &$post;
     118                $this->posts_processed[$post_ID][1] = 0;
     119            }
     120        }
    91121    }
    92122
     
    151181        echo '<ol id="authors">';
    152182        echo '<form action="?import=wordpress&amp;step=2&amp;id=' . $this->id . '" method="post">';
     183        wp_nonce_field('import-wordpress');
    153184        $j = -1;
    154185        foreach ($authors as $author) {
     
    168199        $file = wp_import_handle_upload();
    169200        if ( isset($file['error']) ) {
    170             $this->header();
    171201            echo '<p>'.__('Sorry, there has been an error.').'</p>';
    172202            echo '<p><strong>' . $file['error'] . '</strong></p>';
    173             $this->footer();
    174203            return;
    175204        }
     
    211240
    212241    function process_posts() {
    213         global $wpdb;
    214242        $i = -1;
    215243        echo '<ol>';
    216         foreach ($this->posts as $post) {
    217 
    218             // There are only ever one of these
    219             $post_title     = $this->get_tag( $post, 'title' );
    220             $post_date      = $this->get_tag( $post, 'wp:post_date' );
    221             $post_date_gmt  = $this->get_tag( $post, 'wp:post_date_gmt' );
    222             $comment_status = $this->get_tag( $post, 'wp:comment_status' );
    223             $ping_status    = $this->get_tag( $post, 'wp:ping_status' );
    224             $post_status    = $this->get_tag( $post, 'wp:status' );
    225             $post_parent    = $this->get_tag( $post, 'wp:post_parent' );
    226             $post_type      = $this->get_tag( $post, 'wp:post_type' );
    227             $guid           = $this->get_tag( $post, 'guid' );
    228             $post_author    = $this->get_tag( $post, 'dc:creator' );
    229 
    230             $post_content = $this->get_tag( $post, 'content:encoded' );
    231             $post_content = str_replace(array ('<![CDATA[', ']]>'), '', $post_content);
    232             $post_content = preg_replace('|<(/?[A-Z]+)|e', "'<' . strtolower('$1')", $post_content);
    233             $post_content = str_replace('<br>', '<br />', $post_content);
    234             $post_content = str_replace('<hr>', '<hr />', $post_content);
    235 
    236             preg_match_all('|<category>(.*?)</category>|is', $post, $categories);
    237             $categories = $categories[1];
    238 
    239             $cat_index = 0;
    240             foreach ($categories as $category) {
    241                 $categories[$cat_index] = $wpdb->escape($this->unhtmlentities(str_replace(array ('<![CDATA[', ']]>'), '', $category)));
    242                 $cat_index++;
    243             }
    244 
    245             if ($post_id = post_exists($post_title, '', $post_date)) {
    246                 echo '<li>';
    247                 printf(__('Post <i>%s</i> already exists.'), stripslashes($post_title));
    248             } else {
    249                 echo '<li>';
    250                 printf(__('Importing post <i>%s</i>...'), stripslashes($post_title));
    251 
    252                 $post_author = $this->checkauthor($post_author); //just so that if a post already exists, new users are not created by checkauthor
    253 
    254                 $postdata = compact('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_excerpt', 'post_status', 'comment_status', 'ping_status', 'post_modified', 'post_modified_gmt', 'guid', 'post_parent', 'post_type');
    255                 $comment_post_ID = $post_id = wp_insert_post($postdata);
    256                 // Add categories.
    257                 if (0 != count($categories)) {
    258                     wp_create_categories($categories, $post_id);
     244
     245        foreach ($this->posts as $post)
     246            $this->process_post($post);
     247
     248        echo '</ol>';
     249
     250        wp_import_cleanup($this->id);
     251
     252        echo '<h3>'.sprintf(__('All done.').' <a href="%s">'.__('Have fun!').'</a>', get_option('home')).'</h3>';
     253    }
     254 
     255    function process_post($post) {
     256        global $wpdb;
     257
     258        $post_ID = (int) $this->get_tag( $post, 'wp:post_id' );
     259        if ( $post_ID && !empty($this->posts_processed[$post_ID][1]) ) // Processed already
     260            return 0;
     261     
     262        // There are only ever one of these
     263        $post_title     = $this->get_tag( $post, 'title' );
     264        $post_date      = $this->get_tag( $post, 'wp:post_date' );
     265        $post_date_gmt  = $this->get_tag( $post, 'wp:post_date_gmt' );
     266        $comment_status = $this->get_tag( $post, 'wp:comment_status' );
     267        $ping_status    = $this->get_tag( $post, 'wp:ping_status' );
     268        $post_status    = $this->get_tag( $post, 'wp:status' );
     269        $post_name      = $this->get_tag( $post, 'wp:post_name' );
     270        $post_parent    = $this->get_tag( $post, 'wp:post_parent' );
     271        $menu_order     = $this->get_tag( $post, 'wp:menu_order' );
     272        $post_type      = $this->get_tag( $post, 'wp:post_type' );
     273        $guid           = $this->get_tag( $post, 'guid' );
     274        $post_author    = $this->get_tag( $post, 'dc:creator' );
     275
     276        $post_content = $this->get_tag( $post, 'content:encoded' );
     277        $post_content = str_replace(array ('<![CDATA[', ']]>'), '', $post_content);
     278        $post_content = preg_replace('|<(/?[A-Z]+)|e', "'<' . strtolower('$1')", $post_content);
     279        $post_content = str_replace('<br>', '<br />', $post_content);
     280        $post_content = str_replace('<hr>', '<hr />', $post_content);
     281
     282        preg_match_all('|<category>(.*?)</category>|is', $post, $categories);
     283        $categories = $categories[1];
     284
     285        $cat_index = 0;
     286        foreach ($categories as $category) {
     287            $categories[$cat_index] = $wpdb->escape($this->unhtmlentities(str_replace(array ('<![CDATA[', ']]>'), '', $category)));
     288            $cat_index++;
     289        }
     290
     291        if ($post_id = post_exists($post_title, '', $post_date)) {
     292            echo '<li>';
     293            printf(__('Post <i>%s</i> already exists.'), stripslashes($post_title));
     294        } else {
     295
     296            // If it has parent, process parent first.
     297            $post_parent = (int) $post_parent;
     298            if ($parent = $this->posts_processed[$post_parent]) {
     299                if (!$parent[1]) $this->process_post($parent[0]); // If not yet, process the parent first.
     300                $post_parent = $parent[1]; // New ID of the parent;
     301            }
     302
     303            echo '<li>';
     304            printf(__('Importing post <i>%s</i>...'), stripslashes($post_title));
     305
     306            $post_author = $this->checkauthor($post_author); //just so that if a post already exists, new users are not created by checkauthor
     307
     308            $postdata = compact('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_excerpt', 'post_status', 'post_name', 'comment_status', 'ping_status', 'post_modified', 'post_modified_gmt', 'guid', 'post_parent', 'menu_order', 'post_type');
     309            $comment_post_ID = $post_id = wp_insert_post($postdata);
     310
     311            // Memorize old and new ID.
     312            if ( $post_id && $post_ID && $this->posts_processed[$post_ID] )
     313                $this->posts_processed[$post_ID][1] = $post_id; // New ID.
     314           
     315            // Add categories.
     316            if (count($categories) > 0) {
     317                $post_cats = array();
     318                foreach ($categories as $category) {
     319                    $cat_ID = (int) $wpdb->get_var("SELECT cat_ID FROM $wpdb->categories WHERE cat_name = '$category'");
     320                    if ($cat_ID == 0) {
     321                        $cat_ID = wp_insert_category(array('cat_name' => $category));
     322                    }
     323                    $post_cats[] = $cat_ID;
    259324                }
    260             }
    261 
    262                 // Now for comments
    263                 preg_match_all('|<wp:comment>(.*?)</wp:comment>|is', $post, $comments);
    264                 $comments = $comments[1];
    265                 $num_comments = 0;
    266                 if ( $comments) { foreach ($comments as $comment) {
    267                     $comment_author       = $this->get_tag( $comment, 'wp:comment_author');
    268                     $comment_author_email = $this->get_tag( $comment, 'wp:comment_author_email');
    269                     $comment_author_IP    = $this->get_tag( $comment, 'wp:comment_author_IP');
    270                     $comment_author_url   = $this->get_tag( $comment, 'wp:comment_author_url');
    271                     $comment_date         = $this->get_tag( $comment, 'wp:comment_date');
    272                     $comment_date_gmt     = $this->get_tag( $comment, 'wp:comment_date_gmt');
    273                     $comment_content      = $this->get_tag( $comment, 'wp:comment_content');
    274                     $comment_approved     = $this->get_tag( $comment, 'wp:comment_approved');
    275                     $comment_type         = $this->get_tag( $comment, 'wp:comment_type');
    276                     $comment_parent       = $this->get_tag( $comment, 'wp:comment_parent');
    277 
    278                     if ( !comment_exists($comment_author, $comment_date) ) {
    279                         $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_url', 'comment_author_email', 'comment_author_IP', 'comment_date', 'comment_date_gmt', 'comment_content', 'comment_approved', 'comment_type', 'comment_parent');
    280                         wp_insert_comment($commentdata);
    281                         $num_comments++;
    282                     }
    283                 } }
    284                 if ( $num_comments )
    285                     printf(' '.__('(%s comments)'), $num_comments);
    286 
    287                 // Now for post meta
    288                 preg_match_all('|<wp:postmeta>(.*?)</wp:postmeta>|is', $post, $postmeta);
    289                 $postmeta = $postmeta[1];
    290                 if ( $postmeta) { foreach ($postmeta as $p) {
    291                     $key   = $this->get_tag( $p, 'wp:meta_key' );
    292                     $value = $this->get_tag( $p, 'wp:meta_value' );
    293                     add_post_meta( $post_id, $key, $value );
    294                 } }
    295 
    296             $index++;
    297         }
    298 
    299         echo '</ol>';
    300 
    301         wp_import_cleanup($this->id);
    302 
    303         echo '<h3>'.sprintf(__('All done.').' <a href="%s">'.__('Have fun!').'</a>', get_option('home')).'</h3>';
     325                wp_set_post_categories($post_id, $post_cats);
     326            }   
     327        }
     328
     329        // Now for comments
     330        preg_match_all('|<wp:comment>(.*?)</wp:comment>|is', $post, $comments);
     331        $comments = $comments[1];
     332        $num_comments = 0;
     333        if ( $comments) { foreach ($comments as $comment) {
     334            $comment_author       = $this->get_tag( $comment, 'wp:comment_author');
     335            $comment_author_email = $this->get_tag( $comment, 'wp:comment_author_email');
     336            $comment_author_IP    = $this->get_tag( $comment, 'wp:comment_author_IP');
     337            $comment_author_url   = $this->get_tag( $comment, 'wp:comment_author_url');
     338            $comment_date         = $this->get_tag( $comment, 'wp:comment_date');
     339            $comment_date_gmt     = $this->get_tag( $comment, 'wp:comment_date_gmt');
     340            $comment_content      = $this->get_tag( $comment, 'wp:comment_content');
     341            $comment_approved     = $this->get_tag( $comment, 'wp:comment_approved');
     342            $comment_type         = $this->get_tag( $comment, 'wp:comment_type');
     343            $comment_parent       = $this->get_tag( $comment, 'wp:comment_parent');
     344
     345            if ( !comment_exists($comment_author, $comment_date) ) {
     346                $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_url', 'comment_author_email', 'comment_author_IP', 'comment_date', 'comment_date_gmt', 'comment_content', 'comment_approved', 'comment_type', 'comment_parent');
     347                wp_insert_comment($commentdata);
     348                $num_comments++;
     349            }
     350        } }
     351
     352        if ( $num_comments )
     353            printf(' '.__('(%s comments)'), $num_comments);
     354
     355        // Now for post meta
     356        preg_match_all('|<wp:postmeta>(.*?)</wp:postmeta>|is', $post, $postmeta);
     357        $postmeta = $postmeta[1];
     358        if ( $postmeta) { foreach ($postmeta as $p) {
     359            $key   = $this->get_tag( $p, 'wp:meta_key' );
     360            $value = $this->get_tag( $p, 'wp:meta_value' );
     361            $value = stripslashes($value); // add_post_meta() will escape.
     362            add_post_meta( $post_id, $key, $value );
     363        } }
    304364    }
    305365
     
    326386                break;
    327387            case 1 :
     388                check_admin_referer('import-upload');
    328389                $this->select_authors();
    329390                break;
    330391            case 2:
     392                check_admin_referer('import-wordpress');
    331393                $this->import();
    332394                break;
  • tags/2.2/wp-admin/index.php

    r5468 r5480  
    1616add_action( 'admin_head', 'index_js' );
    1717wp_enqueue_script('prototype');
     18wp_enqueue_script('interface');
    1819
    1920$title = __('Dashboard');
     
    5051if ( $comments ) {
    5152foreach ($comments as $comment) {
    52     echo '<li>' . sprintf(__('%1$s on %2$s'), get_comment_author_link(), '<a href="'. get_permalink($comment->comment_post_ID) . '#comment-' . $comment->comment_ID . '">' . get_the_title($comment->comment_post_ID) . '</a>');
     53    echo '<li>' . sprintf(__('%1$s on %2$s'), get_comment_author_link(), '<a href="'. get_permalink($comment->comment_post_ID) . '#comment-' . $comment->comment_ID . '">' . apply_filters('the_title', get_the_title($comment->comment_post_ID)) . '</a>');
    5354    edit_comment_link(__("Edit"), ' <small>(', ')</small>');
    5455    echo '</li>';
     
    6162
    6263<?php
    63 if ( $recentposts = $wpdb->get_results("SELECT ID, post_title FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' AND post_date_gmt < '$today' ORDER BY post_date DESC LIMIT 5") ) :
     64if ( $recentposts = $wpdb->get_results("SELECT ID, post_title FROM $wpdb->posts WHERE post_type = 'post' AND " . get_private_posts_cap_sql('post') . " AND post_date_gmt < '$today' ORDER BY post_date DESC LIMIT 5") ) :
    6465?>
    6566<div>
     
    99100<h3><?php _e('Blog Stats'); ?></h3>
    100101<?php
    101 $numposts = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish'");
    102 if (0 < $numposts) $numposts = number_format($numposts);
     102$numposts = (int) $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish'");
     103$numcomms = (int) $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = '1'");
     104$numcats  = (int) $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->categories");
    103105
    104 $numcomms = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->comments WHERE comment_approved = '1'");
    105 if (0 < $numcomms) $numcomms = number_format($numcomms);
     106$post_str = sprintf(__ngettext('%1$s <a href="%2$s" title="Posts">post</a>', '%1$s <a href="%2$s" title="Posts">posts</a>', $numposts), number_format($numposts), 'edit.php');
     107$comm_str = sprintf(__ngettext('%1$s <a href="%2$s" title="Comments">comment</a>', '%1$s <a href="%2$s" title="Comments">comments</a>', $numcomms), number_format($numcomms), 'edit-comments.php');
     108$cat_str  = sprintf(__ngettext('%1$s <a href="%2$s" title="Categories">category</a>', '%1$s <a href="%2$s" title="Categories">categories</a>', $numcats), number_format($numcats), 'categories.php');
     109?>
    106110
    107 $numcats = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->categories");
    108 if (0 < $numcats) $numcats = number_format($numcats);
    109 ?>
    110 <p><?php
    111 $post_str = sprintf(__ngettext('%1$s <a href="%2$s" title="Posts">post</a>', '%1$s <a href="%2$s" title="Posts">posts</a>', $numposts), $numposts, 'edit.php');
    112 $comm_str = sprintf(__ngettext('%1$s <a href="%2$s" title="Comments">comment</a>', '%1$s <a href="%2$s" title="Comments">comments</a>', $numcomms), $numcomms, 'edit-comments.php');
    113 $cat_str = sprintf(__ngettext('%1$s <a href="%2$s" title="Categories">category</a>', '%1$s <a href="%2$s" title="Categories">categories</a>', $numcats), $numcats, 'categories.php');
    114 
    115 printf(__('There are currently %1$s and %2$s, contained within %3$s.'), $post_str, $comm_str, $cat_str); ?></p>
     111<p><?php printf(__('There are currently %1$s and %2$s, contained within %3$s.'), $post_str, $comm_str, $cat_str); ?></p>
    116112</div>
    117113
     
    127123    <li><a href="profile.php"><?php _e('Update your profile or change your password'); ?></a></li>
    128124<?php if ( current_user_can('manage_links') ) : ?>
    129     <li><a href="link-add.php"><?php _e('Add a bookmark to your blogroll'); ?></a></li>
     125    <li><a href="link-add.php"><?php _e('Add a link to your blogroll'); ?></a></li>
    130126<?php endif; ?>
    131127<?php if ( current_user_can('switch_themes') ) : ?>
  • tags/2.2/wp-admin/link-add.php

    r5468 r5480  
    2929<div id="wp-link-bookmarklet"  class="wrap">
    3030<h3><?php _e('Add Link Bookmarklet'); ?></h3>
    31 <p><?php _e('Right click on the following link and choose "Bookmark This Link..." to create an add link shortcut. Right now this only works on Mozilla or Netscape, but we&#8217;re working on it.'); ?></p>
     31<p><?php _e('Right click on the following link and choose &#0147;Bookmark This Link...&#0148; or &#0147;Add to Favorites...&#0148; to create a Link This shortcut.'); ?></p>
    3232<?php printf('<p><a href="%s" title="'.__('Link add bookmarklet').'">'.__('Link This').'</a></p>', "javascript:void(linkmanpopup=window.open('" . get_option('siteurl') . "/wp-admin/link-add.php?action=popup&amp;linkurl='+escape(location.href)+'&amp;name='+escape(document.title),'LinkManager','scrollbars=yes,width=750,height=550,left=15,top=15,status=yes,resizable=yes'));linkmanpopup.focus();window.focus();linkmanpopup.focus();") ?>
    3333</div>
  • tags/2.2/wp-admin/link-import.php

    r5468 r5480  
    1313<?php
    1414switch ($step) {
    15     case 0:
    16     {
    17         include_once('admin-header.php');
    18         if ( !current_user_can('manage_links') )
    19             wp_die(__('Cheatin&#8217; uh?'));
     15    case 0: {
     16        include_once('admin-header.php');
     17        if ( !current_user_can('manage_links') )
     18            wp_die(__('Cheatin&#8217; uh?'));
    2019
    21         $opmltype = 'blogrolling'; // default.
     20        $opmltype = 'blogrolling'; // default.
    2221?>
    2322
    2423<div class="wrap">
     24
    2525<h2><?php _e('Import your blogroll from another system') ?> </h2>
    2626<form enctype="multipart/form-data" action="link-import.php" method="post" name="blogroll">
     
    4141</div>
    4242
    43 
    4443</div>
    4544
     
    5049foreach ($categories as $category) {
    5150?>
    52 <option value="<?php echo $category->cat_ID; ?>"><?php echo wp_specialchars($category->cat_name); ?></option>
     51<option value="<?php echo $category->cat_ID; ?>"><?php echo wp_specialchars(apply_filters('link_category', $category->cat_name)); ?></option>
    5352<?php
    5453} // end foreach
     
    6160</div>
    6261<?php
    63                 break;
    64             } // end case 0
     62        break;
     63    } // end case 0
    6564
    66     case 1: {
     65    case 1: {
    6766        check_admin_referer('import-bookmarks');
    6867
    69                 include_once('admin-header.php');
    70                 if ( !current_user_can('manage_links') )
    71                     wp_die(__('Cheatin&#8217; uh?'));
     68        include_once('admin-header.php');
     69        if ( !current_user_can('manage_links') )
     70            wp_die(__('Cheatin&#8217; uh?'));
    7271?>
    7372<div class="wrap">
    7473
    75      <h2><?php _e('Importing...') ?></h2>
     74<h2><?php _e('Importing...') ?></h2>
    7675<?php
    77                 $cat_id = $_POST['cat_id'];
    78                 if (($cat_id == '') || ($cat_id == 0)) {
    79                     $cat_id  = 1;
    80                 }
     76        $cat_id = $_POST['cat_id'];
     77        if ( $cat_id == '' || $cat_id == 0 )
     78            $cat_id  = 1;
    8179
    82                 $opml_url = $_POST['opml_url'];
    83                 if (isset($opml_url) && $opml_url != '' && $opml_url != 'http://') {
    84                     $blogrolling = true;
    85                 }
    86                 else // try to get the upload file.
    87                 {
    88                     $overrides = array('test_form' => false, 'test_type' => false);
    89                     $file = wp_handle_upload($_FILES['userfile'], $overrides);
     80        $opml_url = $_POST['opml_url'];
     81        if ( isset($opml_url) && $opml_url != '' && $opml_url != 'http://' ) {
     82            $blogrolling = true;
     83        } else { // try to get the upload file.
     84            $overrides = array('test_form' => false, 'test_type' => false);
     85            $file = wp_handle_upload($_FILES['userfile'], $overrides);
    9086
    91                     if ( isset($file['error']) )
    92                         wp_die($file['error']);
     87            if ( isset($file['error']) )
     88                wp_die($file['error']);
    9389
    94                     $url = $file['url'];
    95                     $opml_url = $file['file'];
    96                     $blogrolling = false;
    97                 }
     90            $url = $file['url'];
     91            $opml_url = $file['file'];
     92            $blogrolling = false;
     93        }
    9894
    99                 if (isset($opml_url) && $opml_url != '') {
    100                     $opml = wp_remote_fopen($opml_url);
    101                     include_once('link-parse-opml.php');
     95        if ( isset($opml_url) && $opml_url != '' ) {
     96            if ( $blogrolling === true ) {
     97                $opml = wp_remote_fopen($opml_url);
     98            } else {
     99                $opml = file_get_contents($opml_url);
     100            }
     101           
     102            include_once('link-parse-opml.php');
    102103
    103                     $link_count = count($names);
    104                     for ($i = 0; $i < $link_count; $i++) {
    105                         if ('Last' == substr($titles[$i], 0, 4))
    106                             $titles[$i] = '';
    107                         if ('http' == substr($titles[$i], 0, 4))
    108                             $titles[$i] = '';
    109                         $link = array( 'link_url' => $urls[$i], 'link_name' => $wpdb->escape($names[$i]), 'link_category' => array($cat_id), 'link_description' => $wpdb->escape($descriptions[$i]), 'link_owner' => $user_ID, 'link_rss' => $feeds[$i]);                       
    110                         wp_insert_link($link);
    111                         echo sprintf('<p>'.__('Inserted <strong>%s</strong>').'</p>', $names[$i]);
    112                     }
     104            $link_count = count($names);
     105            for ( $i = 0; $i < $link_count; $i++ ) {
     106                if ('Last' == substr($titles[$i], 0, 4))
     107                    $titles[$i] = '';
     108                if ( 'http' == substr($titles[$i], 0, 4) )
     109                    $titles[$i] = '';
     110                $link = array( 'link_url' => $urls[$i], 'link_name' => $wpdb->escape($names[$i]), 'link_category' => array($cat_id), 'link_description' => $wpdb->escape($descriptions[$i]), 'link_owner' => $user_ID, 'link_rss' => $feeds[$i]);
     111                wp_insert_link($link);
     112                echo sprintf('<p>'.__('Inserted <strong>%s</strong>').'</p>', $names[$i]);
     113            }
    113114?>
    114      <p><?php printf(__('Inserted %1$d links into category %2$s. All done! Go <a href="%3$s">manage those links</a>.'), $link_count, $cat_id, 'link-manager.php') ?></p>
     115
     116<p><?php printf(__('Inserted %1$d links into category %2$s. All done! Go <a href="%3$s">manage those links</a>.'), $link_count, $cat_id, 'link-manager.php') ?></p>
     117
    115118<?php
    116                 } // end if got url
    117                 else
    118                 {
    119                     echo "<p>" . __("You need to supply your OPML url. Press back on your browser and try again") . "</p>\n";
    120                 } // end else
     119} // end if got url
     120else
     121{
     122    echo "<p>" . __("You need to supply your OPML url. Press back on your browser and try again") . "</p>\n";
     123} // end else
    121124
    122                 if ( ! $blogrolling )
    123                     @unlink($opml_url);
     125if ( ! $blogrolling )
     126    apply_filters( 'wp_delete_file', $opml_url);
     127    @unlink($opml_url);
    124128?>
    125129</div>
    126130<?php
    127                 break;
    128             } // end case 1
     131        break;
     132    } // end case 1
    129133} // end switch
    130134
  • tags/2.2/wp-admin/link-manager.php

    r5468 r5480  
    8181$select_cat .= '<option value="all"'  . (($cat_id == 'all') ? " selected='selected'" : '') . '>' . __('All') . "</option>\n";
    8282foreach ((array) $categories as $cat)
    83     $select_cat .= '<option value="' . $cat->cat_ID . '"' . (($cat->cat_ID == $cat_id) ? " selected='selected'" : '') . '>' . wp_specialchars($cat->cat_name) . "</option>\n";
     83    $select_cat .= '<option value="' . $cat->cat_ID . '"' . (($cat->cat_ID == $cat_id) ? " selected='selected'" : '') . '>' . wp_specialchars(apply_filters('link_category', $cat->cat_name)) . "</option>\n";
    8484$select_cat .= "</select>\n";
    8585
     
    132132<?php
    133133    foreach ($links as $link) {
    134         $link->link_name = attribute_escape($link->link_name);
    135         $link->link_description = wp_specialchars($link->link_description);
     134        $link->link_name = attribute_escape(apply_filters('link_title', $link->link_name));
     135        $link->link_description = wp_specialchars(apply_filters('link_description', $link->link_description));
    136136        $link->link_url = clean_url($link->link_url);
    137137        $link->link_category = wp_get_link_cats($link->link_id);
     
    161161                    foreach ($link->link_category as $category) {
    162162                        $cat_name = get_the_category_by_ID($category);
    163                         $cat_name = wp_specialchars($cat_name);
     163                        $cat_name = wp_specialchars(apply_filters('link_category', $cat_name));
    164164                        if ( $cat_id != $category )
    165165                            $cat_name = "<a href='link-manager.php?cat_id=$category'>$cat_name</a>";
     
    181181                default:
    182182                    ?>
    183                     <td><?php do_action('manage_link_custom_column', $column_name, $id); ?></td>
     183                    <td><?php do_action('manage_link_custom_column', $column_name, $link->link_id); ?></td>
    184184                    <?php
    185185                    break;
  • tags/2.2/wp-admin/menu.php

    r5468 r5480  
    77$menu[0] = array(__('Dashboard'), 'read', 'index.php');
    88
    9 if ( strstr($_SERVER['REQUEST_URI'], 'edit-pages.php') )
     9if (strpos($_SERVER['REQUEST_URI'], 'edit-pages.php') !== false)
    1010    $menu[5] = array(__('Write'), 'edit_pages', 'page-new.php');
    1111else
    1212    $menu[5] = array(__('Write'), 'edit_posts', 'post-new.php');
    13 if ( strstr($_SERVER['REQUEST_URI'], 'page-new.php') )
     13if (strpos($_SERVER['REQUEST_URI'], 'page-new.php') !== false)
    1414    $menu[10] = array(__('Manage'), 'edit_pages', 'edit-pages.php');
    1515else
    1616    $menu[10] = array(__('Manage'), 'edit_posts', 'edit.php');
    17    
     17
    1818$menu[15] = array(__('Comments'), 'edit_posts', 'edit-comments.php');
    1919$menu[20] = array(__('Blogroll'), 'manage_links', 'link-manager.php');
     
    7070$submenu['themes.php'][10] = array(__('Theme Editor'), 'edit_themes', 'theme-editor.php');
    7171
     72do_action('_admin_menu');
     73
    7274// Create list of page plugin hook names.
    7375foreach ($menu as $menu_page) {
     
    105107        $_wp_real_parent_file[$old_parent] = $new_parent;
    106108        $menu[$id][2] = $new_parent;
    107        
     109
    108110        foreach ($submenu[$old_parent] as $index => $data) {
    109111            $submenu[$new_parent][$index] = $submenu[$old_parent][$index];
  • tags/2.2/wp-admin/moderation.php

    r5468 r5480  
    122122    <p><strong><?php comment_author() ?></strong> <?php if ($comment->comment_author_email) { ?>| <?php comment_author_email_link() ?> <?php } if ($comment->comment_author_url && 'http://' != $comment->comment_author_url) { ?> | <?php comment_author_url_link() ?> <?php } ?>| <?php _e('IP:') ?> <a href="http://ws.arin.net/cgi-bin/whois.pl?queryinput=<?php comment_author_IP() ?>"><?php comment_author_IP() ?></a></p>
    123123<?php comment_text() ?>
    124 <p><?php comment_date('M j, g:i A'); ?> &#8212; [ <?php
     124<p><?php comment_date(__('M j, g:i A')); ?> &#8212; [ <?php
    125125echo '<a href="comment.php?action=editcomment&amp;c='.$comment->comment_ID.'">' . __('Edit') . '</a> | ';
    126126echo " <a href=\"post.php?action=deletecomment&amp;p=".$comment->comment_post_ID."&amp;comment=".$comment->comment_ID."\" onclick=\"return deleteSomething( 'comment', $comment->comment_ID, '" . js_escape(sprintf(__("You are about to delete this comment by '%s'.\n'Cancel' to stop, 'OK' to delete."), $comment->comment_author )) . "', theCommentList );\">" . __('Delete') . "</a> | "; ?>
  • tags/2.2/wp-admin/options-general.php

    r5468 r5480  
    2626<tr valign="top">
    2727<th scope="row"><?php _e('WordPress address (URL):') ?></th>
    28 <td><input name="siteurl" type="text" id="siteurl" value="<?php form_option('siteurl'); ?>" size="40" class="code" /></td>
     28<td><input name="siteurl" type="text" id="siteurl" value="<?php form_option('siteurl'); ?>" size="40" class="code<?php if ( defined( 'WP_SITEURL' ) ) : ?> disabled" disabled="disabled"<?php else: ?>"<?php endif; ?> /></td>
    2929</tr>
    3030<tr valign="top">
    3131<th scope="row"><?php _e('Blog address (URL):') ?></th>
    32 <td><input name="home" type="text" id="home" value="<?php form_option('home'); ?>" size="40" class="code" /><br /><?php _e('If you want your blog homepage <a href="http://codex.wordpress.org/Giving_WordPress_Its_Own_Directory">to be different than the directory</a> you installed WordPress in, enter that address here.'); ?></td>
     32<td><input name="home" type="text" id="home" value="<?php form_option('home'); ?>" size="40" class="code<?php if ( defined( 'WP_HOME' ) ) : ?> disabled" disabled="disabled"<?php else: ?>"<?php endif; ?> /><br /><?php _e('Enter the address here if you want your blog homepage <a href="http://codex.wordpress.org/Giving_WordPress_Its_Own_Directory">to be different from the directory</a> you installed WordPress.'); ?></td>
    3333</tr>
    3434<tr valign="top">
     
    9898<p class="submit"><input type="submit" name="Submit" value="<?php _e('Update Options &raquo;') ?>" />
    9999<input type="hidden" name="action" value="update" />
    100 <input type="hidden" name="page_options" value="blogname,blogdescription,siteurl,admin_email,users_can_register,gmt_offset,date_format,time_format,home,start_of_week,comment_registration,default_role" />
     100<input type="hidden" name="page_options" value="<?php if ( ! defined( 'WP_SITEURL' ) ) echo 'siteurl,'; if ( ! defined( 'WP_HOME' ) ) echo 'home,'; ?>blogname,blogdescription,admin_email,users_can_register,gmt_offset,date_format,time_format,start_of_week,comment_registration,default_role" />
    101101</p>
    102102</form>
  • tags/2.2/wp-admin/options-head.php

    r5468 r5480  
    11<?php wp_reset_vars(array('action', 'standalone', 'option_group_id')); ?>
    2 
    3 <br clear="all" />
    42
    53<?php if (isset($_GET['updated'])) : ?>
  • tags/2.2/wp-admin/options-misc.php

    r5468 r5480  
    3737
    3838<p><input name="use_linksupdate" type="checkbox" id="use_linksupdate" value="1" <?php checked('1', get_option('use_linksupdate')); ?> />
    39 <label for="use_linksupdate"><?php _e('Track Bookmarks&#8217; Update Times') ?></label></p>
     39<label for="use_linksupdate"><?php _e('Track Links&#8217; Update Times') ?></label></p>
    4040<p>
    4141<label><input type="checkbox" name="hack_file" value="1" <?php checked('1', get_option('hack_file')); ?> /> <?php _e('Use legacy <code>my-hacks.php</code> file support') ?></label>
  • tags/2.2/wp-admin/options-writing.php

    r5468 r5480  
    4242</tr>
    4343<tr valign="top">
    44 <th scope="row"><?php _e('Default bookmark category:') ?></th>
     44<th scope="row"><?php _e('Default link category:') ?></th>
    4545<td><select name="default_link_category" id="default_link_category">
    4646<?php
     
    104104<?php else : ?>
    105105
    106     <p><?php printf(__('WordPress is not notifying any <a href="http://codex.wordpress.org/Update_Services">Update Services</a> because of your blog\'s <a href="%s">privacy settings</a>'), 'options-privacy.php'); ?>
     106    <p><?php printf(__('WordPress is not notifying any <a href="http://codex.wordpress.org/Update_Services">Update Services</a> because of your blog\'s <a href="%s">privacy settings</a>.'), 'options-privacy.php'); ?>
    107107
    108108<?php endif; ?>
  • tags/2.2/wp-admin/options.php

    r5468 r5480  
    7979    }
    8080
    81     return $value; 
     81    return $value;
    8282}
    8383
     
    149149<td>";
    150150
    151     if (stristr($value, "\n")) echo "<textarea class='$class' name='$option->option_name' id='$option->option_name' cols='30' rows='5'>$value</textarea>";
     151    if (strpos($value, "\n") !== false) echo "<textarea class='$class' name='$option->option_name' id='$option->option_name' cols='30' rows='5'>$value</textarea>";
    152152    else echo "<input class='$class' type='text' name='$option->option_name' id='$option->option_name' size='30' value='" . $value . "'$disabled />";
    153    
     153
    154154    echo "</td>
    155155    <td>$option->option_description</td>
  • tags/2.2/wp-admin/page-new.php

    r5468 r5480  
    55$editing = true;
    66wp_enqueue_script('prototype');
     7wp_enqueue_script('interface');
    78wp_enqueue_script('autosave');
    89require_once('admin-header.php');
  • tags/2.2/wp-admin/page.php

    r5468 r5480  
    5353    if($post->post_status == 'draft') {
    5454        wp_enqueue_script('prototype');
     55        wp_enqueue_script('interface');
    5556        wp_enqueue_script('autosave');
    5657    }
     
    6162
    6263    include('edit-page-form.php');
    63     ?>
    64     <div id='preview' class='wrap'>
    65     <h2 id="preview-post"><?php _e('Page Preview (updated when page is saved)'); ?></h2>
    66         <iframe src="<?php echo clean_url(apply_filters('preview_page_link', add_query_arg('preview', 'true', get_permalink($post->ID)))); ?>" width="100%" height="600" ></iframe>
    67     </div>
    68     <?php
    6964    break;
    7065
     
    107102
    108103        if ( isset($_POST['save']) )
    109             $location = "page.php?action=edit&post=$page_ID";       
     104            $location = "page.php?action=edit&post=$page_ID";
    110105    } else {
    111106        if ($_POST['save']) {
     
    148143
    149144    $sendback = wp_get_referer();
    150     if (strstr($sendback, 'page.php')) $sendback = get_option('siteurl') .'/wp-admin/page.php';
    151     elseif (strstr($sendback, 'attachments.php')) $sendback = get_option('siteurl') .'/wp-admin/attachments.php';
     145    if (strpos($sendback, 'page.php') !== false) $sendback = get_option('siteurl') .'/wp-admin/page.php';
     146    elseif (strpos($sendback, 'attachments.php') !== false) $sendback = get_option('siteurl') .'/wp-admin/attachments.php';
    152147    $sendback = preg_replace('|[^a-z0-9-~+_.?#=&;,/:]|i', '', $sendback);
    153148    wp_redirect($sendback);
  • tags/2.2/wp-admin/plugin-editor.php

    r5468 r5480  
    3131        fwrite($f, $newcontent);
    3232        fclose($f);
     33
     34        // Deactivate so we can test it.
     35        $current = get_option('active_plugins');
     36        if ( in_array($file, $current) || isset($_POST['phperror']) ) {
     37            if ( in_array($file, $current) ) {
     38                array_splice($current, array_search( $file, $current), 1 ); // Array-fu!
     39                update_option('active_plugins', $current);
     40            }
     41            wp_redirect(add_query_arg('_wpnonce', wp_create_nonce('edit-plugin-test_' . $file), "plugin-editor.php?file=$file&liveupdate=1"));
     42            exit();
     43        }
    3344        wp_redirect("plugin-editor.php?file=$file&a=te");
    3445    } else {
     
    4455    if ( !current_user_can('edit_plugins') )
    4556        wp_die('<p>'.__('You do not have sufficient permissions to edit plugins for this blog.').'</p>');
     57
     58    if ( $_GET['liveupdate'] ) {
     59        check_admin_referer('edit-plugin-test_' . $file);
     60        $current = get_option('active_plugins');
     61        $plugin = $file;
     62        if ( validate_file($plugin) )
     63            wp_die(__('Invalid plugin.'));
     64        if ( ! file_exists(ABSPATH . PLUGINDIR . '/' . $plugin) )
     65            wp_die(__('Plugin file does not exist.'));
     66        if (!in_array($plugin, $current)) {
     67            wp_redirect("plugin-editor.php?file=$file&phperror=1"); // we'll override this later if the plugin can be included without fatal error
     68            @include(ABSPATH . PLUGINDIR . '/' . $plugin);
     69            $current[] = $plugin;
     70            sort($current);
     71            update_option('active_plugins', $current);
     72        }
     73        wp_redirect("plugin-editor.php?file=$file&a=te");
     74    }
    4675
    4776    require_once('admin-header.php');
     
    6190<?php if (isset($_GET['a'])) : ?>
    6291 <div id="message" class="updated fade"><p><?php _e('File edited successfully.') ?></p></div>
     92<?php elseif (isset($_GET['phperror'])) : ?>
     93 <div id="message" class="updated fade"><p><?php _e('This plugin has been deactivated because your changes resulted in a <strong>fatal error</strong>.') ?></p></div>
    6394<?php endif; ?>
    6495 <div class="wrap">
    6596    <?php
    66     if (is_writeable($real_file)) {
    67         echo '<h2>' . sprintf(__('Editing <strong>%s</strong>'), $file) . '</h2>';
     97    if ( in_array($file, (array) get_option('active_plugins')) ) {
     98        if (is_writeable($real_file)) {
     99            echo '<h2>' . sprintf(__('Editing <strong>%s</strong> (active)'), $file) . '</h2>';
     100        } else {
     101        echo '<h2>' . sprintf(__('Browsing <strong>%s</strong> (active)'), $file) . '</h2>';
     102        }
    68103    } else {
    69         echo '<h2>' . sprintf(__('Browsing <strong>%s</strong>'), $file) . '</h2>';
     104        if (is_writeable($real_file)) {
     105            echo '<h2>' . sprintf(__('Editing <strong>%s</strong> (inactive)'), $file) . '</h2>';
     106        } else {
     107        echo '<h2>' . sprintf(__('Browsing <strong>%s</strong> (inactive)'), $file) . '</h2>';
     108        }
    70109    }
    71110    ?>
     
    91130        </div>
    92131<?php if ( is_writeable($real_file) ) : ?>
     132    <?php if ( in_array($file, (array) get_option('active_plugins')) ) { ?>
     133        <p><?php _e('<strong>Warning:</strong> Making changes to active plugins is not recommended.  If your changes cause a fatal error, the plugin will be automatically deactivated.'); ?></p>
     134    <?php } ?>
    93135    <p class="submit">
    94136    <?php
    95         echo "<input type='submit' name='submit' value='    " . __('Update File &raquo;') . "' tabindex='2' />";
     137        if ( isset($_GET['phperror']) )
     138            echo "<input type='hidden' name='phperror' value='1' /><input type='submit' name='submit' value='" . __('Update File and Attempt to Reactivate &raquo;') . "' tabindex='2' />";
     139        else
     140            echo "<input type='submit' name='submit' value='" . __('Update File &raquo;') . "' tabindex='2' />";
    96141    ?>
    97142    </p>
  • tags/2.2/wp-admin/plugins.php

    r5468 r5480  
    1212            wp_die(__('Plugin file does not exist.'));
    1313        if (!in_array($plugin, $current)) {
     14            wp_redirect('plugins.php?error=true'); // we'll override this later if the plugin can be included without fatal error
     15            ob_start();
     16            @include(ABSPATH . PLUGINDIR . '/' . $plugin);
    1417            $current[] = $plugin;
    1518            sort($current);
    1619            update_option('active_plugins', $current);
    17             include(ABSPATH . PLUGINDIR . '/' . $plugin);
    1820            do_action('activate_' . $plugin);
     21            ob_end_clean();
    1922        }
    20         wp_redirect('plugins.php?activate=true');
     23        wp_redirect('plugins.php?activate=true'); // overrides the ?error=true one above
    2124    } else if ('deactivate' == $_GET['action']) {
    2225        check_admin_referer('deactivate-plugin_' . $_GET['plugin']);
     
    2629        do_action('deactivate_' . trim( $_GET['plugin'] ));
    2730        wp_redirect('plugins.php?deactivate=true');
     31    } elseif ($_GET['action'] == 'deactivate-all') {
     32        check_admin_referer('deactivate-all');
     33        $current = get_option('active_plugins');
     34       
     35        foreach ($current as $plugin) {
     36            array_splice($current, array_search($plugin, $current), 1);
     37            do_action('deactivate_' . $plugin);
     38        }
     39       
     40        update_option('active_plugins', array());
     41        wp_redirect('plugins.php?deactivate-all=true');
    2842    }
    2943    exit;
     
    5973?>
    6074
    61 <?php if (isset($_GET['activate'])) : ?>
    62 <div id="message" class="updated fade"><p><?php _e('Plugin <strong>activated</strong>.') ?></p>
    63 </div>
    64 <?php endif; ?>
    65 <?php if (isset($_GET['deactivate'])) : ?>
    66 <div id="message" class="updated fade"><p><?php _e('Plugin <strong>deactivated</strong>.') ?></p>
    67 </div>
     75<?php if ( isset($_GET['error']) ) : ?>
     76    <div id="message" class="updated fade"><p><?php _e('Plugin could not be activated because it triggered a <strong>fatal error</strong>.') ?></p></div>
     77<?php elseif ( isset($_GET['activate']) ) : ?>
     78    <div id="message" class="updated fade"><p><?php _e('Plugin <strong>activated</strong>.') ?></p></div>
     79<?php elseif ( isset($_GET['deactivate']) ) : ?>
     80    <div id="message" class="updated fade"><p><?php _e('Plugin <strong>deactivated</strong>.') ?></p></div>
     81<?php elseif (isset($_GET['deactivate-all'])) : ?>
     82    <div id="message" class="updated fade"><p><?php _e('All plugins <strong>deactivated</strong>.'); ?></p></div>
    6883<?php endif; ?>
    6984
     
    117132        if ( $style != '' )
    118133            $style = 'class="' . $style . '"';
    119         if ( is_writable(ABSPATH . 'wp-content/plugins/' . $plugin_file) )
     134        if ( is_writable(ABSPATH . PLUGINDIR . '/' . $plugin_file) )
    120135            $edit = "<a href='plugin-editor.php?file=$plugin_file' title='".__('Open this file in the Plugin Editor')."' class='edit'>".__('Edit')."</a>";
    121136        else
     
    136151?>
    137152
     153<tr>
     154    <td colspan="3">&nbsp;</td>
     155    <td colspan="2" style="width:12em;"><a href="<?php echo wp_nonce_url('plugins.php?action=deactivate-all', 'deactivate-all'); ?>" class="delete"><?php _e('Deactivate All Plugins'); ?></a></td>
     156</tr>
     157
    138158</table>
    139159<?php
  • tags/2.2/wp-admin/post-new.php

    r5468 r5480  
    55$editing = true;
    66wp_enqueue_script('prototype');
     7wp_enqueue_script('interface');
    78wp_enqueue_script('autosave');
    89require_once ('./admin-header.php');
  • tags/2.2/wp-admin/post.php

    r5468 r5480  
    4848    $post_ID = $p = (int) $_GET['post'];
    4949    $post = get_post($post_ID);
    50    
     50
    5151    if ( 'page' == $post->post_type ) {
    5252        wp_redirect("page.php?action=edit&post=$post_ID");
     
    6767    include('edit-form-advanced.php');
    6868
    69     ?>
    70     <div id='preview' class='wrap'>
    71     <h2 id="preview-post"><?php _e('Post Preview (updated when post is saved)'); ?></h2>
    72         <iframe src="<?php echo clean_url(apply_filters('preview_post_link', add_query_arg('preview', 'true', get_permalink($post->ID)))); ?>" width="100%" height="600" ></iframe>
    73     </div>
    74     <?php
    7569    break;
    7670
     
    120114            $referredby = preg_replace('|https?://[^/]+|i', '', $_POST['referredby']);
    121115        $referer = preg_replace('|https?://[^/]+|i', '', wp_get_referer());
    122    
     116
    123117        if ($_POST['save']) {
    124118            $location = "post.php?action=edit&post=$post_ID";
     
    161155
    162156    $sendback = wp_get_referer();
    163     if (strstr($sendback, 'post.php')) $sendback = get_option('siteurl') .'/wp-admin/post-new.php';
    164     elseif (strstr($sendback, 'attachments.php')) $sendback = get_option('siteurl') .'/wp-admin/attachments.php';
     157    if (strpos($sendback, 'post.php') !== false) $sendback = get_option('siteurl') .'/wp-admin/post-new.php';
     158    elseif (strpos($sendback, 'attachments.php') !== false) $sendback = get_option('siteurl') .'/wp-admin/attachments.php';
    165159    $sendback = preg_replace('|[^a-z0-9-~+_.?#=&;,/:]|i', '', $sendback);
    166160    wp_redirect($sendback);
  • tags/2.2/wp-admin/rtl.css

    r5468 r5480  
    1515#wphead h1 { font-size: 2.4em; }
    1616
    17 #postdiv , #titlediv, #guiddiv { margin: 0 0 0 8px; }
     17#postdiv, #titlediv, #guiddiv, #tagdiv { margin: 0 0 0 8px; }
    1818
    1919#ed_toolbar input { margin: 3px 0 2px 2px; }
     
    4343#adminmenu {
    4444    padding: .2em 2em .3em .2em;
    45     height: 30px;
    46 }
     45    height: 28px;
     46}
     47
     48#adminmenu li { line-height: 160%; }
    4749
    4850#adminmenu a {
     
    5759}
    5860
    59 #adminmenu li { line-height: 180%; }
    60 
    61 #submenu, #minisub { padding: 3px 3em 0 2em; }
     61#submenu, #minisub { padding: 1px 3em 0 2em; }
     62
     63#submenu { height: 28px; }
     64
     65#submenu li { line-height: 160%; }
     66
     67#submenu a {
     68    margin: 0 0 0 10px;
     69    display: block;
     70    float: right;
     71}
    6272
    6373#submenu .current {
     
    6676}
    6777
    68 #submenu a {
    69     padding: .3em .4em .4em .4em;
    70     margin: 0 0 0 10px;
    71     display: block;
    72     float: right;
    73 }
    74 
    75 #submenu li { line-height: 120%; }
    76 
    7778#currenttheme img {
    7879    float: right;
     
    9192}
    9293
    93 * html #postexcerpt .dbx-toggle-open, * html #postexcerpt .dbx-toggle-open, #postexcerpt div, #attachmentlinks div {
     94#postexcerpt div, #attachmentlinks div {
     95    margin-right: auto;
     96    margin-left: 8px;
     97}
     98
     99* html #postexcerpt .dbx-toggle-open {
    94100    padding-right: 0;
    95101    padding-left: 8px;
     
    191197    margin-left: 3px;
    192198}
     199
     200a.view-link {
     201    right:auto;
     202    left:5%;
     203    margin-right:0;
     204    margin-left:220px;
     205}
  • tags/2.2/wp-admin/setup-config.php

    r5468 r5480  
    158158        switch (substr($line,0,16)) {
    159159            case "define('DB_NAME'":
    160                 fwrite($handle, str_replace("wordpress", $dbname, $line));
     160                fwrite($handle, str_replace("putyourdbnamehere", $dbname, $line));
    161161                break;
    162162            case "define('DB_USER'":
    163                 fwrite($handle, str_replace("'username'", "'$uname'", $line));
     163                fwrite($handle, str_replace("'usernamehere'", "'$uname'", $line));
    164164                break;
    165165            case "define('DB_PASSW":
    166                 fwrite($handle, str_replace("'password'", "'$passwrd'", $line));
     166                fwrite($handle, str_replace("'yourpasswordhere'", "'$passwrd'", $line));
    167167                break;
    168168            case "define('DB_HOST'":
  • tags/2.2/wp-admin/templates.php

    r5468 r5480  
    5353        wp_die('<p>'.__('You do not have sufficient permissions to edit templates for this blog.').'</p>');
    5454
    55     if ( strstr( $file, 'wp-config.php' ) )
     55    if (strpos($file, 'wp-config.php') !== false)
    5656    wp_die('<p>'.__('The config file cannot be edited or viewed through the web interface. Sorry!').'</p>');
    5757
  • tags/2.2/wp-admin/themes.php

    r5468 r5480  
    2727<div id="message1" class="updated fade"><p><?php _e('The active theme is broken.  Reverting to the default theme.'); ?></p></div>
    2828<?php elseif ( isset($_GET['activated']) ) : ?>
    29 <div id="message2" class="updated fade"><p><?php printf(__('New theme activated. <a href="%s">View site &raquo;</a>'), get_bloginfo('home') . '/'); ?></p></div>
     29<div id="message2" class="updated fade"><p><?php printf(__('New theme activated. <a href="%s">View site &raquo;</a>'), get_bloginfo('url') . '/'); ?></p></div>
    3030<?php endif; ?>
    3131
  • tags/2.2/wp-admin/upgrade-functions.php

    r5468 r5480  
    2222    update_option('blog_public', $public);
    2323    $schema = ( isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ) ? 'https://' : 'http://';
    24     $guessurl = preg_replace('|/wp-admin/.*|i', '', $schema . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
     24
     25    if ( defined('WP_SITEURL') && '' != WP_SITEURL )
     26        $guessurl = WP_SITEURL;
     27    else
     28        $guessurl = preg_replace('|/wp-admin/.*|i', '', $schema . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
     29
    2530    update_option('siteurl', $guessurl);
    2631
     
    171176        upgrade_130();
    172177    }
     178   
     179    maybe_disable_automattic_widgets();
    173180
    174181    if ( $wp_current_db_version < 3308 )
     
    653660function __get_option($setting) {
    654661    global $wpdb;
    655 
     662   
     663    if ( $setting == 'home' && defined( 'WP_HOME' ) ) {
     664        return preg_replace( '|/+$|', '', constant( 'WP_HOME' ) );
     665    }
     666   
     667    if ( $setting == 'siteurl' && defined( 'WP_SITEURL' ) ) {
     668        return preg_replace( '|/+$|', '', constant( 'WP_SITEURL' ) );
     669    }
     670   
    656671    $option = $wpdb->get_var("SELECT option_value FROM $wpdb->options WHERE option_name = '$setting'");
    657672
     
    923938        if ($oldfile == 'index.php') { // Check to make sure it's not a new index
    924939            $index = implode('', file("$oldpath/$oldfile"));
    925             if ( strstr( $index, 'WP_USE_THEMES' ) ) {
     940            if (strpos($index, 'WP_USE_THEMES') !== false) {
    926941                if (! @copy(ABSPATH . 'wp-content/themes/default/index.php', "$site_dir/$newfile"))
    927942                    return false;
     
    9951010
    9961011        foreach ($stylelines as $line) {
    997             if (strstr($line, "Theme Name:")) $line = "Theme Name: $theme_name";
    998             elseif (strstr($line, "Theme URI:")) $line = "Theme URI: " . __get_option('siteurl');
    999             elseif (strstr($line, "Description:")) $line = "Description: Your theme";
    1000             elseif (strstr($line, "Version:")) $line = "Version: 1";
    1001             elseif (strstr($line, "Author:")) $line = "Author: You";
    1002             fwrite($f, "{$line}\n");
     1012            if (strpos($line, 'Theme Name:') !== false) $line = 'Theme Name: ' . $theme_name;
     1013            elseif (strpos($line, 'Theme URI:') !== false) $line = 'Theme URI: ' . __get_option('url');
     1014            elseif (strpos($line, 'Description:') !== false) $line = 'Description: Your theme.';
     1015            elseif (strpos($line, 'Version:') !== false) $line = 'Version: 1';
     1016            elseif (strpos($line, 'Author:') !== false) $line = 'Author: You';
     1017            fwrite($f, $line . "\n");
    10031018        }
    10041019        fclose($f);
     
    10951110}
    10961111
     1112function maybe_disable_automattic_widgets() {
     1113    $plugins = __get_option( 'active_plugins' );
     1114   
     1115    foreach ( (array) $plugins as $plugin ) {
     1116        if ( basename( $plugin ) == 'widgets.php' ) {
     1117            array_splice( $plugins, array_search( $plugin, $plugins ), 1 );
     1118            update_option( 'active_plugins', $plugins );
     1119            break;
     1120        }
     1121    }
     1122}
     1123
    10971124?>
  • tags/2.2/wp-admin/upgrade-schema.php

    r5468 r5480  
    11<?php
    22// Here we keep the DB structure and option values
     3
     4$charset_collate = '';
     5
     6if ( version_compare(mysql_get_server_info(), '4.1.0', '>=') ) {
     7    if ( ! empty($wpdb->charset) )
     8        $charset_collate = "DEFAULT CHARACTER SET $wpdb->charset";
     9    if ( ! empty($wpdb->collate) )
     10        $charset_collate .= " COLLATE $wpdb->collate";
     11}
    312
    413$wp_queries="CREATE TABLE $wpdb->categories (
     
    1423  PRIMARY KEY  (cat_ID),
    1524  KEY category_nicename (category_nicename)
    16 );
     25) $charset_collate;
    1726CREATE TABLE $wpdb->comments (
    1827  comment_ID bigint(20) unsigned NOT NULL auto_increment,
     
    3443  KEY comment_approved (comment_approved),
    3544  KEY comment_post_ID (comment_post_ID)
    36 );
     45) $charset_collate;
    3746CREATE TABLE $wpdb->link2cat (
    3847  rel_id bigint(20) NOT NULL auto_increment,
     
    4150  PRIMARY KEY  (rel_id),
    4251  KEY link_id (link_id,category_id)
    43 );
     52) $charset_collate;
    4453CREATE TABLE $wpdb->links (
    4554  link_id bigint(20) NOT NULL auto_increment,
     
    6069  KEY link_category (link_category),
    6170  KEY link_visible (link_visible)
    62 );
     71) $charset_collate;
    6372CREATE TABLE $wpdb->options (
    6473  option_id bigint(20) NOT NULL auto_increment,
     
    7584  PRIMARY KEY  (option_id,blog_id,option_name),
    7685  KEY option_name (option_name)
    77 );
     86) $charset_collate;
    7887CREATE TABLE $wpdb->post2cat (
    7988  rel_id bigint(20) NOT NULL auto_increment,
     
    8291  PRIMARY KEY  (rel_id),
    8392  KEY post_id (post_id,category_id)
    84 );
     93) $charset_collate;
    8594CREATE TABLE $wpdb->postmeta (
    8695  meta_id bigint(20) NOT NULL auto_increment,
     
    91100  KEY post_id (post_id),
    92101  KEY meta_key (meta_key)
    93 );
     102) $charset_collate;
    94103CREATE TABLE $wpdb->posts (
    95104  ID bigint(20) unsigned NOT NULL auto_increment,
     
    120129  KEY post_name (post_name),
    121130  KEY type_status_date (post_type,post_status,post_date,ID)
    122 );
     131) $charset_collate;
    123132CREATE TABLE $wpdb->users (
    124133  ID bigint(20) unsigned NOT NULL auto_increment,
     
    134143  PRIMARY KEY  (ID),
    135144  KEY user_login_key (user_login)
    136 );
     145) $charset_collate;
    137146CREATE TABLE $wpdb->usermeta (
    138147  umeta_id bigint(20) NOT NULL auto_increment,
     
    143152  KEY user_id (user_id),
    144153  KEY meta_key (meta_key)
    145 );";
     154) $charset_collate;";
    146155
    147156function populate_options() {
  • tags/2.2/wp-admin/upgrade.php

    r5468 r5480  
    99
    1010if (isset($_GET['step']))
    11     $step = $_GET['step'];
     11    $step = (int) $_GET['step'];
    1212else
    1313    $step = 0;
     
    2626<body>
    2727<h1 id="logo"><img alt="WordPress" src="images/wordpress-logo.png" /></h1>
    28 <?php
    29 switch($step) {
     28
     29<?php if ( get_option('db_version') == $wp_db_version ) : ?>
     30
     31<h2><?php _e('No Upgrade Required'); ?></h2>
     32<p><?php _e('Your WordPress database is already up-to-date!'); ?></p>
     33<h2 class="step"><a href="<?php echo get_option('home'); ?>/"><?php _e('Continue &raquo;'); ?></a></h2>
     34
     35<?php else :
     36switch($step) :
    3037    case 0:
    3138        $goback = clean_url(stripslashes(wp_get_referer()));
    32 ?>
    33 <p><?php _e('This file upgrades you from any previous version of WordPress to the latest. It may take a while though, so be patient.'); ?></p>
     39?>
     40<h2><?php _e('Database Upgrade Required'); ?></h2>
     41<p><?php _e('Your WordPress database is out-of-date, and must be upgraded before you can continue.'); ?></p>
     42<p><?php _e('The upgrade process may take a while, so please be patient.'); ?></p>
    3443<h2 class="step"><a href="upgrade.php?step=1&amp;backto=<?php echo $goback; ?>"><?php _e('Upgrade WordPress &raquo;'); ?></a></h2>
    3544<?php
     
    3948
    4049        if ( empty( $_GET['backto'] ) )
    41             $backto = __get_option('home');
     50            $backto = __get_option('home') . '/';
    4251        else
    4352            $backto = clean_url(stripslashes($_GET['backto']));
    4453?>
    45 <h2><?php _e('Step 1'); ?></h2>
    46     <p><?php printf(__("There's actually only one step. So if you see this, you're done. <a href='%s'>Have fun</a>!"),  $backto); ?></p>
     54<h2><?php _e('Upgrade Complete'); ?></h2>
     55    <p><?php _e('Your WordPress database has been successfully upgraded!'); ?></p>
     56    <h2 class="step"><a href="<?php echo $backto; ?>"><?php _e('Continue &raquo;'); ?></a></h2>
    4757
    4858<!--
     
    5666<?php
    5767        break;
    58 }
     68endswitch;
     69endif;
    5970?>
    6071</body>
  • tags/2.2/wp-admin/upload-functions.php

    r5468 r5480  
    1414    if ( isset($attachment_data['width']) )
    1515        list($width,$height) = wp_shrink_dimensions($attachment_data['width'], $attachment_data['height'], 171, 128);
    16        
     16
    1717    ob_start();
    1818        the_title();
    1919        $post_title = attribute_escape(ob_get_contents());
    2020    ob_end_clean();
    21     $post_content = apply_filters( 'content_edit_pre', $post->post_content );
    22    
     21    $post_content = attribute_escape(apply_filters( 'content_edit_pre', $post->post_content ));
     22
    2323    $class = 'text';
    2424    $innerHTML = get_attachment_innerHTML( $id, false, $dims );
     
    3636
    3737    if ( $href )
    38         $r .= "<a id='file-link-$id' href='" . clean_url($href) ."' title='$post_title' class='file-link $class'>\n";
     38        $r .= "<a id='file-link-$id' href='$href' title='$post_title' class='file-link $class'>\n";
    3939    if ( $href || $image_src )
    4040        $r .= "\t\t\t$innerHTML";
     
    286286    global $wpdb, $action, $paged;
    287287    $old_vars = compact( 'paged' );
    288    
     288
    289289    switch ( $action ) :
    290290    case 'edit' :
     
    356356    }
    357357}
     358
     359?>
  • tags/2.2/wp-admin/upload.css

    r5468 r5480  
    4545
    4646#upload-menu li #current-tab-nav {
     47    background: #f9fcfe;
    4748    float: left;
    4849    padding: 5px 5px 0 0;
  • tags/2.2/wp-admin/upload.php

    r5468 r5480  
    9090    $href = add_query_arg( array('tab' => $t, 'ID' => '', 'action' => '', 'paged' => '') );
    9191    if ( isset($tab_array[4]) && is_array($tab_array[4]) )
    92         add_query_arg( $tab_array[4], $href );
     92        $href = add_query_arg( $tab_array[4], $href );
    9393    $_href = clean_url( $href);
    9494    $page_links = '';
  • tags/2.2/wp-admin/user-edit.php

    r5468 r5480  
    5656    <p><strong><?php _e('User updated.') ?></strong></p>
    5757    <?php if ( $wp_http_referer ) : ?>
    58     <p><a href="<?php echo clean_url($wp_http_referer); ?>"><?php _e('&laquo; Back to Authors and Users'); ?></a></p>
     58    <p><a href="users.php"><?php _e('&laquo; Back to Authors and Users'); ?></a></p>
    5959    <?php endif; ?>
    6060</div>
     
    8383<input type="hidden" name="checkuser_id" value="<?php echo $user_ID ?>" />
    8484</p>
     85
     86<p><label for="rich_editing"><input name="rich_editing" type="checkbox" id="rich_editing" value="true" <?php checked('true', $profileuser->rich_editing); ?> /> <?php _e('Use the visual editor when writing'); ?></label></p>
     87
     88<p class="submit"><input type="submit" value="<?php _e('Update User &raquo;'); ?>" name="submit" /></p>
    8589
    8690<fieldset>
  • tags/2.2/wp-admin/users.php

    r5468 r5480  
    8686                'total' => ceil($this->total_users_for_query / $this->users_per_page),
    8787                'current' => $this->page,
    88                 'prev_text' => '&laquo; Previous Page',
    89                 'next_text' => 'Next Page &raquo;',
     88                'prev_text' => __('&laquo; Previous Page'),
     89                'next_text' => __('Next Page &raquo;'),
    9090                'base' => 'users.php?%_%',
    9191                'format' => 'userspage=%#%',
     
    339339
    340340    <form action="" method="get" name="search" id="search">
    341         <p><input type="text" name="usersearch" id="usersearch" value="<?php echo attribute_escape($wp_user_search->search_term); ?>" /> <input type="submit" value="<?php _e('Search   users &raquo;'); ?>" class="button" /></p>
     341        <p><input type="text" name="usersearch" id="usersearch" value="<?php echo attribute_escape($wp_user_search->search_term); ?>" /> <input type="submit" value="<?php _e('Search Users &raquo;'); ?>" class="button" /></p>
    342342    </form>
    343343
     
    451451<div class="narrow">
    452452
    453 <?php echo '<p>'.sprintf(__('Users can <a href="%1$s">register themselves</a> or you can manually create users here.'), get_option('siteurl').'/wp-register.php').'</p>'; ?>
     453<?php
     454    if ( get_option('users_can_register') )
     455        echo '<p>' . sprintf(__('Users can <a href="%1$s">register themselves</a> or you can manually create users here.'), get_option('siteurl').'/wp-register.php') . '</p>';
     456    else
     457        echo '<p>' . sprintf(__('Users cannot currently <a href="%1$s">register themselves</a>, but you can manually create users here.'), get_option('siteurl').'/wp-admin/options-general.php#users_can_register') . '</p>';
     458?>
    454459<form action="#add-new-user" method="post" name="adduser" id="adduser">
    455460<?php wp_nonce_field('add-user') ?>
  • tags/2.2/wp-admin/wp-admin.css

    r5468 r5480  
    202202    border: 1px solid #b2b2b2;
    203203    color: #000;
    204     font:  13px Verdana, Arial, Helvetica, sans-serif;
     204    font: 13px Verdana, Arial, Helvetica, sans-serif;
    205205    margin: 1px;
    206206    padding: 3px;
     
    209209#uploading {
    210210    border-style: none;
    211     padding: 0px;
     211    padding: 0;
    212212    margin-bottom: 16px;
    213213    height: 18em;
     
    293293}
    294294
     295.commentlist li li {
     296    border-bottom: 0px;
     297    padding: 0;
     298}
     299
    295300.commentlist p {
    296301    padding: 0;
     
    460465}
    461466
    462 
    463467#adminmenu .current, #submenu .current {
    464468    font-weight: bold;
     
    485489    list-style: none;
    486490    text-align: center;
     491    white-space: nowrap;
    487492}
    488493
     
    530535}
    531536
    532 
    533537#categorydiv input, #poststatusdiv input, #commentstatusdiv input, #pingstatusdiv input {
    534538    border: none;
     
    537541#postdiv, #titlediv, #guiddiv {
    538542    margin: 0 8px 0 0;
    539     padding: 0px;
     543    padding: 0;
    540544}
    541545
    542546#postdivrich {
    543     margin: 0px;
    544     padding: 0px;
     547    margin: 0;
     548    padding: 0;
    545549}
    546550
    547551#content {
    548     margin: 0 0 0 0;
     552    margin: 0;
    549553    width: 100%;
    550554}
    551555
    552556#postdivrich #content {
    553     padding: .7em;
     557    padding: 5px;
    554558    line-height: 140%;
    555559}
    556560
    557561#titlediv input, #guiddiv input {
    558     margin: 0px;
     562    margin: 0;
    559563    width: 100%;
    560564}
     
    580584#postdivrich #quicktags {
    581585    background: #f0f0ee;
    582     padding: 0px;
     586    padding: 0;
    583587    border: 1px solid #ccc;
    584588    border-bottom: none;
     
    594598
    595599#quicktags #ed_toolbar {
    596     padding: 0px 2px;
     600    padding: 0 2px;
    597601}
    598602
    599603#ed_toolbar input {
    600     background: #fff url( images/fade-butt.png ) repeat-x 0px -2px;
     604    background: #fff url( images/fade-butt.png ) repeat-x 0 -2px;
    601605    margin: 3px 2px 2px;
    602606}
     
    626630#title {
    627631    font-size: 1.7em;
    628     padding: 4px;
     632    padding: 4px 3px;
    629633}
    630634
     
    644648
    645649#excerpt, .attachmentlinks {
    646     margin: 0px;
     650    margin: 0;
    647651    height: 4em;
    648652    width: 100%;
     
    729733    display: block;
    730734    border-bottom: none;
    731 }
    732 
    733 #login .hide {
    734     display: none;
     735    text-indent: -9999px;
    735736}
    736737
     
    815816#postcustom table {
    816817    border: 1px solid #ccc;
    817     margin: 0px;
     818    margin: 0;
    818819    width: 100%;
    819820}
     
    836837
    837838* html #template div {
    838     margin-right: 0px;
     839    margin-right: 0;
    839840}
    840841
     
    891892    letter-spacing: -.05em;
    892893    margin: 0;
    893     font-family: Georgia, "Times New Roman", Times, serif
     894    font-family: Georgia, "Times New Roman", Times, serif;
    894895}
    895896
     
    968969set display:none; */
    969970.zerosize {
    970     height: 0px;
    971     width: 0px;
    972     margin: 0px;
    973     border: 0px;
    974     padding: 0px;
     971    height: 0;
     972    width: 0;
     973    margin: 0;
     974    border: 0;
     975    padding: 0;
    975976    overflow: hidden;
    976977    position: absolute;
     
    979980/* Box stuff */
    980981.dbx-clone {
    981     position:absolute;
    982     visibility:hidden;
     982    position: absolute;
     983    visibility: hidden;
    983984}
    984985.dbx-clone, .dbx-clone .dbx-handle-cursor {
    985     cursor:move !important;
     986    cursor: move !important;
    986987}
    987988.dbx-dummy {
    988     display:block;
    989     width:0;
    990     height:0;
    991     overflow:hidden;
     989    display: block;
     990    width: 0;
     991    height: 0;
     992    overflow: hidden;
    992993}
    993994.dbx-group, .dbx-box, .dbx-handle {
    994     position:relative;
    995     display:block;
     995    position: relative;
     996    display: block;
    996997}
    997998
     
    10011002
    10021003* html #themeselect {
    1003     padding: 0px 3px;
     1004    padding: 0 3px;
    10041005    height: 22px;
    10051006}
     
    10111012*****************************************************************/
    10121013.dbx-box {
    1013     margin:0;
    1014     padding:0;
    1015     border:none;
     1014    margin: 0;
     1015    padding: 0;
     1016    border: none;
    10161017}
    10171018
     
    10211022}
    10221023#moremeta fieldset div {
    1023     margin: 2px 0 0 0px;
     1024    margin: 2px 0 0 0;
    10241025    padding: 7px;
    10251026}
     
    10841085}
    10851086
    1086 #your-profile fieldset input  {
     1087#your-profile fieldset input {
    10871088    width: 100%;
    10881089    font-size: 20px;
     
    11231124/* handles */
    11241125
    1125 .dbx-handle  {
     1126.dbx-handle {
    11261127    background: #2685af;
    11271128    padding: 6px 1em 2px;
     
    11581159    margin-left: 8px;
    11591160    background: url(images/box-bg-right.gif) repeat-y right;
    1160     padding: 10px 10px 15px 0px;
     1161    padding: 10px 10px 15px 0;
    11611162}
    11621163
     
    11911192}
    11921193
    1193 
    11941194/* handle cursors */
    11951195.dbx-handle-cursor {
     
    11991199/* toggle images */
    12001200a.dbx-toggle, a.dbx-toggle:visited {
    1201     display:block;
     1201    display: block;
    12021202    overflow: hidden;
    12031203    background-image: url( images/toggle.gif );
    12041204    position: absolute;
    1205     top: 0px;
    1206     right: 0px;
     1205    top: 0;
     1206    right: 0;
    12071207    background-repeat: no-repeat;
    1208     border: 0px;
    1209     margin: 0px;
    1210     padding: 0px;
     1208    border: 0;
     1209    margin: 0;
     1210    padding: 0;
    12111211}
    12121212
     
    12141214    height: 25px;
    12151215    width: 27px;
    1216     background-position: 0 0px;
     1216    background-position: 0 0;
    12171217}
    12181218
     
    12971297
    12981298#edButtons input, #edButtons input:active {
    1299     margin: 0px 2px -1px;
     1299    margin: 0 2px -1px;
    13001300}
    13011301
     
    13061306
    13071307#edButtons input.edButtonBack, #edButtons input.edButtonBack:active {
    1308     background: #fff url( images/fade-butt.png ) repeat-x 0px 15px;
     1308    background: #fff url( images/fade-butt.png ) repeat-x 0 15px;
    13091309    border-bottom: 1px solid #ccc;
    13101310}
     
    13331333    margin: 0 6px;
    13341334}
     1335
     1336a.view-link {
     1337    position: absolute;
     1338    right: 5%;
     1339    margin-right: 220px;
     1340    text-decoration:underline;
     1341}
  • tags/2.2/wp-atom.php

    r5468 r5480  
    66}
    77
    8 header('Content-type: application/atom+xml; charset=' . get_option('blog_charset'), true);
    9 $more = 1;
     8require (ABSPATH . WPINC . '/feed-atom.php');
    109
    1110?>
    12 <?php echo '<?xml version="1.0" encoding="'.get_option('blog_charset').'"?'.'>'; ?>
    13 <feed version="0.3"
    14     xmlns="http://purl.org/atom/ns#"
    15     xmlns:dc="http://purl.org/dc/elements/1.1/"
    16     xml:lang="<?php echo get_option('rss_language'); ?>"
    17     <?php do_action('atom_ns'); ?>
    18 >
    19     <title><?php bloginfo_rss('name') ?></title>
    20     <link rel="alternate" type="text/html" href="<?php bloginfo_rss('home') ?>" />
    21     <tagline><?php bloginfo_rss("description") ?></tagline>
    22     <modified><?php echo mysql2date('Y-m-d\TH:i:s\Z', get_lastpostmodified('GMT'), false); ?></modified>
    23     <copyright>Copyright <?php echo mysql2date('Y', get_lastpostdate('blog'), 0); ?></copyright>
    24     <generator url="http://wordpress.org/" version="<?php bloginfo_rss('version'); ?>">WordPress</generator>
    25     <?php do_action('atom_head'); ?>
    26     <?php while (have_posts()) : the_post(); ?>
    27     <entry>
    28         <author>
    29             <name><?php the_author() ?></name>
    30         </author>
    31         <title type="text/html" mode="escaped"><![CDATA[<?php the_title_rss() ?>]]></title>
    32         <link rel="alternate" type="text/html" href="<?php permalink_single_rss() ?>" />
    33         <id><?php the_guid(); ?></id>
    34         <modified><?php echo get_post_time('Y-m-d\TH:i:s\Z', true); ?></modified>
    35         <issued><?php echo get_post_time('Y-m-d\TH:i:s\Z', true); ?></issued>
    36         <?php the_category_rss('rdf') ?>
    37         <summary type="<?php bloginfo('html_type'); ?>" mode="escaped"><![CDATA[<?php the_excerpt_rss(); ?>]]></summary>
    38 <?php if ( !get_option('rss_use_excerpt') ) : ?>
    39         <content type="<?php bloginfo('html_type'); ?>" mode="escaped" xml:base="<?php permalink_single_rss() ?>"><![CDATA[<?php the_content('', 0, '') ?>]]></content>
    40 <?php endif; ?>
    41 <?php rss_enclosure(); ?>
    42 <?php do_action('atom_entry'); ?>
    43     </entry>
    44     <?php endwhile ; ?>
    45 </feed>
  • tags/2.2/wp-blog-header.php

    r5468 r5480  
    33if (! isset($wp_did_header)):
    44if ( !file_exists( dirname(__FILE__) . '/wp-config.php') ) {
    5     if ( strstr( $_SERVER['PHP_SELF'], 'wp-admin') ) $path = '';
     5    if (strpos($_SERVER['PHP_SELF'], 'wp-admin') !== false) $path = '';
    66    else $path = 'wp-admin/';
    77
    8   require_once( dirname(__FILE__) . '/wp-includes/functions.php');
    9   wp_die("There doesn't seem to be a <code>wp-config.php</code> file. I need this before we can get started. Need more help? <a href='http://codex.wordpress.org/Editing_wp-config.php'>We got it</a>. You can <a href='{$path}setup-config.php'>create a <code>wp-config.php</code> file through a web interface</a>, but this doesn't work for all server setups. The safest way is to manually create the file.", "WordPress &rsaquo; Error");
     8    require_once( dirname(__FILE__) . '/wp-includes/classes.php');
     9    require_once( dirname(__FILE__) . '/wp-includes/functions.php');
     10    require_once( dirname(__FILE__) . '/wp-includes/plugin.php');
     11    wp_die("There doesn't seem to be a <code>wp-config.php</code> file. I need this before we can get started. Need more help? <a href='http://codex.wordpress.org/Editing_wp-config.php'>We got it</a>. You can <a href='{$path}setup-config.php'>create a <code>wp-config.php</code> file through a web interface</a>, but this doesn't work for all server setups. The safest way is to manually create the file.", "WordPress &rsaquo; Error");
    1012}
    1113
  • tags/2.2/wp-comments-post.php

    r5468 r5480  
    11<?php
     2if ($_SERVER["REQUEST_METHOD"] != "POST") {
     3    header('Allow: POST');
     4    header("HTTP/1.1 405 Method Not Allowed");
     5    header("Content-type: text/plain");
     6    exit;
     7}
    28require( dirname(__FILE__) . '/wp-config.php' );
    39
     
    1925}
    2026
    21 $comment_author       = trim($_POST['author']);
     27$comment_author       = trim(strip_tags($_POST['author']));
    2228$comment_author_email = trim($_POST['email']);
    2329$comment_author_url   = trim($_POST['url']);
  • tags/2.2/wp-commentsrss2.php

    r5468 r5480  
    66}
    77
    8 header('Content-type: text/xml;charset=' . get_option('blog_charset'), true);
     8require (ABSPATH . WPINC . '/feed-rss2-comments.php');
    99
    10 echo '<?xml version="1.0" encoding="'.get_option('blog_charset').'"?'.'>';
    1110?>
    12 <!-- generator="wordpress/<?php echo $wp_version ?>" -->
    13 <rss version="2.0"
    14     xmlns:content="http://purl.org/rss/1.0/modules/content/">
    15 <channel>
    16 <?php
    17 $i = 0;
    18 if (have_posts()) :
    19   while (have_posts()) : the_post();
    20     if ($i < 1) {
    21         $i++;
    22 ?>
    23     <title><?php if (is_single() || is_page() ) { printf(__('Comments on: %s'), get_the_title_rss()); } else { printf(__('Comments for %s'), get_bloginfo_rss("name")); } ?></title>
    24     <link><?php (is_single()) ? permalink_single_rss() : bloginfo_rss("url") ?></link>
    25     <description><?php bloginfo_rss("description") ?></description>
    26     <pubDate><?php echo gmdate('r'); ?></pubDate>
    27     <generator>http://wordpress.org/?v=<?php echo $wp_version ?></generator>
    28 
    29 <?php
    30         if (is_single() || is_page()) {
    31             $comments = $wpdb->get_results("SELECT comment_ID, comment_author, comment_author_email,
    32             comment_author_url, comment_date, comment_date_gmt, comment_content, comment_post_ID,
    33             $wpdb->posts.ID, $wpdb->posts.post_password FROM $wpdb->comments
    34             LEFT JOIN $wpdb->posts ON comment_post_id = id WHERE comment_post_ID = '" . get_the_ID() . "'
    35             AND $wpdb->comments.comment_approved = '1' AND $wpdb->posts.post_status = 'publish'
    36             AND post_date_gmt < '" . gmdate("Y-m-d H:i:59") . "'
    37             ORDER BY comment_date_gmt ASC" );
    38         } else { // if no post id passed in, we'll just ue the last 10 comments.
    39             $comments = $wpdb->get_results("SELECT comment_ID, comment_author, comment_author_email,
    40             comment_author_url, comment_date, comment_date_gmt, comment_content, comment_post_ID,
    41             $wpdb->posts.ID, $wpdb->posts.post_password FROM $wpdb->comments
    42             LEFT JOIN $wpdb->posts ON comment_post_id = id WHERE $wpdb->posts.post_status = 'publish'
    43             AND $wpdb->comments.comment_approved = '1' AND post_date_gmt < '" . gmdate("Y-m-d H:i:s") . "' 
    44             ORDER BY comment_date_gmt DESC LIMIT " . get_option('posts_per_rss') );
    45         }
    46     // this line is WordPress' motor, do not delete it.
    47         if ($comments) {
    48             foreach ($comments as $comment) {
    49                 $GLOBALS['comment'] =& $comment;
    50                 // Some plugins may need to know the metadata
    51                 // associated with this comment's post:
    52                 get_post_custom($comment->comment_post_ID);
    53 ?>
    54     <item>
    55         <title><?php if ( ! (is_single() || is_page()) ) {
    56             $title = get_the_title($comment->comment_post_ID);
    57             $title = apply_filters('the_title', $title);
    58             $title = apply_filters('the_title_rss', $title);
    59             printf(__('Comment on %1$s by %2$s'), $title, get_comment_author_rss());
    60         } else {
    61             printf(__('By: %s'), get_comment_author_rss());
    62         } ?></title>
    63         <link><?php comment_link() ?></link>
    64         <author><?php echo get_comment_author_rss() ?></author>
    65         <pubDate><?php echo mysql2date('D, d M Y H:i:s +0000', get_comment_time('Y-m-d H:i:s', true), false); ?></pubDate>
    66         <guid><?php comment_link() ?></guid>
    67             <?php
    68             if (!empty($comment->post_password) && $_COOKIE['wp-postpass'] != $comment->post_password) {
    69             ?>
    70         <description><?php _e('Protected Comments: Please enter your password to view comments.'); ?></description>
    71         <content:encoded><![CDATA[<?php echo get_the_password_form() ?>]]></content:encoded>
    72             <?php
    73             } else {
    74             ?>
    75         <description><?php comment_text_rss() ?></description>
    76         <content:encoded><![CDATA[<?php comment_text() ?>]]></content:encoded>
    77             <?php
    78             } // close check for password
    79             do_action('commentrss2_item', $comment->comment_ID, $comment->comment_post_ID);
    80             ?>
    81     </item>
    82 <?php
    83             }
    84         }
    85     }
    86 endwhile; endif;
    87 ?>
    88 </channel>
    89 </rss>
  • tags/2.2/wp-config-sample.php

    • Property svn:eol-style changed from native to CRLF
    r5468 r5480  
    11<?php
    22// ** MySQL settings ** //
    3 define('DB_NAME', 'wordpress');    // The name of the database
    4 define('DB_USER', 'username');     // Your MySQL username
    5 define('DB_PASSWORD', 'password'); // ...and password
     3define('DB_NAME', 'putyourdbnamehere');    // The name of the database
     4define('DB_USER', 'usernamehere');     // Your MySQL username
     5define('DB_PASSWORD', 'yourpasswordhere'); // ...and password
    66define('DB_HOST', 'localhost');    // 99% chance you won't need to change this value
     7define('DB_CHARSET', 'utf8');
     8define('DB_COLLATE', '');
    79
    810// You can have multiple installations in one database if you give each a unique prefix
     
    1012
    1113// Change this to localize WordPress.  A corresponding MO file for the
    12 // chosen language must be installed to wp-includes/languages.
    13 // For example, install de.mo to wp-includes/languages and set WPLANG to 'de'
     14// chosen language must be installed to wp-content/languages.
     15// For example, install de.mo to wp-content/languages and set WPLANG to 'de'
    1416// to enable German language support.
    1517define ('WPLANG', '');
  • tags/2.2/wp-content/index.php

    • Property svn:eol-style set to native
  • tags/2.2/wp-content/themes/classic/comments-popup.php

    r5468 r5480  
    2222<h2 id="comments"><?php _e("Comments"); ?></h2>
    2323
    24 <p><a href="<?php echo get_option('siteurl'); ?>/wp-commentsrss2.php?p=<?php echo $post->ID; ?>"><?php _e("<abbr title=\"Really Simple Syndication\">RSS</abbr> feed for comments on this post."); ?></a></p>
     24<p><a href="<?php echo get_post_comments_feed_link($post->ID); ?>"><?php _e("<abbr title=\"Really Simple Syndication\">RSS</abbr> feed for comments on this post."); ?></a></p>
    2525
    2626<?php if ('open' == $post->ping_status) { ?>
     
    5757
    5858<form action="<?php echo get_option('siteurl'); ?>/wp-comments-post.php" method="post" id="commentform">
     59<?php if ( $user_ID ) : ?>
     60    <p>Logged in as <a href="<?php echo get_option('siteurl'); ?>/wp-admin/profile.php"><?php echo $user_identity; ?></a>. <a href="<?php echo get_option('siteurl'); ?>/wp-login.php?action=logout" title="Log out of this account">Logout &raquo;</a></p>
     61<?php else : ?>
    5962    <p>
    6063      <input type="text" name="author" id="author" class="textarea" value="<?php echo $comment_author; ?>" size="28" tabindex="1" />
     
    7376       <label for="url"><?php _e("<abbr title=\"Universal Resource Locator\">URL</abbr>"); ?></label>
    7477    </p>
     78<?php endif; ?>
    7579
    7680    <p>
  • tags/2.2/wp-content/themes/classic/sidebar.php

    r5468 r5480  
    44
    55<ul>
     6<?php   /* Widgetized sidebar, if you have the plugin installed. */
     7        if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar() ) : ?>
    68    <?php wp_list_pages('title_li=' . __('Pages:')); ?>
    79    <?php wp_list_bookmarks('title_after=&title_before='); ?>
     
    3335    </ul>
    3436 </li>
     37<?php endif; ?>
    3538
    3639</ul>
  • tags/2.2/wp-content/themes/default/archive.php

    r5468 r5480  
    77         <?php $post = $posts[0]; // Hack. Set $post so that the_date() works. ?>
    88<?php /* If this is a category archive */ if (is_category()) { ?>
    9         <h2 class="pagetitle">Archive for the &#8216;<?php echo single_cat_title(); ?>&#8217; Category</h2>
     9        <h2 class="pagetitle">Archive for the &#8216;<?php single_cat_title(); ?>&#8217; Category</h2>
    1010
    1111      <?php /* If this is a daily archive */ } elseif (is_day()) { ?>
  • tags/2.2/wp-content/themes/default/attachment.php

    • Property svn:eol-style set to native
  • tags/2.2/wp-content/themes/default/comments-popup.php

    r5468 r5480  
    2222<h2 id="comments">Comments</h2>
    2323
    24 <p><a href="<?php echo get_option('siteurl'); ?>/wp-commentsrss2.php?p=<?php echo $post->ID; ?>"><abbr title="Really Simple Syndication">RSS</abbr> feed for comments on this post.</a></p>
     24<p><a href="<?php echo get_post_comments_feed_link($post->ID); ?>"><abbr title="Really Simple Syndication">RSS</abbr> feed for comments on this post.</a></p>
    2525
    2626<?php if ('open' == $post->ping_status) { ?>
     
    5757
    5858<form action="<?php echo get_option('siteurl'); ?>/wp-comments-post.php" method="post" id="commentform">
     59<?php if ( $user_ID ) : ?>
     60    <p>Logged in as <a href="<?php echo get_option('siteurl'); ?>/wp-admin/profile.php"><?php echo $user_identity; ?></a>. <a href="<?php echo get_option('siteurl'); ?>/wp-login.php?action=logout" title="Log out of this account">Logout &raquo;</a></p>
     61<?php else : ?>
    5962    <p>
    6063      <input type="text" name="author" id="author" class="textarea" value="<?php echo $comment_author; ?>" size="28" tabindex="1" />
     
    7376       <label for="url"><abbr title="Universal Resource Locator">URL</abbr></label>
    7477    </p>
     78<?php endif; ?>
    7579
    7680    <p>
  • tags/2.2/wp-content/themes/default/comments.php

    r5468 r5480  
    77            ?>
    88
    9             <p class="nocomments">This post is password protected. Enter the password to view comments.<p>
     9            <p class="nocomments">This post is password protected. Enter the password to view comments.</p>
    1010
    1111            <?php
     
    1515
    1616    /* This variable is for alternating comment background */
    17     $oddcomment = 'alt';
     17    $oddcomment = 'class="alt" ';
    1818?>
    1919
     
    2727    <?php foreach ($comments as $comment) : ?>
    2828
    29         <li class="<?php echo $oddcomment; ?>" id="comment-<?php comment_ID() ?>">
     29        <li <?php echo $oddcomment; ?>id="comment-<?php comment_ID() ?>">
    3030            <cite><?php comment_author_link() ?></cite> Says:
    3131            <?php if ($comment->comment_approved == '0') : ?>
     
    3434            <br />
    3535
    36             <small class="commentmetadata"><a href="#comment-<?php comment_ID() ?>" title=""><?php comment_date('F jS, Y') ?> at <?php comment_time() ?></a> <?php edit_comment_link('e','',''); ?></small>
     36            <small class="commentmetadata"><a href="#comment-<?php comment_ID() ?>" title=""><?php comment_date('F jS, Y') ?> at <?php comment_time() ?></a> <?php edit_comment_link('edit','&nbsp;&nbsp;',''); ?></small>
    3737
    3838            <?php comment_text() ?>
     
    4040        </li>
    4141
    42     <?php /* Changes every other comment to a different class */
    43         if ('alt' == $oddcomment) $oddcomment = '';
    44         else $oddcomment = 'alt';
     42    <?php
     43        /* Changes every other comment to a different class */
     44        $oddcomment = ( empty( $oddcomment ) ) ? 'class="alt" ' : '';
    4545    ?>
    4646
     
    8989<?php endif; ?>
    9090
    91 <!--<p><small><strong>XHTML:</strong> You can use these tags: <?php echo allowed_tags(); ?></small></p>-->
     91<!--<p><small><strong>XHTML:</strong> You can use these tags: <code><?php echo allowed_tags(); ?></code></small></p>-->
    9292
    9393<p><textarea name="comment" id="comment" cols="100%" rows="10" tabindex="4"></textarea></p>
  • tags/2.2/wp-content/themes/default/footer.php

    r5468 r5480  
    22<hr />
    33<div id="footer">
    4 <!-- If you'd like to support WordPress, having the "powered by" link someone on your blog is the best way, it's our only promotion or advertising. -->
     4<!-- If you'd like to support WordPress, having the "powered by" link somewhere on your blog is the best way, it's our only promotion or advertising. -->
    55    <p>
    66        <?php bloginfo('name'); ?> is proudly powered by
  • tags/2.2/wp-content/themes/default/functions.php

    r5468 r5480  
    11<?php
     2if ( function_exists('register_sidebar') )
     3    register_sidebar(array(
     4        'before_widget' => '<li id="%1$s" class="widget %2$s">',
     5        'after_widget' => '</li>',
     6        'before_title' => '<h2 class="widgettitle">',
     7        'after_title' => '</h2>',
     8    ));
    29
    310function kubrick_head() {
     
    2633
    2734function kubrick_upper_color() {
    28     if ( strstr( $url = kubrick_header_image_url(), 'header-img.php?' ) ) {
     35    if (strpos($url = kubrick_header_image_url(), 'header-img.php?') !== false) {
    2936        parse_str(substr($url, strpos($url, '?') + 1), $q);
    3037        return $q['upper'];
     
    3441
    3542function kubrick_lower_color() {
    36     if ( strstr( $url = kubrick_header_image_url(), 'header-img.php?' ) ) {
     43    if (strpos($url = kubrick_header_image_url(), 'header-img.php?') !== false) {
    3744        parse_str(substr($url, strpos($url, '?') + 1), $q);
    3845        return $q['lower'];
     
    7683    if ( $_GET['page'] == basename(__FILE__) ) {
    7784        if ( 'save' == $_REQUEST['action'] ) {
     85            check_admin_referer('kubrick-header');
    7886            if ( isset($_REQUEST['njform']) ) {
    7987                if ( isset($_REQUEST['defaults']) ) {
     
    8492                    if ( '' == $_REQUEST['njfontcolor'] )
    8593                        delete_option('kubrick_header_color');
    86                     else
    87                         update_option('kubrick_header_color', $_REQUEST['njfontcolor']);
    88 
     94                    else {
     95                        $fontcolor = preg_replace('/^.*(#[0-9a-fA-F]{6})?.*$/', '$1', $_REQUEST['njfontcolor']);
     96                        update_option('kubrick_header_color', $fontcolor);
     97                    }
    8998                    if ( preg_match('/[0-9A-F]{6}|[0-9A-F]{3}/i', $_REQUEST['njuppercolor'], $uc) && preg_match('/[0-9A-F]{6}|[0-9A-F]{3}/i', $_REQUEST['njlowercolor'], $lc) ) {
    9099                        $uc = ( strlen($uc[0]) == 3 ) ? $uc[0]{0}.$uc[0]{0}.$uc[0]{1}.$uc[0]{1}.$uc[0]{2}.$uc[0]{2} : $uc[0];
    91100                        $lc = ( strlen($lc[0]) == 3 ) ? $lc[0]{0}.$lc[0]{0}.$lc[0]{1}.$lc[0]{1}.$lc[0]{2}.$lc[0]{2} : $lc[0];
    92                         update_option('kubrick_header_image', "header-img.php?upper=$uc&amp;lower=$lc");
     101                        update_option('kubrick_header_image', "header-img.php?upper=$uc&lower=$lc");
    93102                    }
    94103
     
    103112
    104113                if ( isset($_REQUEST['headerimage']) ) {
     114                    check_admin_referer('kubrick-header');
    105115                    if ( '' == $_REQUEST['headerimage'] )
    106116                        delete_option('kubrick_header_image');
    107                     else
    108                         update_option('kubrick_header_image', $_REQUEST['headerimage']);
     117                    else {
     118                        $headerimage = preg_replace('/^.*?(header-img.php\?upper=[0-9a-fA-F]{6}&lower=[0-9a-fA-F]{6})?.*$/', '$1', $_REQUEST['headerimage']);
     119                        update_option('kubrick_header_image', $headerimage);
     120                    }
    109121                }
    110122
    111123                if ( isset($_REQUEST['fontcolor']) ) {
     124                    check_admin_referer('kubrick-header');
    112125                    if ( '' == $_REQUEST['fontcolor'] )
    113126                        delete_option('kubrick_header_color');
    114                     else
    115                         update_option('kubrick_header_color', $_REQUEST['fontcolor']);
     127                    else {
     128                        $fontcolor = preg_replace('/^.*?(#[0-9a-fA-F]{6})?.*$/', '$1', $_REQUEST['fontcolor']);
     129                        update_option('kubrick_header_color', $fontcolor);
     130                    }
    116131                }
    117132
    118133                if ( isset($_REQUEST['fontdisplay']) ) {
     134                    check_admin_referer('kubrick-header');
    119135                    if ( '' == $_REQUEST['fontdisplay'] || 'inline' == $_REQUEST['fontdisplay'] )
    120136                        delete_option('kubrick_header_display');
     
    129145        add_action('admin_head', 'kubrick_theme_page_head');
    130146    }
    131     add_theme_page('Customize Header', 'Header Image and Color', 'edit_themes', basename(__FILE__), 'kubrick_theme_page');
     147    add_theme_page(__('Customize Header'), __('Header Image and Color'), 'edit_themes', basename(__FILE__), 'kubrick_theme_page');
    132148}
    133149
     
    142158    }
    143159    function PopupWindow_populate(contents) {
    144         contents += '<br /><p style="text-align:center;margin-top:0px;"><input type="button" value="Close Color Picker" onclick="cp.hidePopup(\'prettyplease\')"></input></p>';
     160        contents += '<br /><p style="text-align:center;margin-top:0px;"><input type="button" value="<?php echo attribute_escape(__('Close Color Picker')); ?>" onclick="cp.hidePopup(\'prettyplease\')"></input></p>';
    145161        this.contents = contents;
    146162        this.populated = false;
     
    227243    }
    228244    function kRevert() {
    229         document.getElementById('headerimage').value = '<?php echo kubrick_header_image(); ?>';
    230         document.getElementById('advuppercolor').value = document.getElementById('uppercolor').value = '#<?php echo kubrick_upper_color(); ?>';
    231         document.getElementById('advlowercolor').value = document.getElementById('lowercolor').value = '#<?php echo kubrick_lower_color(); ?>';
    232         document.getElementById('header').style.background = 'url("<?php echo kubrick_header_image_url(); ?>") center no-repeat';
     245        document.getElementById('headerimage').value = '<?php echo js_escape(kubrick_header_image()); ?>';
     246        document.getElementById('advuppercolor').value = document.getElementById('uppercolor').value = '#<?php echo js_escape(kubrick_upper_color()); ?>';
     247        document.getElementById('advlowercolor').value = document.getElementById('lowercolor').value = '#<?php echo js_escape(kubrick_lower_color()); ?>';
     248        document.getElementById('header').style.background = 'url("<?php echo js_escape(kubrick_header_image_url()); ?>") center no-repeat';
    233249        document.getElementById('header').style.color = '';
    234         document.getElementById('advfontcolor').value = document.getElementById('fontcolor').value = '<?php echo kubrick_header_color_string(); ?>';
    235         document.getElementById('fontdisplay').value = '<?php echo kubrick_header_display_string(); ?>';
     250        document.getElementById('advfontcolor').value = document.getElementById('fontcolor').value = '<?php echo js_escape(kubrick_header_color_string()); ?>';
     251        document.getElementById('fontdisplay').value = '<?php echo js_escape(kubrick_header_display_string()); ?>';
    236252        document.getElementById('headerimg').style.display = document.getElementById('fontdisplay').value;
    237253    }
     
    339355
    340356function kubrick_theme_page() {
    341     if ( $_REQUEST['saved'] ) echo '<div id="message" class="updated fade"><p><strong>Options saved.</strong></p></div>';
     357    if ( $_REQUEST['saved'] ) echo '<div id="message" class="updated fade"><p><strong>'.__('Options saved.').'</strong></p></div>';
    342358?>
    343359<div class='wrap'>
    344360    <div id="kubrick-header">
    345         <h2>Header Image and Color</h2>
     361    <h2><?php _e('Header Image and Color'); ?></h2>
    346362        <div id="headwrap">
    347363            <div id="header">
     
    355371        <div id="nonJsForm">
    356372            <form method="post" action="">
    357                 <div class="zerosize"><input type="submit" name="defaultsubmit" value="Save" /></div>
    358                 <label for="njfontcolor">Font Color:</label><input type="text" name="njfontcolor" id="njfontcolor" value="<?php echo kubrick_header_color(); ?>" /> Any CSS color (<code>red</code> or <code>#FF0000</code> or <code>rgb(255, 0, 0)</code>)<br />
    359                 <label for="njuppercolor">Upper Color:</label><input type="text" name="njuppercolor" id="njuppercolor" value="#<?php echo kubrick_upper_color(); ?>" /> HEX only (<code>#FF0000</code> or <code>#F00</code>)<br />
    360                 <label for="njlowercolor">Lower Color:</label><input type="text" name="njlowercolor" id="njlowercolor" value="#<?php echo kubrick_lower_color(); ?>" /> HEX only (<code>#FF0000</code> or <code>#F00</code>)<br />
    361                 <input type="hidden" name="hi" id="hi" value="<?php echo kubrick_header_image(); ?>" />
    362                 <input type="submit" name="toggledisplay" id="toggledisplay" value="Toggle Text" />
    363                 <input type="submit" name="defaults" value="Use Defaults" />
    364                 <input type="submit" class="defbutton" name="submitform" value="&nbsp;&nbsp;Save&nbsp;&nbsp;" />
     373                <?php wp_nonce_field('kubrick-header'); ?>
     374                <div class="zerosize"><input type="submit" name="defaultsubmit" value="<?php echo attribute_escape(__('Save')); ?>" /></div>
     375                    <label for="njfontcolor"><?php _e('Font Color:'); ?></label><input type="text" name="njfontcolor" id="njfontcolor" value="<?php echo attribute_escape(kubrick_header_color()); ?>" /> <?php printf(__('Any CSS color (%s or %s or %s)'), '<code>red</code>', '<code>#FF0000</code>', '<code>rgb(255, 0, 0)</code>'); ?><br />
     376                    <label for="njuppercolor"><?php _e('Upper Color:'); ?></label><input type="text" name="njuppercolor" id="njuppercolor" value="#<?php echo attribute_escape(kubrick_upper_color()); ?>" /> <?php printf(__('HEX only (%s or %s)'), '<code>#FF0000</code>', '<code>#F00</code>'); ?><br />
     377                <label for="njlowercolor"><?php _e('Lower Color:'); ?></label><input type="text" name="njlowercolor" id="njlowercolor" value="#<?php echo attribute_escape(kubrick_lower_color()); ?>" /> <?php printf(__('HEX only (%s or %s)'), '<code>#FF0000</code>', '<code>#F00</code>'); ?><br />
     378                <input type="hidden" name="hi" id="hi" value="<?php echo attribute_escape(kubrick_header_image()); ?>" />
     379                <input type="submit" name="toggledisplay" id="toggledisplay" value="<?php echo attribute_escape(__('Toggle Text')); ?>" />
     380                <input type="submit" name="defaults" value="<?php echo attribute_escape(__('Use Defaults')); ?>" />
     381                <input type="submit" class="defbutton" name="submitform" value="&nbsp;&nbsp;<?php _e('Save'); ?>&nbsp;&nbsp;" />
    365382                <input type="hidden" name="action" value="save" />
    366383                <input type="hidden" name="njform" value="true" />
     
    369386        <div id="jsForm">
    370387            <form style="display:inline;" method="post" name="hicolor" id="hicolor" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
    371                 <input type="button" onclick="tgt=document.getElementById('fontcolor');colorSelect(tgt,'pick1');return false;" name="pick1" id="pick1" value="Font Color"></input>
    372                 <input type="button" onclick="tgt=document.getElementById('uppercolor');colorSelect(tgt,'pick2');return false;" name="pick2" id="pick2" value="Upper Color"></input>
    373                 <input type="button" onclick="tgt=document.getElementById('lowercolor');colorSelect(tgt,'pick3');return false;" name="pick3" id="pick3" value="Lower Color"></input>
    374                 <input type="button" name="revert" value="Revert" onclick="kRevert()" />
    375                 <input type="button" value="Advanced" onclick="toggleAdvanced()" />
     388                <?php wp_nonce_field('kubrick-header'); ?>
     389    <input type="button" onclick="tgt=document.getElementById('fontcolor');colorSelect(tgt,'pick1');return false;" name="pick1" id="pick1" value="<?php echo attribute_escape(__('Font Color')); ?>"></input>
     390        <input type="button" onclick="tgt=document.getElementById('uppercolor');colorSelect(tgt,'pick2');return false;" name="pick2" id="pick2" value="<?php echo attribute_escape(__('Upper Color')); ?>"></input>
     391        <input type="button" onclick="tgt=document.getElementById('lowercolor');colorSelect(tgt,'pick3');return false;" name="pick3" id="pick3" value="<?php echo attribute_escape(__('Lower Color')); ?>"></input>
     392                <input type="button" name="revert" value="<?php echo attribute_escape(__('Revert')); ?>" onclick="kRevert()" />
     393                <input type="button" value="<?php echo attribute_escape(__('Advanced')); ?>" onclick="toggleAdvanced()" />
    376394                <input type="hidden" name="action" value="save" />
    377                 <input type="hidden" name="fontdisplay" id="fontdisplay" value="<?php echo kubrick_header_display(); ?>" />
    378                 <input type="hidden" name="fontcolor" id="fontcolor" value="<?php echo kubrick_header_color(); ?>" />
    379                 <input type="hidden" name="uppercolor" id="uppercolor" value="<?php echo kubrick_upper_color(); ?>" />
    380                 <input type="hidden" name="lowercolor" id="lowercolor" value="<?php echo kubrick_lower_color(); ?>" />
    381                 <input type="hidden" name="headerimage" id="headerimage" value="<?php echo kubrick_header_image(); ?>" />
    382                 <p class="submit"><input type="submit" name="submitform" class="defbutton" value="<?php _e('Update Header &raquo;'); ?>" onclick="cp.hidePopup('prettyplease')" /></p>
     395                <input type="hidden" name="fontdisplay" id="fontdisplay" value="<?php echo attribute_escape(kubrick_header_display()); ?>" />
     396                <input type="hidden" name="fontcolor" id="fontcolor" value="<?php echo attribute_escape(kubrick_header_color()); ?>" />
     397                <input type="hidden" name="uppercolor" id="uppercolor" value="<?php echo attribute_escape(kubrick_upper_color()); ?>" />
     398                <input type="hidden" name="lowercolor" id="lowercolor" value="<?php echo attribute_escape(kubrick_lower_color()); ?>" />
     399                <input type="hidden" name="headerimage" id="headerimage" value="<?php echo attribute_escape(kubrick_header_image()); ?>" />
     400                <p class="submit"><input type="submit" name="submitform" class="defbutton" value="<?php echo attribute_escape(__('Update Header &raquo;')); ?>" onclick="cp.hidePopup('prettyplease')" /></p>
    383401            </form>
    384402            <div id="colorPickerDiv" style="z-index: 100;background:#eee;border:1px solid #ccc;position:absolute;visibility:hidden;"> </div>
    385403            <div id="advanced">
    386404                <form id="jsAdvanced" style="display:none;" action="">
    387                     <label for="advfontcolor">Font Color (CSS): </label><input type="text" id="advfontcolor" onchange="advUpdate(this.value, 'fontcolor')" value="<?php echo kubrick_header_color(); ?>" /><br />
    388                     <label for="advuppercolor">Upper Color (HEX): </label><input type="text" id="advuppercolor" onchange="advUpdate(this.value, 'uppercolor')" value="#<?php echo kubrick_upper_color(); ?>" /><br />
    389                     <label for="advlowercolor">Lower Color (HEX): </label><input type="text" id="advlowercolor" onchange="advUpdate(this.value, 'lowercolor')" value="#<?php echo kubrick_lower_color(); ?>" /><br />
    390                     <input type="button" name="default" value="Select Default Colors" onclick="kDefaults()" /><br />
    391                     <input type="button" onclick="toggleDisplay();return false;" name="pick" id="pick" value="Toggle Text Display"></input><br />
     405                    <?php wp_nonce_field('kubrick-header'); ?>
     406                    <label for="advfontcolor"><?php _e('Font Color (CSS):'); ?> </label><input type="text" id="advfontcolor" onchange="advUpdate(this.value, 'fontcolor')" value="<?php echo attribute_escape(kubrick_header_color()); ?>" /><br />
     407                    <label for="advuppercolor"><?php _e('Upper Color (HEX):');?> </label><input type="text" id="advuppercolor" onchange="advUpdate(this.value, 'uppercolor')" value="#<?php echo attribute_escape(kubrick_upper_color()); ?>" /><br />
     408                    <label for="advlowercolor"><?php _e('Lower Color (HEX):'); ?> </label><input type="text" id="advlowercolor" onchange="advUpdate(this.value, 'lowercolor')" value="#<?php echo attribute_escape(kubrick_lower_color()); ?>" /><br />
     409                    <input type="button" name="default" value="<?php echo attribute_escape(__('Select Default Colors')); ?>" onclick="kDefaults()" /><br />
     410                    <input type="button" onclick="toggleDisplay();return false;" name="pick" id="pick" value="<?php echo attribute_escape(__('Toggle Text Display')); ?>"></input><br />
    392411                </form>
    393412            </div>
  • tags/2.2/wp-content/themes/default/header.php

    r5468 r5480  
    1919if ( !$withcomments && !is_single() ) {
    2020?>
    21     #page { background: url("<?php bloginfo('stylesheet_directory'); ?>/images/kubrickbg.jpg") repeat-y top; border: none; }
     21    #page { background: url("<?php bloginfo('stylesheet_directory'); ?>/images/kubrickbg-<?php bloginfo('text_direction'); ?>.jpg") repeat-y top; border: none; }
    2222<?php } else { // No sidebar ?>
    2323    #page { background: url("<?php bloginfo('stylesheet_directory'); ?>/images/kubrickbgwide.jpg") repeat-y top; border: none; }
  • tags/2.2/wp-content/themes/default/searchform.php

    r5468 r5480  
    1 <form method="get" id="searchform" action="<?php bloginfo('home'); ?>/">
     1<form method="get" id="searchform" action="<?php bloginfo('url'); ?>/">
    22<div><input type="text" value="<?php the_search_query(); ?>" name="s" id="s" />
    33<input type="submit" id="searchsubmit" value="Search" />
  • tags/2.2/wp-content/themes/default/sidebar.php

    r5468 r5480  
    11    <div id="sidebar">
    22        <ul>
    3 
     3            <?php   /* Widgetized sidebar, if you have the plugin installed. */
     4                    if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar() ) : ?>
    45            <li>
    56                <?php include (TEMPLATEPATH . '/searchform.php'); ?>
     
    1213            -->
    1314
    14             <li>
     15            <?php if ( is_404() || is_category() || is_day() || is_month() ||
     16                        is_year() || is_search() || is_paged() ) {
     17            ?> <li>
     18
    1519            <?php /* If this is a 404 page */ if (is_404()) { ?>
    1620            <?php /* If this is a category archive */ } elseif (is_category()) { ?>
     
    1822
    1923            <?php /* If this is a yearly archive */ } elseif (is_day()) { ?>
    20             <p>You are currently browsing the <a href="<?php bloginfo('home'); ?>/"><?php echo bloginfo('name'); ?></a> weblog archives
     24            <p>You are currently browsing the <a href="<?php bloginfo('url'); ?>/"><?php echo bloginfo('name'); ?></a> weblog archives
    2125            for the day <?php the_time('l, F jS, Y'); ?>.</p>
    2226
    2327            <?php /* If this is a monthly archive */ } elseif (is_month()) { ?>
    24             <p>You are currently browsing the <a href="<?php bloginfo('home'); ?>/"><?php echo bloginfo('name'); ?></a> weblog archives
     28            <p>You are currently browsing the <a href="<?php bloginfo('url'); ?>/"><?php echo bloginfo('name'); ?></a> weblog archives
    2529            for <?php the_time('F, Y'); ?>.</p>
    2630
    2731            <?php /* If this is a yearly archive */ } elseif (is_year()) { ?>
    28             <p>You are currently browsing the <a href="<?php bloginfo('home'); ?>/"><?php echo bloginfo('name'); ?></a> weblog archives
     32            <p>You are currently browsing the <a href="<?php bloginfo('url'); ?>/"><?php echo bloginfo('name'); ?></a> weblog archives
    2933            for the year <?php the_time('Y'); ?>.</p>
    3034
    3135            <?php /* If this is a monthly archive */ } elseif (is_search()) { ?>
    32             <p>You have searched the <a href="<?php echo bloginfo('home'); ?>/"><?php echo bloginfo('name'); ?></a> weblog archives
     36            <p>You have searched the <a href="<?php echo bloginfo('url'); ?>/"><?php echo bloginfo('name'); ?></a> weblog archives
    3337            for <strong>'<?php the_search_query(); ?>'</strong>. If you are unable to find anything in these search results, you can try one of these links.</p>
    3438
    3539            <?php /* If this is a monthly archive */ } elseif (isset($_GET['paged']) && !empty($_GET['paged'])) { ?>
    36             <p>You are currently browsing the <a href="<?php echo bloginfo('home'); ?>/"><?php echo bloginfo('name'); ?></a> weblog archives.</p>
     40            <p>You are currently browsing the <a href="<?php echo bloginfo('url'); ?>/"><?php echo bloginfo('name'); ?></a> weblog archives.</p>
    3741
    3842            <?php } ?>
    39             </li>
     43               
     44            </li> <?php }?>
    4045
    4146            <?php wp_list_pages('title_li=<h2>Pages</h2>' ); ?>
     
    6368                </li>
    6469            <?php } ?>
    65 
     70           
     71            <?php endif; ?>
    6672        </ul>
    6773    </div>
  • tags/2.2/wp-cron.php

    r5468 r5480  
    44require_once('wp-config.php');
    55
    6 if ( $_GET['check'] != md5(DB_PASS . '187425') )
     6if ( $_GET['check'] != wp_hash('187425') )
    77    exit;
    88
  • tags/2.2/wp-includes/author-template.php

    r5468 r5480  
    174174
    175175function wp_list_authors($args = '') {
     176    global $wpdb;
     177   
    176178    if ( is_array($args) )
    177179        $r = &$args;
     
    183185    $r = array_merge($defaults, $r);
    184186    extract($r);
    185 
    186     global $wpdb;
     187   
    187188    // TODO:  Move select to get_authors().
    188     $query = "SELECT ID, user_nicename from $wpdb->users " . ($exclude_admin ? "WHERE user_login <> 'admin' " : '') . "ORDER BY display_name";
    189     $authors = $wpdb->get_results($query);
     189    $authors = $wpdb->get_results("SELECT ID, user_nicename from $wpdb->users " . ($exclude_admin ? "WHERE user_login <> 'admin' " : '') . "ORDER BY display_name");
     190   
     191    $author_count = array();
     192    foreach ((array) $wpdb->get_results("SELECT DISTINCT post_author, COUNT(ID) AS count FROM $wpdb->posts WHERE post_status = 'publish' GROUP BY post_author") as $row) {
     193        $author_count[$row->post_author] = $row->count;
     194    }
    190195
    191196    foreach ( (array) $authors as $author ) {
    192197        $author = get_userdata( $author->ID );
    193         $posts = get_usernumposts($author->ID);
     198        $posts = (isset($author_count[$author->ID])) ? $author_count[$author->ID] : 0;
    194199        $name = $author->nickname;
    195200
  • tags/2.2/wp-includes/bookmark-template.php

    r5468 r5480  
    137137        if ( $show_description && '' != $desc )
    138138            $output .= $between . $desc;
     139       
     140        if ($show_rating) {
     141            $output .= $between . get_linkrating($row);
     142        }
    139143
    140144        $output .= "$after\n";
     
    267271            $rel = ' rel="' . $rel . '"';
    268272
    269         $desc = attribute_escape($bookmark->link_description);
    270         $name = attribute_escape($bookmark->link_name);
    271         $title = $desc;
     273        $desc = attribute_escape(apply_filters('link_description', $bookmark->link_description));
     274        $name = attribute_escape(apply_filters('link_title', $bookmark->link_name));
     275        $title = $desc;
    272276
    273277        if ( $show_updated )
     
    305309        if ( $show_description && '' != $desc )
    306310            $output .= $between . $desc;
     311       
     312        if ($show_rating) {
     313            $output .= $between . get_linkrating($bookmark);
     314        }
     315       
    307316        $output .= "$after\n";
    308317    } // end while
     
    332341
    333342        foreach ( (array) $cats as $cat ) {
    334             $bookmarks = get_bookmarks("limit=$limit&category={$cat->cat_ID}&show_updated=$show_updated&orderby=$orderby&order=$order&hide_invisible=$hide_invisible&show_updated=$show_updated");
     343            $params = array_merge($r, array('category'=>$cat->cat_ID));
     344            $bookmarks = get_bookmarks($params);
    335345            if ( empty($bookmarks) )
    336346                continue;
    337347            $output .= str_replace(array('%id', '%class'), array("linkcat-$cat->cat_ID", $class), $category_before);
    338             $output .= "$title_before$cat->cat_name$title_after\n\t<ul>\n";
     348            $catname = apply_filters( "link_category", $cat->cat_name );
     349            $output .= "$title_before$catname$title_after\n\t<ul>\n";
    339350            $output .= _walk_bookmarks($bookmarks, $r);
    340351            $output .= "\n\t</ul>\n$category_after\n";
     
    342353    } else {
    343354        //output one single list using title_li for the title
    344         $bookmarks = get_bookmarks("limit=$limit&category=$category&show_updated=$show_updated&orderby=$orderby&order=$order&hide_invisible=$hide_invisible&show_updated=$show_updated");
    345        
     355        $bookmarks = get_bookmarks($r);
     356
    346357        if ( !empty($bookmarks) ) {
    347358            if ( !empty( $title_li ) ){
  • tags/2.2/wp-includes/bookmark.php

    r5468 r5480  
    7474    if (!empty($exclusions))
    7575        $exclusions .= ')';
    76        
     76
    7777    if ( ! empty($category_name) ) {
    7878        if ( $cat_id = $wpdb->get_var("SELECT cat_ID FROM $wpdb->categories WHERE cat_name='$category_name' LIMIT 1") )
     
    137137
    138138    $cache[ $key ] = $results;
    139     wp_cache_set( 'get_bookmarks', $cache, 'bookmark' );
     139    wp_cache_add( 'get_bookmarks', $cache, 'bookmark' );
    140140
    141141    return apply_filters('get_bookmarks', $results, $r);
  • tags/2.2/wp-includes/cache.php

    r5468 r5480  
    195195                    $this->cache['category'][$catt->cat_ID] = $catt;
    196196            }
    197         } else
    198             if ('options' == $group) {
    199                 $wpdb->hide_errors();
    200                 if (!$options = $wpdb->get_results("SELECT option_name, option_value FROM $wpdb->options WHERE autoload = 'yes'")) {
    201                     $options = $wpdb->get_results("SELECT option_name, option_value FROM $wpdb->options");
    202                 }
    203                 $wpdb->show_errors();
    204 
    205                 if ( ! $options )
    206                     return;
    207 
    208                 foreach ($options as $option) {
    209                     $this->cache['options'][$option->option_name] = $option->option_value;
    210                 }
    211             }
     197        }
     198
    212199    }
    213200
     
    354341                fclose($fd);
    355342                if (!@ rename($temp_file, $cache_file)) {
    356                     if (@ copy($temp_file, $cache_file))
    357                         @ unlink($temp_file);
    358                     else
     343                    if (!@ copy($temp_file, $cache_file))
    359344                        $errors++;
     345                    @ unlink($temp_file);
    360346                }
    361347                @ chmod($cache_file, $file_perms);
     
    400386        return $this->__construct();
    401387    }
    402    
     388
    403389    function __construct() {
    404390        global $blog_id;
     
    443429    function __destruct() {
    444430        $this->save();
    445         return true;   
     431        return true;
    446432    }
    447433}
  • tags/2.2/wp-includes/category-template.php

    r5468 r5480  
    3333
    3434        if ( $parent = $category->category_parent )
    35             $category_nicename = get_category_parents($parent, false, '/', true) . $category_nicename . '/';
     35            $category_nicename = get_category_parents($parent, false, '/', true) . $category_nicename;
    3636
    3737        $catlink = str_replace('%category%', $category_nicename, $catlink);
    38         $catlink = get_option('home') . trailingslashit($catlink);
     38        $catlink = get_option('home') . user_trailingslashit($catlink, 'category');
    3939    }
    4040    return apply_filters('category_link', $catlink, $category_id);
     
    7373
    7474    if ( !empty($categories) )
    75         sort($categories);
     75        usort($categories, '_get_the_category_usort');
    7676    else
    7777        $categories = array();
    7878
    7979    return $categories;
     80}
     81
     82function _get_the_category_usort($a, $b) {
     83    return strcmp($a->category_name, $b->category_name);
    8084}
    8185
     
    8791
    8892function get_the_category_list($separator = '', $parents='') {
     93    global $wp_rewrite;
    8994    $categories = get_the_category();
    9095    if (empty($categories))
    9196        return apply_filters('the_category', __('Uncategorized'), $separator, $parents);
     97
     98    $rel = ( is_object($wp_rewrite) && $wp_rewrite->using_permalinks() ) ? 'rel="category tag"' : 'rel="category"';
    9299
    93100    $thelist = '';
     
    100107                    if ($category->category_parent)
    101108                        $thelist .= get_category_parents($category->category_parent, TRUE);
    102                     $thelist .= '<a href="' . get_category_link($category->cat_ID) . '" title="' . sprintf(__("View all posts in %s"), $category->cat_name) . '" rel="category tag">'.$category->cat_name.'</a></li>';
     109                    $thelist .= '<a href="' . get_category_link($category->cat_ID) . '" title="' . sprintf(__("View all posts in %s"), $category->cat_name) . '" ' . $rel . '>' . $category->cat_name.'</a></li>';
    103110                    break;
    104111                case 'single':
    105                     $thelist .= '<a href="' . get_category_link($category->cat_ID) . '" title="' . sprintf(__("View all posts in %s"), $category->cat_name) . ' rel="category tag">';
     112                    $thelist .= '<a href="' . get_category_link($category->cat_ID) . '" title="' . sprintf(__("View all posts in %s"), $category->cat_name) . '" ' . $rel . '>';
    106113                    if ($category->category_parent)
    107114                        $thelist .= get_category_parents($category->category_parent, FALSE);
     
    110117                case '':
    111118                default:
    112                     $thelist .= '<a href="' . get_category_link($category->cat_ID) . '" title="' . sprintf(__("View all posts in %s"), $category->cat_name) . '" rel="category tag">'.$category->cat_name.'</a></li>';
     119                    $thelist .= '<a href="' . get_category_link($category->cat_ID) . '" title="' . sprintf(__("View all posts in %s"), $category->cat_name) . '" ' . $rel . '>' . $category->cat_name.'</a></li>';
    113120            }
    114121        }
     
    123130                    if ( $category->category_parent )
    124131                        $thelist .= get_category_parents($category->category_parent, TRUE);
    125                     $thelist .= '<a href="' . get_category_link($category->cat_ID) . '" title="' . sprintf(__("View all posts in %s"), $category->cat_name) . '" rel="category tag">'.$category->cat_name.'</a>';
     132                    $thelist .= '<a href="' . get_category_link($category->cat_ID) . '" title="' . sprintf(__("View all posts in %s"), $category->cat_name) . '" ' . $rel . '>' . $category->cat_name.'</a>';
    126133                    break;
    127134                case 'single':
    128                     $thelist .= '<a href="' . get_category_link($category->cat_ID) . '" title="' . sprintf(__("View all posts in %s"), $category->cat_name) . '" rel="category tag">';
     135                    $thelist .= '<a href="' . get_category_link($category->cat_ID) . '" title="' . sprintf(__("View all posts in %s"), $category->cat_name) . '" ' . $rel . '>';
    129136                    if ( $category->category_parent )
    130137                        $thelist .= get_category_parents($category->category_parent, FALSE);
     
    133140                case '':
    134141                default:
    135                     $thelist .= '<a href="' . get_category_link($category->cat_ID) . '" title="' . sprintf(__("View all posts in %s"), $category->cat_name) . '" rel="category tag">'.$category->cat_name.'</a>';
     142                    $thelist .= '<a href="' . get_category_link($category->cat_ID) . '" title="' . sprintf(__("View all posts in %s"), $category->cat_name) . '" ' . $rel . '>' . $category->cat_name.'</a>';
    136143            }
    137144            ++$i;
     
    243250        global $wp_query;
    244251       
     252        if( !empty($show_option_all) )
     253            if ('list' == $style ) 
     254                $output .= '<li><a href="' .  get_bloginfo('url')  . '">' . $show_option_all . '</a></li>';
     255            else
     256                $output .= '<a href="' .  get_bloginfo('url')  . '">' . $show_option_all . '</a>';
     257       
    245258        if ( is_category() )
    246259            $r['current_category'] = $wp_query->get_queried_object_id();
  • tags/2.2/wp-includes/category.php

    r5468 r5480  
    66    if ( ! $cat_ids = wp_cache_get('all_category_ids', 'category') ) {
    77        $cat_ids = $wpdb->get_col("SELECT cat_ID FROM $wpdb->categories");
    8         wp_cache_set('all_category_ids', $cat_ids, 'category');
     8        wp_cache_add('all_category_ids', $cat_ids, 'category');
    99    }
    1010
     
    106106    }
    107107
    108     if ( $child_of || $hierarchical )
    109         $categories = & _get_cat_children($child_of, $categories);
     108    if ( $child_of || $hierarchical ) {
     109        $children = _get_category_hierarchy();
     110        if ( ! empty($children) )
     111            $categories = & _get_cat_children($child_of, $categories);
     112    }
    110113
    111114    // Update category counts to include children.
     
    130133
    131134    $cache[ $key ] = $categories;
    132     wp_cache_set( 'get_categories', $cache, 'category' );
    133 
    134     return apply_filters('get_categories', $categories, $r);
     135    wp_cache_add( 'get_categories', $cache, 'category' );
     136
     137    $categories = apply_filters('get_categories', $categories, $r);
     138    return $categories;
    135139}
    136140
     
    150154        if ( ! $_category = wp_cache_get($category, 'category') ) {
    151155            $_category = $wpdb->get_row("SELECT * FROM $wpdb->categories WHERE cat_ID = '$category' LIMIT 1");
    152             wp_cache_set($category, $_category, 'category');
     156            wp_cache_add($category, $_category, 'category');
    153157        }
    154158    }
     
    248252
    249253    $category_list = array();
     254    $has_children = _get_category_hierarchy();
     255
     256    if  ( ( 0 != $category_id ) && ! isset($has_children[$category_id]) )
     257        return array();
     258
    250259    foreach ( $categories as $category ) {
    251260        if ( $category->cat_ID == $category_id )
     
    254263        if ( $category->category_parent == $category_id ) {
    255264            $category_list[] = $category;
     265
     266            if ( !isset($has_children[$category->cat_ID]) )
     267                continue;
     268
    256269            if ( $children = _get_cat_children($category->cat_ID, $categories) )
    257270                $category_list = array_merge($category_list, $children);
     
    301314}
    302315
     316function _get_category_hierarchy() {
     317    $children = get_option('category_children');
     318    if ( is_array($children) )
     319        return $children;
     320
     321    $children = array();
     322    $categories = get_categories('hide_empty=0&hierarchical=0');
     323    foreach ( $categories as $cat ) {
     324        if ( $cat->category_parent > 0 )
     325            $children[$cat->category_parent][] = $cat->cat_ID;
     326    }
     327    update_option('category_children', $children);
     328
     329    return $children;
     330}
    303331?>
  • tags/2.2/wp-includes/class-pop3.php

    r5468 r5480  
    44    * mail_fetch/setup.php
    55    *
    6     * Copyright (c) 1999-2002 The SquirrelMail Project Team
     6    * Copyright (c) 1999-2006 The SquirrelMail Project Team
    77    *
    88    * Copyright (c) 1999 CDI (cdi@thewebmasters.net) All Rights Reserved
     
    4141                                //  pop server - used for apop()
    4242
    43     var $RFC1939    = TRUE;     //  Set by noop(). See rfc1939.txt
    44                                 //
    45 
    4643    var $ALLOWAPOP  = FALSE;    //  Allow or disallow apop()
    4744                                //  This must be set to true
     
    6057            settype($timeout,"integer");
    6158            $this->TIMEOUT = $timeout;
     59            if (!ini_get('safe_mode'))
    6260            set_time_limit($timeout);
    6361        }
     
    6664
    6765    function update_timer () {
     66        if (!ini_get('safe_mode'))
    6867        set_time_limit($this->TIMEOUT);
    6968        return true;
     
    7675        // If MAILSERVER is set, override $server with it's value
    7776
     77        if (!isset($port) || !$port) {$port = 110;}
    7878        if(!empty($this->MAILSERVER))
    7979            $server = $this->MAILSERVER;
     
    8585        }
    8686
    87         $fp = fsockopen("$server", $port, $errno, $errstr);
     87        $fp = @fsockopen("$server", $port, $errno, $errstr);
    8888
    8989        if(!$fp) {
     
    106106        $this->FP = $fp;
    107107        $this->BANNER = $this->parse_banner($reply);
    108         $this->RFC1939 = $this->noop();
    109         if($this->RFC1939) {
    110             $this->ERROR = _("POP3: premature NOOP OK, NOT an RFC 1939 Compliant server");
    111             $this->quit();
    112             return false;
    113         } else
    114             return true;
    115     }
    116 
    117     function noop () {
    118    
    119         if(!isset($this->FP)) {
    120             $this->ERROR = _("POP3 noop:") . ' ' . _("No connection to server");
    121             return false;
    122         } else {
    123             $cmd = "NOOP";
    124             $reply = $this->send_cmd( $cmd );
    125             return( $this->is_ok( $reply ) );
    126         }
     108        return true;
    127109    }
    128110
     
    159141            $reply = $this->send_cmd("PASS $pass");
    160142            if(!$this->is_ok($reply)) {
    161                 $this->ERROR = _("POP3 pass:") . ' ' . _("authentication failed ") . "[$reply]";
     143                $this->ERROR = _("POP3 pass:") . ' ' . _("Authentication failed ") . "[$reply]";
    162144                $this->quit();
    163145                return false;
     
    166148                $count = $this->last("count");
    167149                $this->COUNT = $count;
    168                 $this->RFC1939 = $this->noop();
    169                 if(!$this->RFC1939) {
    170                     $this->ERROR = _("POP3 pass:") . ' ' . _("NOOP failed. Server not RFC 1939 compliant");
    171                     $this->quit();
    172                     return false;
    173                 } else
    174                     return $count;
     150                return $count;
    175151            }
    176152        }
     
    215191                    $count = $this->last("count");
    216192                    $this->COUNT = $count;
    217                     $this->RFC1939 = $this->noop();
    218                     if(!$this->RFC1939) {
    219                         $this->ERROR = _("POP3 apop:") . ' ' . _("NOOP failed. Server not RFC 1939 compliant");
    220                         $this->quit();
    221                         return false;
    222                     } else
    223                         return $count;
     193                    return $count;
    224194                }
    225195            }
     
    331301                return false;
    332302            }
    333             list($junk,$num,$size) = explode(" ",$reply);
     303            list($junk,$num,$size) = preg_split('/\s+/',$reply);
    334304            return $size;
    335305        }
     
    354324                return false;
    355325            }
    356             list($thisMsg,$msgSize) = explode(" ",$line);
     326            list($thisMsg,$msgSize) = preg_split('/\s+/',$line);
    357327            settype($thisMsg,"integer");
    358328            if($thisMsg != $msgC)
     
    394364        $MsgArray = array();
    395365
    396         $line = fgets($fp,$buffer);
     366        $line = "";
    397367        while ( !ereg("^\.\r\n",$line))
    398368        {
     369            $line = fgets($fp,$buffer);
     370            if (preg_match("/^\s+/", $line) && $count > 0) {
     371                $MsgArray[$count-1] .= $line;
     372                continue;
     373            }
     374            if(empty($line))    { break; }
     375
    399376            $MsgArray[$count] = $line;
    400377            $count++;
    401             $line = fgets($fp,$buffer);
    402             if(empty($line))    { break; }
    403378        }
    404379        return $MsgArray;
     
    424399        }
    425400
    426         $Vars = explode(" ",$reply);
     401        $Vars = preg_split('/\s+/',$reply);
    427402        $count = $Vars[1];
    428403        $size = $Vars[2];
     
    555530                return false;
    556531            }
    557             list ($ok,$num,$myUidl) = explode(" ",$reply);
     532            list ($ok,$num,$myUidl) = preg_split('/\s+/',$reply);
    558533            return $myUidl;
    559534        } else {
     
    586561                    break;
    587562                }
    588                 list ($msg,$msgUidl) = explode(" ",$line);
     563                list ($msg,$msgUidl) = preg_split('/\s+/',$line);
    589564                $msgUidl = $this->strip_clf($msgUidl);
    590565                if($count == $msg) {
     
    657632        {
    658633            $digit = substr($server_text, $count, 1);
    659             if ( false !== $digit ) {
     634            if (!empty($digit)) {
    660635                if( (!$outside) && ($digit != '<') && ($digit != '>') )
    661636                {
  • tags/2.2/wp-includes/classes.php

    r5468 r5480  
    5959            // filename, if any.  For 404 requests, this leaves us with the
    6060            // requested permalink.
    61             $req_uri = str_replace($pathinfo, '', $req_uri);
     61            $req_uri = str_replace($pathinfo, '', rawurldecode($req_uri));
    6262            $req_uri = trim($req_uri, '/');
    6363            $req_uri = preg_replace("|^$home_path|", '', $req_uri);
     
    121121
    122122            // If req_uri is empty or if it is a request for ourself, unset error.
    123             if ( empty($request) || $req_uri == $self || strstr($_SERVER['PHP_SELF'], 'wp-admin/') ) {
     123            if (empty($request) || $req_uri == $self || strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false) {
    124124                if (isset($_GET['error']))
    125125                    unset($_GET['error']);
     
    128128                    unset($error);
    129129
    130                 if ( isset($perma_query_vars) && strstr($_SERVER['PHP_SELF'], 'wp-admin/') )
     130                if (isset($perma_query_vars) && strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false)
    131131                    unset($perma_query_vars);
    132132
     
    418418                    $output = call_user_func_array(array(&$this, 'start_el'), $cb_args);
    419419                }
    420    
     420
    421421                // End the element.
    422422                if ( isset($element->$id_field) && $element->$id_field != 0 ) {
     
    424424                    $output = call_user_func_array(array(&$this, 'end_el'), $cb_args);
    425425                }
    426    
    427                 continue;   
    428             }
    429    
     426
     427                continue;
     428            }
     429
    430430            // Walk the tree.
    431431            if ( !empty($previous_element) && ($element->$parent_field == $previous_element->$id_field) ) {
     
    515515            $css_class .= ' current_page_parent';
    516516
    517         $output .= $indent . '<li class="' . $css_class . '"><a href="' . get_page_link($page->ID) . '" title="' . attribute_escape($page->post_title) . '">' . $page->post_title . '</a>';
    518    
     517        $output .= $indent . '<li class="' . $css_class . '"><a href="' . get_page_link($page->ID) . '" title="' . attribute_escape(apply_filters('the_title', $page->post_title)) . '">' . apply_filters('the_title', $page->post_title) . '</a>';
     518
    519519        if ( !empty($show_date) ) {
    520520            if ( 'modified' == $show_date )
     
    522522            else
    523523                $time = $page->post_date;
    524    
     524
    525525            $output .= " " . mysql2date($date_format, $time);
    526526        }
     
    528528        return $output;
    529529    }
    530    
     530
    531531    function end_el($output, $page, $depth) {
    532532        $output .= "</li>\n";
     
    582582
    583583        $cat_name = attribute_escape( $category->cat_name);
     584        $cat_name = apply_filters( 'list_cats', $cat_name, $category );
    584585        $link = '<a href="' . get_category_link( $category->cat_ID ) . '" ';
    585586        if ( $use_desc_for_title == 0 || empty($category->category_description) )
     
    588589            $link .= 'title="' . attribute_escape( apply_filters( 'category_description', $category->category_description, $category )) . '"';
    589590        $link .= '>';
    590         $link .= apply_filters( 'list_cats', $category->cat_name, $category ).'</a>';
     591        $link .= $cat_name . '</a>';
    591592
    592593        if ( (! empty($feed_image)) || (! empty($feed)) ) {
     
    617618                $link .= ')';
    618619        }
    619    
     620
    620621        if ( isset($show_count) && $show_count )
    621622            $link .= ' (' . intval($category->category_count) . ')';
    622    
     623
    623624        if ( isset($show_date) && $show_date ) {
    624625            $link .= ' ' . gmdate('Y-m-d', $category->last_update_timestamp);
  • tags/2.2/wp-includes/comment-template.php

    r5468 r5480  
    162162}
    163163
    164 function comments_number( $zero = false, $one = false, $more = false, $number = '' ) {
     164function comments_number( $zero = false, $one = false, $more = false, $deprecated = '' ) {
    165165    global $id;
    166166    $number = get_comments_number($id);
     
    227227
    228228    if ( '' != get_option('permalink_structure') )
    229         $tb_url = trailingslashit(get_permalink()) . 'trackback/';
    230 
    231     return $tb_url;
     229        $tb_url = trailingslashit(get_permalink()) . user_trailingslashit('trackback', 'single_trackback');
     230
     231    return apply_filters('trackback_url', $tb_url);
    232232}
    233233function trackback_url( $display = true ) {
     
    240240function trackback_rdf($timezone = 0) {
    241241    global $id;
    242     if (!stristr($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator')) {
    243     echo '<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    244             xmlns:dc="http://purl.org/dc/elements/1.1/"
    245             xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
    246         <rdf:Description rdf:about="';
    247     the_permalink();
    248     echo '"'."\n";
    249     echo '    dc:identifier="';
    250     the_permalink();
    251     echo '"'."\n";
    252     echo '    dc:title="'.str_replace('--', '&#x2d;&#x2d;', wptexturize(strip_tags(get_the_title()))).'"'."\n";
    253     echo '    trackback:ping="'.trackback_url(0).'"'." />\n";
    254     echo '</rdf:RDF>';
     242    if (strpos($_SERVER['HTTP_USER_AGENT'], 'W3C_Validator') !== false) {
     243        echo '<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
     244                xmlns:dc="http://purl.org/dc/elements/1.1/"
     245                xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
     246            <rdf:Description rdf:about="';
     247        the_permalink();
     248        echo '"'."\n";
     249        echo '    dc:identifier="';
     250        the_permalink();
     251        echo '"'."\n";
     252        echo '    dc:title="'.str_replace('--', '&#x2d;&#x2d;', wptexturize(strip_tags(get_the_title()))).'"'."\n";
     253        echo '    trackback:ping="'.trackback_url(0).'"'." />\n";
     254        echo '</rdf:RDF>';
    255255    }
    256256}
     
    289289
    290290    // TODO: Use API instead of SELECTs.
    291     if ( empty($comment_author) ) {
     291    if ( $user_ID) {
     292        $comments = $wpdb->get_results("SELECT * FROM $wpdb->comments WHERE comment_post_ID = '$post->ID' AND (comment_approved = '1' OR ( user_id = '$user_ID' AND comment_approved = '0' ) )  ORDER BY comment_date");
     293    } else if ( empty($comment_author) ) {
    292294        $comments = $wpdb->get_results("SELECT * FROM $wpdb->comments WHERE comment_post_ID = '$post->ID' AND comment_approved = '1' ORDER BY comment_date");
    293295    } else {
     
    297299    }
    298300
    299     $comments = apply_filters( 'comments_array', $comments, $post->ID );
     301    // keep $comments for legacy's sake (remember $table*? ;) )
     302    $comments = $wp_query->comments = apply_filters( 'comments_array', $comments, $post->ID );
     303    $wp_query->comment_count = count($wp_query->comments);
    300304
    301305    define('COMMENTS_TEMPLATE', true);
     
    330334
    331335    if ( 0 == $number && 'closed' == $post->comment_status && 'closed' == $post->ping_status ) {
    332         echo $none;
     336        echo '<span' . ((!empty($CSSclass)) ? ' class="' . $CSSclass . '"' : '') . '>' . $none . '</span>';
    333337        return;
    334338    }
  • tags/2.2/wp-includes/compat.php

    r5468 r5480  
    119119}
    120120
     121// Added in PHP 5.0
     122if (!function_exists('stripos')) {
     123    function stripos($haystack, $needle, $offset = 0) {
     124        return strpos(strtolower($haystack), strtolower($needle), $offset);
     125    }
     126}
     127
    121128?>
  • tags/2.2/wp-includes/cron.php

    r5468 r5480  
    5555function wp_clear_scheduled_hook( $hook ) {
    5656    $args = array_slice( func_get_args(), 1 );
    57    
     57
    5858    while ( $timestamp = wp_next_scheduled( $hook, $args ) )
    5959        wp_unschedule_event( $timestamp, $hook, $args );
     
    7474function spawn_cron() {
    7575    $crons = _get_cron_array();
    76    
     76
    7777    if ( !is_array($crons) )
    7878        return;
    79    
     79
    8080    $keys = array_keys( $crons );
    8181    if ( array_shift( $keys ) > time() )
     
    8484    $cron_url = get_option( 'siteurl' ) . '/wp-cron.php';
    8585    $parts = parse_url( $cron_url );
    86 
    87     $argyle = @ fsockopen( $parts['host'], $_SERVER['SERVER_PORT'], $errno, $errstr, 0.01 );
     86   
     87    if ($parts['scheme'] == 'https') {
     88        // support for SSL was added in 4.3.0
     89        if (version_compare(phpversion(), '4.3.0', '>=') && function_exists('openssl_open')) {
     90            $argyle = @fsockopen('ssl://' . $parts['host'], $_SERVER['SERVER_PORT'], $errno, $errstr, 0.01);
     91        } else {
     92            return false;
     93        }
     94    } else {
     95        $argyle = @ fsockopen( $parts['host'], $_SERVER['SERVER_PORT'], $errno, $errstr, 0.01 );
     96    }
     97   
    8898    if ( $argyle )
    8999        fputs( $argyle,
    90               "GET {$parts['path']}?check=" . md5(DB_PASS . '187425') . " HTTP/1.0\r\n"
     100              "GET {$parts['path']}?check=" . wp_hash('187425') . " HTTP/1.0\r\n"
    91101            . "Host: {$_SERVER['HTTP_HOST']}\r\n\r\n"
    92102        );
     
    99109
    100110    $crons = _get_cron_array();
    101    
     111
    102112    if ( !is_array($crons) )
    103113        return;
  • tags/2.2/wp-includes/default-filters.php

    r5468 r5480  
    4646
    4747add_filter('comment_text', 'convert_chars');
    48 add_filter('comment_text', 'make_clickable');
     48add_filter('comment_text', 'make_clickable', 9);
    4949add_filter('comment_text', 'force_balance_tags', 25);
    5050add_filter('comment_text', 'wpautop', 30);
     
    146146add_filter('option_ping_sites', 'privacy_ping_filter');
    147147add_filter('option_blog_charset', 'wp_specialchars');
     148add_filter('option_home', '_config_wp_home');
     149add_filter('option_siteurl', '_config_wp_siteurl');
    148150add_filter('mce_plugins', '_mce_load_rtl_plugin');
    149151add_filter('mce_buttons', '_mce_add_direction_buttons');
     
    171173add_action('admin_print_scripts', 'wp_print_scripts', 20);
    172174add_action('mce_options', '_mce_set_direction');
     175add_action('init', 'smilies_init', 5);
     176add_action( 'plugins_loaded', 'wp_maybe_load_widgets', 0 );
     177add_action( 'shutdown', 'wp_ob_end_flush_all', 1);
     178
    173179?>
  • tags/2.2/wp-includes/deprecated.php

    r5468 r5480  
    22
    33/*
    4  *  Deprecated global variables.
     4 * Deprecated global variables.
    55 */
    6  
     6
    77$tableposts = $wpdb->posts;
    88$tableusers = $wpdb->users;
     
    1616
    1717/*
    18  * Deprecated functios come here to die.
     18 * Deprecated functions come here to die.
    1919 */
    2020
    21 // Deprecated.  Use get_post().
     21// Use get_post().
    2222function get_postdata($postid) {
    2323    $post = &get_post($postid);
     
    4444}
    4545
    46 // Deprecated.  Use the new post loop.
     46// Use the new post loop.
    4747function start_wp() {
    4848    global $wp_query, $post;
     
    5454}
    5555
    56 // Deprecated.
    5756function the_category_ID($echo = true) {
    5857    // Grab the first cat in the list.
     
    6665}
    6766
    68 // Deprecated.
    6967function the_category_head($before='', $after='') {
    7068    global $currentcat, $previouscat;
     
    8078}
    8179
    82 // Deprecated.  Use previous_post_link().
     80// Use previous_post_link().
    8381function previous_post($format='%', $previous='previous post: ', $title='yes', $in_same_cat='no', $limitprev=1, $excluded_categories='') {
    8482
     
    10199}
    102100
    103 // Deprecated.  Use next_post_link().
     101// Use next_post_link().
    104102function next_post($format='%', $next='next post: ', $title='yes', $in_same_cat='no', $limitnext=1, $excluded_categories='') {
    105103
     
    123121
    124122//
    125 // These are deprecated.  Use current_user_can().
     123// Use current_user_can() for these.
    126124//
    127125
     
    245243    $args = add_query_arg('category', $cat_id, $args);
    246244    wp_get_links($args);
    247 } // end wp_get_linksbyname
     245}
    248246
    249247/** function get_linkobjectsbyname()
     
    422420}
    423421
     422// Use wp_list_cats().
    424423function list_cats($optionall = 1, $all = 'All', $sort_column = 'ID', $sort_order = 'asc', $file = '', $list = true, $optiondates = 0, $optioncount = 0, $hide_empty = 1, $use_desc_for_title = 1, $children=FALSE, $child_of=0, $categories=0, $recurse=0, $feed = '', $feed_image = '', $exclude = '', $hierarchical=FALSE) {
    425424    $query = compact('optionall', 'all', 'sort_column', 'sort_order', 'file', 'list', 'optiondates', 'optioncount', 'hide_empty', 'use_desc_for_title', 'children',
     
    470469}
    471470
    472 // Deprecated.  Use wp_print_scripts() or WP_Scripts instead.
     471// Use wp_print_scripts() or WP_Scripts.
    473472function tinymce_include() {
    474     wp_print_script( 'wp_tiny_mce' );
     473    wp_print_script('wp_tiny_mce');
    475474}
    476475
     
    488487}
    489488
     489// Use wp_get_archives().
    490490function get_archives($type='', $limit='', $format='html', $before = '', $after = '', $show_post_count = false) {
    491491    $args = compact('type', 'limit', 'format', 'before', 'after', 'show_post_count');
     
    493493}
    494494
    495 // Deprecated. Use get_author_posts_url().
     495// Use get_author_posts_url().
    496496function get_author_link($echo = false, $author_id, $author_nicename = '') {
    497497    $link = get_author_posts_url($author_id, $author_nicename);
     
    502502}
    503503
     504// Use wp_link_pages().
    504505function link_pages($before='<br />', $after='<br />', $next_or_number='number', $nextpagelink='next page', $previouspagelink='previous page', $pagelink='%', $more_file='') {
    505506    $args = compact('before', 'after', 'next_or_number', 'nextpagelink', 'previouspagelink', 'pagelink', 'more_file');
     
    507508}
    508509
     510// Use get_option().
    509511function get_settings($option) {
    510512    return get_option($option);
  • tags/2.2/wp-includes/feed.php

    r5468 r5480  
    33function get_bloginfo_rss($show = '') {
    44    $info = strip_tags(get_bloginfo($show));
    5     return apply_filters('bloginfo_rss', convert_chars($info));
     5    return apply_filters('get_bloginfo_rss', convert_chars($info));
    66}
    77
    88
    99function bloginfo_rss($show = '') {
    10     echo get_bloginfo_rss($show);
    11 }
    12 
     10    echo apply_filters('bloginfo_rss', get_bloginfo_rss($show));
     11}
     12
     13function get_wp_title_rss($sep = '&#187;') {
     14    $title = wp_title($sep, false);
     15    $title = apply_filters('get_wp_title_rss', $title);
     16    return $title;
     17}
     18
     19function wp_title_rss($sep = '&#187;') {
     20    echo apply_filters('wp_title_rss', get_wp_title_rss($sep));
     21}
    1322
    1423function get_the_title_rss() {
     
    9099
    91100
    92 function comments_rss_link($link_text = 'Comments RSS', $commentsrssfilename = '') {
    93     $url = comments_rss($commentsrssfilename);
     101function comments_rss_link($link_text = 'Comments RSS', $commentsrssfilename = 'nolongerused') {
     102    $url = get_post_comments_feed_link();
    94103    echo "<a href='$url'>$link_text</a>";
    95104}
    96105
    97106
    98 function comments_rss($commentsrssfilename = '') {
    99     global $id;
    100 
    101     if ( '' != get_option('permalink_structure') )
    102         $url = trailingslashit( get_permalink() ) . 'feed/';
    103     else
    104         $url = get_option('home') . "/$commentsrssfilename?feed=rss2&amp;p=$id";
    105 
    106     return apply_filters('post_comments_feed_link', $url);
     107function comments_rss($commentsrssfilename = 'nolongerused') {
     108    return get_post_comments_feed_link();
    107109}
    108110
     
    116118    } else {
    117119        $link = get_author_posts_url($author_id, $author_nicename);
    118         $link = $link . "feed/";
     120        $link = $link . user_trailingslashit('feed', 'feed');
    119121    }
    120122
     
    134136    } else {
    135137        $link = get_category_link($cat_ID);
    136         $link = $link . "feed/";
     138        $link = $link . user_trailingslashit('feed', 'feed');
    137139    }
    138140
     
    147149function get_the_category_rss($type = 'rss') {
    148150    $categories = get_the_category();
     151    $home = get_bloginfo_rss('home');
    149152    $the_list = '';
    150153    foreach ( (array) $categories as $category ) {
     
    152155        if ( 'rdf' == $type )
    153156            $the_list .= "\n\t\t<dc:subject><![CDATA[$category->cat_name]]></dc:subject>\n";
     157        if ( 'atom' == $type )
     158            $the_list .= "<category scheme='$home' term='$category->cat_name' />";
    154159        else
    155160            $the_list .= "\n\t\t<category><![CDATA[$category->cat_name]]></category>\n";
     
    161166function the_category_rss($type = 'rss') {
    162167    echo get_the_category_rss($type);
     168}
     169
     170function html_type_rss() {
     171    $type = get_bloginfo('html_type');
     172    if (strpos($type, 'xhtml') !== false)
     173        $type = 'xhtml';
     174    else
     175        $type = 'html';
     176    echo $type;
    163177}
    164178
     
    169183        return;
    170184
    171     $custom_fields = get_post_custom();
    172     if ( is_array($custom_fields) ) {
    173         while ( list($key, $val) = each($custom_fields) ) {
    174             if ( $key == 'enclosure' ) {
    175                 if ( is_array($val) ) {
    176                     foreach ( (array) $val as $enc ) {
    177                         $enclosure = split( "\n", $enc );
    178                         print "<enclosure url='".trim( htmlspecialchars($enclosure[ 0 ]) )."' length='".trim( $enclosure[ 1 ] )."' type='".trim( $enclosure[ 2 ] )."'/>\n";
    179                     }
    180                 }
     185    foreach (get_post_custom() as $key => $val) {
     186        if ($key == 'enclosure') {
     187            foreach ((array)$val as $enc) {
     188                $enclosure = split("\n", $enc);
     189                echo apply_filters('rss_enclosure', '<enclosure url="' . trim(htmlspecialchars($enclosure[0])) . '" length="' . trim($enclosure[1]) . '" type="' . trim($enclosure[2]) . '" />' . "\n");
    181190            }
    182191        }
     
    184193}
    185194
     195function atom_enclosure() {
     196    global $id, $post;
     197    if ( !empty($post->post_password) && ($_COOKIE['wp-postpass_'.COOKIEHASH] != $post->post_password) )
     198        return;
     199
     200    foreach (get_post_custom() as $key => $val) {
     201        if ($key == 'enclosure') {
     202            foreach ((array)$val as $enc) {
     203                $enclosure = split("\n", $enc);
     204                echo apply_filters('atom_enclosure', '<link href="' . trim(htmlspecialchars($enclosure[0])) . '" rel="enclosure" length="' . trim($enclosure[1]) . '" type="' . trim($enclosure[2]) . '" />' . "\n");
     205            }
     206        }
     207    }
     208}
     209
    186210?>
  • tags/2.2/wp-includes/formatting.php

    r5468 r5480  
    2222
    2323    $dynamic_characters = array('/\'(\d\d(?:&#8217;|\')?s)/', '/(\s|\A|")\'/', '/(\d+)"/', '/(\d+)\'/', '/(\S)\'([^\'\s])/', '/(\s|\A)"(?!\s)/', '/"(\s|\S|\Z)/', '/\'([\s.]|\Z)/', '/(\d+)x(\d+)/');
    24     $dynamic_replacements = array('&#8217;$1','$1&#8216;', '$1&#8243;', '$1&#8242;', '$1&#8217;$2', '$1&#8220;$2', '&#8221;$1', '&#8217;$1', '$1&#215;$2'); 
     24    $dynamic_replacements = array('&#8217;$1','$1&#8216;', '$1&#8243;', '$1&#8242;', '$1&#8217;$2', '$1&#8220;$2', '&#8221;$1', '&#8217;$1', '$1&#215;$2');
    2525
    2626    for ( $i = 0; $i < $stop; $i++ ) {
     
    3030            // static strings
    3131            $curl = str_replace($static_characters, $static_replacements, $curl);
    32 
    3332            // regular expressions
    3433            $curl = preg_replace($dynamic_characters, $dynamic_replacements, $curl);
    35         } elseif ( strstr($curl, '<code') || strstr($curl, '<pre') || strstr($curl, '<kbd') || strstr($curl, '<style') || strstr($curl, '<script') ) {
     34        } elseif (strpos($curl, '<code') !== false || strpos($curl, '<pre') !== false || strpos($curl, '<kbd') !== false || strpos($curl, '<style') !== false || strpos($curl, '<script') !== false) {
    3635            $next = false;
    3736        } else {
     
    5756    $pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
    5857    // Space things out a little
    59     $allblocks = '(?:table|thead|tfoot|caption|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|blockquote|address|math|style|script|object|input|param|p|h[1-6])';
     58    $allblocks = '(?:table|thead|tfoot|caption|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|map|area|blockquote|address|math|style|input|p|h[1-6]|hr)';
    6059    $pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee);
    6160    $pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
     
    7978    $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
    8079    $pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
    81     if ( strstr( $pee, '<pre' ) )
     80    if (strpos($pee, '<pre') !== false)
    8281        $pee = preg_replace('!(<pre.*?>)(.*?)</pre>!ise', " stripslashes('$1') .  stripslashes(clean_pre('$2'))  . '</pre>' ", $pee);
    8382    $pee = preg_replace( "|\n</p>$|", '</p>', $pee );
     
    565564
    566565function trailingslashit($string) {
    567         if ( '/' != substr($string, -1)) {
    568                 $string .= '/';
    569         }
    570         return $string;
     566    return untrailingslashit($string) . '/';
     567}
     568
     569function untrailingslashit($string) {
     570    return rtrim($string, '/');
    571571}
    572572
     
    582582
    583583
    584 function stripslashes_deep($value)
    585 {
     584function stripslashes_deep($value) {
    586585     $value = is_array($value) ?
    587                              array_map('stripslashes_deep', $value) :
    588                              stripslashes($value);
     586         array_map('stripslashes_deep', $value) :
     587         stripslashes($value);
     588
     589     return $value;
     590}
     591
     592function urlencode_deep($value) {
     593     $value = is_array($value) ?
     594         array_map('urlencode_deep', $value) :
     595         urlencode($value);
    589596
    590597     return $value;
     
    659666function is_email($user_email) {
    660667    $chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";
    661     if(strstr($user_email, '@') && strstr($user_email, '.')) {
     668    if (strpos($user_email, '@') !== false && strpos($user_email, '.') !== false) {
    662669        if (preg_match($chars, $user_email)) {
    663670            return true;
     
    10751082    // Append http unless a relative link starting with / or a php file.
    10761083    if ( strpos($url, '://') === false &&
    1077         substr( $url, 0, 1 ) != '/' && !preg_match('/^[a-z0-9]+?\.php/i', $url) )
     1084        substr( $url, 0, 1 ) != '/' && !preg_match('/^[a-z0-9-]+?\.php/i', $url) )
    10781085        $url = 'http://' . $url;
    10791086   
  • tags/2.2/wp-includes/functions.php

    r5468 r5480  
    99        return false;
    1010    }
    11     $i = mktime(substr($m,11,2),substr($m,14,2),substr($m,17,2),substr($m,5,2),substr($m,8,2),substr($m,0,4));
     11    $i = mktime(
     12        (int) substr( $m, 11, 2 ), (int) substr( $m, 14, 2 ), (int) substr( $m, 17, 2 ),
     13        (int) substr( $m, 5, 2 ), (int) substr( $m, 8, 2 ), (int) substr( $m, 0, 4 )
     14    );
    1215
    1316    if( 'U' == $dateformatstring )
     
    204207    global $wpdb;
    205208
    206     $value = wp_cache_get($setting, 'options');
    207 
    208     if ( false === $value ) {
    209         if ( defined('WP_INSTALLING') )
    210             $wpdb->hide_errors();
    211         $row = $wpdb->get_row("SELECT option_value FROM $wpdb->options WHERE option_name = '$setting' LIMIT 1");
    212         if ( defined('WP_INSTALLING') )
    213             $wpdb->show_errors();
    214 
    215         if( is_object( $row) ) { // Has to be get_row instead of get_var because of funkiness with 0, false, null values
    216             $value = $row->option_value;
    217             wp_cache_set($setting, $value, 'options');
    218         } else {
    219             return false;
     209    // Allow plugins to short-circuit options.
     210    $pre = apply_filters( 'pre_option_' . $setting, false );
     211    if ( $pre )
     212        return $pre;
     213
     214    // prevent non-existent options from triggering multiple queries
     215    $notoptions = wp_cache_get('notoptions', 'options');
     216    if ( isset($notoptions[$setting]) )
     217        return false;
     218
     219    $alloptions = wp_load_alloptions();
     220
     221    if ( isset($alloptions[$setting]) ) {
     222        $value = $alloptions[$setting];
     223    } else {
     224        $value = wp_cache_get($setting, 'options');
     225
     226        if ( false === $value ) {
     227            if ( defined('WP_INSTALLING') )
     228                $wpdb->hide_errors();
     229            $row = $wpdb->get_row("SELECT option_value FROM $wpdb->options WHERE option_name = '$setting' LIMIT 1");
     230            if ( defined('WP_INSTALLING') )
     231                $wpdb->show_errors();
     232
     233            if( is_object( $row) ) { // Has to be get_row instead of get_var because of funkiness with 0, false, null values
     234                $value = $row->option_value;
     235                wp_cache_add($setting, $value, 'options');
     236            } else { // option does not exist, so we must cache its non-existence
     237                $notoptions[$setting] = true;
     238                wp_cache_set('notoptions', $notoptions, 'options');
     239                return false;
     240            }
    220241        }
    221242    }
     
    229250
    230251    return apply_filters( 'option_' . $setting, maybe_unserialize($value) );
     252}
     253
     254function wp_protect_special_option($option) {
     255    $protected = array('alloptions', 'notoptions');
     256    if ( in_array($option, $protected) )
     257        die(sprintf(__('%s is a protected WP option and may not be modified'), wp_specialchars($option)));
    231258}
    232259
     
    258285}
    259286
     287function wp_load_alloptions() {
     288    global $wpdb;
     289
     290    $alloptions = wp_cache_get('alloptions', 'options');
     291
     292    if ( !$alloptions ) {
     293        $wpdb->hide_errors();
     294        if ( !$alloptions_db = $wpdb->get_results("SELECT option_name, option_value FROM $wpdb->options WHERE autoload = 'yes'") )
     295            $alloptions_db = $wpdb->get_results("SELECT option_name, option_value FROM $wpdb->options");
     296        $wpdb->show_errors();
     297        $alloptions = array();
     298        foreach ( (array) $alloptions_db as $o )
     299            $alloptions[$o->option_name] = $o->option_value;
     300        wp_cache_add('alloptions', $alloptions, 'options');
     301    }
     302    return $alloptions;
     303}
     304
    260305function update_option($option_name, $newvalue) {
    261306    global $wpdb;
    262307
     308    wp_protect_special_option($option_name);
     309
    263310    if ( is_string($newvalue) )
    264311        $newvalue = trim($newvalue);
     
    266313    // If the new and old values are the same, no need to update.
    267314    $oldvalue = get_option($option_name);
    268     if ( $newvalue == $oldvalue ) {
     315    if ( $newvalue === $oldvalue ) {
    269316        return false;
    270317    }
     
    275322    }
    276323
     324    $notoptions = wp_cache_get('notoptions', 'options');
     325    if ( isset($notoptions[$option_name]) ) {
     326        unset($notoptions[$option_name]);
     327        wp_cache_set('notoptions', $notoptions, 'options');
     328    }
     329
    277330    $_newvalue = $newvalue;
    278331    $newvalue = maybe_serialize($newvalue);
    279332
    280     wp_cache_set($option_name, $newvalue, 'options');
     333    $alloptions = wp_load_alloptions();
     334    if ( isset($alloptions[$option_name]) ) {
     335        $alloptions[$option_name] = $newvalue;
     336        wp_cache_set('alloptions', $alloptions, 'options');
     337    } else {
     338        wp_cache_set($option_name, $newvalue, 'options');
     339    }
    281340
    282341    $newvalue = $wpdb->escape($newvalue);
     
    294353    global $wpdb;
    295354
    296     // Make sure the option doesn't already exist
    297     if ( false !== get_option($name) )
    298         return;
     355    wp_protect_special_option($name);
     356
     357    // Make sure the option doesn't already exist we can check the cache before we ask for a db query
     358    $notoptions = wp_cache_get('notoptions', 'options');
     359    if ( isset($notoptions[$name]) ) {
     360        unset($notoptions[$name]);
     361        wp_cache_set('notoptions', $notoptions, 'options');
     362    } elseif ( false !== get_option($name) ) {
     363            return;
     364    }
    299365
    300366    $value = maybe_serialize($value);
    301367
    302     wp_cache_set($name, $value, 'options');
     368    if ( 'yes' == $autoload ) {
     369        $alloptions = wp_load_alloptions();
     370        $alloptions[$name] = $value;
     371        wp_cache_set('alloptions', $alloptions, 'options');
     372    } else {
     373        wp_cache_set($name, $value, 'options');
     374    }
    303375
    304376    $name = $wpdb->escape($name);
     
    312384function delete_option($name) {
    313385    global $wpdb;
     386
     387    wp_protect_special_option($name);
     388
    314389    // Get the ID, if no ID then return
    315     $option_id = $wpdb->get_var("SELECT option_id FROM $wpdb->options WHERE option_name = '$name'");
    316     if ( !$option_id ) return false;
     390    $option = $wpdb->get_row("SELECT option_id, autoload FROM $wpdb->options WHERE option_name = '$name'");
     391    if ( !$option->option_id ) return false;
    317392    $wpdb->query("DELETE FROM $wpdb->options WHERE option_name = '$name'");
    318     wp_cache_delete($name, 'options');
     393    if ( 'yes' == $option->autoload ) {
     394        $alloptions = wp_load_alloptions();
     395        if ( isset($alloptions[$name]) ) {
     396            unset($alloptions[$name]);
     397            wp_cache_set('alloptions', $alloptions, 'options');
     398        }
     399    } else {
     400        wp_cache_delete($name, 'options');
     401    }
    319402    return true;
    320403}
     
    663746    wp_cache_delete('all_category_ids', 'category');
    664747    wp_cache_delete('get_categories', 'category');
     748    delete_option('category_children');
    665749}
    666750
     
    701785    }
    702786
    703     if ( strstr($uri, '?') ) {
     787    if (strpos($uri, '?') !== false) {
    704788        $parts = explode('?', $uri, 2);
    705789        if ( 1 == count($parts) ) {
     
    710794            $query = $parts[1];
    711795        }
    712     } else if ( !empty($protocol) || strstr($uri, '/') ) {
     796    } elseif (!empty($protocol) || strpos($uri, '/') !== false) {
    713797        $base = $uri . '?';
    714798        $query = '';
     
    719803
    720804    parse_str($query, $qs);
     805    if ( get_magic_quotes_gpc() )
     806        $qs = stripslashes_deep($qs); // parse_str() adds slashes if magicquotes is on.  See: http://php.net/parse_str
     807    $qs = urlencode_deep($qs);
    721808    if ( is_array(func_get_arg(0)) ) {
    722809        $kayvees = func_get_arg(0);
     
    736823        }
    737824    }
     825    $ret = trim($ret, '?');
    738826    $ret = $protocol . $base . $ret . $frag;
    739     if ( get_magic_quotes_gpc() )
    740         $ret = stripslashes($ret); // parse_str() adds slashes if magicquotes is on.  See: http://php.net/parse_str
    741     return trim($ret, '?');
     827    $ret = trim($ret, '?');
     828    return $ret;
    742829}
    743830
     
    829916        $text = 'Gone';
    830917
    831     if ( version_compare(phpversion(), '4.3.0', '>=') )
    832         @header("HTTP/1.1 $header $text", true, $header);
    833     else
    834         @header("HTTP/1.1 $header $text");
     918    $protocol = $_SERVER["SERVER_PROTOCOL"];
     919    if ( ('HTTP/1.1' != $protocol) && ('HTTP/1.0' != $protocol) )
     920        $protocol = 'HTTP/1.0';
     921    $status_header = "$protocol $header $text";
     922    $status_header = apply_filters('status_header', $status_header, $header, $text, $protocol);
     923
     924    if ( version_compare( phpversion(), '4.3.0', '>=' ) ) {
     925        return @header( $status_header, true, $header );
     926    } else {
     927        return @header( $status_header );
     928    }
    835929}
    836930
     
    860954
    861955function do_feed() {
     956    global $wp_query;
     957
    862958    $feed = get_query_var('feed');
    863959
     
    865961    $feed = preg_replace('/^_+/', '', $feed);
    866962
    867     if ($feed == '' || $feed == 'feed')
    868         $feed = 'rss2';
    869 
    870     $for_comments = false;
    871     if ( 1 != get_query_var('withoutcomments') && ( is_singular() || get_query_var('withcomments') == 1 || $feed == 'comments-rss2' ) ) {
     963    if ( $feed == '' || $feed == 'feed' )
    872964        $feed = 'rss2';
    873         $for_comments = true;   
    874     }
    875965
    876966    $hook = 'do_feed_' . $feed;
    877     do_action($hook, $for_comments);
     967    do_action($hook, $wp_query->is_comment_feed);
    878968}
    879969
    880970function do_feed_rdf() {
    881     load_template(ABSPATH . 'wp-rdf.php');
     971    load_template(ABSPATH . WPINC . '/feed-rdf.php');
    882972}
    883973
    884974function do_feed_rss() {
    885     load_template(ABSPATH . 'wp-rss.php');
     975    load_template(ABSPATH . WPINC . '/feed-rss.php');
    886976}
    887977
    888978function do_feed_rss2($for_comments) {
    889979    if ( $for_comments ) {
    890         load_template(ABSPATH . 'wp-commentsrss2.php');
    891     } else {
    892         load_template(ABSPATH . 'wp-rss2.php');
    893     }
    894 }
    895 
    896 function do_feed_atom() {
    897     load_template(ABSPATH . 'wp-atom.php');
     980        load_template(ABSPATH . WPINC . '/feed-rss2-comments.php');
     981    } else {
     982        load_template(ABSPATH . WPINC . '/feed-rss2.php');
     983    }
     984}
     985
     986function do_feed_atom($for_comments) {
     987    if ($for_comments) {
     988        load_template(ABSPATH . WPINC . '/feed-atom-comments.php');
     989    } else {
     990        load_template(ABSPATH . WPINC . '/feed-atom.php');
     991    }
    898992}
    899993
    900994function do_robots() {
     995    header('Content-type: text/plain; charset=utf-8');
     996
    901997    do_action('do_robotstxt');
     998
    902999    if ( '0' == get_option('blog_public') ) {
    9031000        echo "User-agent: *\n";
     
    9141011    $installed = $wpdb->get_var("SELECT option_value FROM $wpdb->options WHERE option_name = 'siteurl'");
    9151012    $wpdb->show_errors();
    916     return $installed;
     1013
     1014    $install_status = !empty( $installed ) ? TRUE : FALSE;
     1015    return $install_status;
    9171016}
    9181017
     
    11431242        $trans['moderate']['comments'] = array(__('Are you sure you want to moderate comments?'), false);
    11441243
    1145         $trans['add']['bookmark'] = array(__('Are you sure you want to add this bookmark?'), false);
    1146         $trans['delete']['bookmark'] = array(__('Are you sure you want to delete this bookmark: &quot;%s&quot;?'), 'use_id');
    1147         $trans['update']['bookmark'] = array(__('Are you sure you want to edit this bookmark: &quot;%s&quot;?'), 'use_id');
    1148         $trans['bulk']['bookmarks'] = array(__('Are you sure you want to bulk modify bookmarks?'), false);
     1244        $trans['add']['bookmark'] = array(__('Are you sure you want to add this link?'), false);
     1245        $trans['delete']['bookmark'] = array(__('Are you sure you want to delete this link: &quot;%s&quot;?'), 'use_id');
     1246        $trans['update']['bookmark'] = array(__('Are you sure you want to edit this link: &quot;%s&quot;?'), 'use_id');
     1247        $trans['bulk']['bookmarks'] = array(__('Are you sure you want to bulk modify links?'), false);
    11491248
    11501249        $trans['add']['page'] = array(__('Are you sure you want to add this page?'), false);
     
    12161315}
    12171316
    1218 function wp_die($message, $title = '') {
     1317function wp_die( $message, $title = '' ) {
    12191318    global $wp_locale;
    12201319
    1221     header('Content-Type: text/html; charset=utf-8');
    1222 
    1223     if ( empty($title) )
    1224         $title = __('WordPress &rsaquo; Error');
    1225 
    1226     if ( strstr($_SERVER['PHP_SELF'], 'wp-admin') )
     1320    if ( is_wp_error( $message ) ) {
     1321        if ( empty($title) ) {
     1322            $error_data = $message->get_error_data();
     1323            if ( is_array($error_data) && isset($error_data['title']) )
     1324                $title = $error_data['title'];
     1325        }
     1326        $errors = $message->get_error_messages();
     1327        switch ( count($errors) ) :
     1328        case 0 :
     1329            $message = '';
     1330            break;
     1331        case 1 :
     1332            $message = "<p>{$errors[0]}</p>";
     1333            break;
     1334        default :
     1335            $message = "<ul>\n\t\t<li>" . join( "</li>\n\t\t<li>", $errors ) . "</li>\n\t</ul>";
     1336            break;
     1337        endswitch;
     1338    } elseif ( is_string($message) ) {
     1339        $message = "<p>$message</p>";
     1340    }
     1341
     1342    if (strpos($_SERVER['PHP_SELF'], 'wp-admin') !== false)
    12271343        $admin_dir = '';
    12281344    else
    12291345        $admin_dir = 'wp-admin/';
     1346
     1347    if ( !did_action('admin_head') ) :
     1348    header('Content-Type: text/html; charset=utf-8');
     1349
     1350    if ( empty($title) )
     1351        $title = __('WordPress &rsaquo; Error');
     1352
     1353
    12301354
    12311355?>
     
    12361360    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    12371361    <link rel="stylesheet" href="<?php echo $admin_dir; ?>install.css" type="text/css" />
    1238 <?php if ( ('rtl' == $wp_locale->text_direction) ) : ?>
     1362<?php
     1363if ( ( $wp_locale ) && ('rtl' == $wp_locale->text_direction) ) : ?>
    12391364    <link rel="stylesheet" href="<?php echo $admin_dir; ?>install-rtl.css" type="text/css" />
    12401365<?php endif; ?>
    12411366</head>
    12421367<body>
     1368<?php endif; ?>
    12431369    <h1 id="logo"><img alt="WordPress" src="<?php echo $admin_dir; ?>images/wordpress-logo.png" /></h1>
    1244     <p><?php echo $message; ?></p>
     1370    <?php echo $message; ?>
     1371
    12451372</body>
    12461373</html>
    12471374<?php
    1248 
    12491375    die();
     1376}
     1377
     1378function _config_wp_home($url = '') {
     1379    if ( defined( 'WP_HOME' ) )
     1380        return WP_HOME;
     1381    else return $url;
     1382}
     1383
     1384function _config_wp_siteurl($url = '') {
     1385    if ( defined( 'WP_SITEURL' ) )
     1386        return WP_SITEURL;
     1387    else return $url;
    12501388}
    12511389
     
    12781416    return $input;
    12791417}
     1418
     1419function smilies_init() {
     1420    global $wpsmiliestrans, $wp_smiliessearch, $wp_smiliesreplace;
     1421
     1422    // don't bother setting up smilies if they are disabled
     1423    if ( !get_option('use_smilies') )
     1424        return;
     1425
     1426    if (!isset($wpsmiliestrans)) {
     1427        $wpsmiliestrans = array(
     1428        ':mrgreen:' => 'icon_mrgreen.gif',
     1429        ':neutral:' => 'icon_neutral.gif',
     1430        ':twisted:' => 'icon_twisted.gif',
     1431          ':arrow:' => 'icon_arrow.gif',
     1432          ':shock:' => 'icon_eek.gif',
     1433          ':smile:' => 'icon_smile.gif',
     1434            ':???:' => 'icon_confused.gif',
     1435           ':cool:' => 'icon_cool.gif',
     1436           ':evil:' => 'icon_evil.gif',
     1437           ':grin:' => 'icon_biggrin.gif',
     1438           ':idea:' => 'icon_idea.gif',
     1439           ':oops:' => 'icon_redface.gif',
     1440           ':razz:' => 'icon_razz.gif',
     1441           ':roll:' => 'icon_rolleyes.gif',
     1442           ':wink:' => 'icon_wink.gif',
     1443            ':cry:' => 'icon_cry.gif',
     1444            ':eek:' => 'icon_surprised.gif',
     1445            ':lol:' => 'icon_lol.gif',
     1446            ':mad:' => 'icon_mad.gif',
     1447            ':sad:' => 'icon_sad.gif',
     1448              '8-)' => 'icon_cool.gif',
     1449              '8-O' => 'icon_eek.gif',
     1450              ':-(' => 'icon_sad.gif',
     1451              ':-)' => 'icon_smile.gif',
     1452              ':-?' => 'icon_confused.gif',
     1453              ':-D' => 'icon_biggrin.gif',
     1454              ':-P' => 'icon_razz.gif',
     1455              ':-o' => 'icon_surprised.gif',
     1456              ':-x' => 'icon_mad.gif',
     1457              ':-|' => 'icon_neutral.gif',
     1458              ';-)' => 'icon_wink.gif',
     1459               '8)' => 'icon_cool.gif',
     1460               '8O' => 'icon_eek.gif',
     1461               ':(' => 'icon_sad.gif',
     1462               ':)' => 'icon_smile.gif',
     1463               ':?' => 'icon_confused.gif',
     1464               ':D' => 'icon_biggrin.gif',
     1465               ':P' => 'icon_razz.gif',
     1466               ':o' => 'icon_surprised.gif',
     1467               ':x' => 'icon_mad.gif',
     1468               ':|' => 'icon_neutral.gif',
     1469               ';)' => 'icon_wink.gif',
     1470              ':!:' => 'icon_exclaim.gif',
     1471              ':?:' => 'icon_question.gif',
     1472        );
     1473    }
     1474
     1475    $siteurl = get_option('siteurl');
     1476    foreach ( (array) $wpsmiliestrans as $smiley => $img ) {
     1477        $wp_smiliessearch[] = '/(\s|^)'.preg_quote($smiley, '/').'(\s|$)/';
     1478        $smiley_masked = htmlspecialchars(trim($smiley), ENT_QUOTES);
     1479        $wp_smiliesreplace[] = " <img src='$siteurl/wp-includes/images/smilies/$img' alt='$smiley_masked' class='wp-smiley' /> ";
     1480    }
     1481}
     1482
     1483function wp_parse_args( $args, $defaults = '' ) {
     1484    if ( is_array($args) ) :
     1485        $r =& $args;
     1486    else :
     1487        parse_str( $args, $r );
     1488        if ( get_magic_quotes_gpc() )
     1489            $r = stripslashes_deep( $r );
     1490    endif;
     1491
     1492    if ( is_array($defaults) ) :
     1493        extract($defaults);
     1494        extract($r);
     1495        return compact(array_keys($defaults)); // only those options defined in $defaults
     1496    else :
     1497        return $r;
     1498    endif;
     1499}
     1500
     1501function wp_maybe_load_widgets() {
     1502    if ( !function_exists( 'dynamic_sidebar' ) ) {
     1503        require_once ABSPATH . WPINC . '/widgets.php';
     1504        add_action( '_admin_menu', 'wp_widgets_add_menu' );
     1505    }
     1506}
     1507
     1508function wp_widgets_add_menu() {
     1509    global $submenu;
     1510    $submenu['themes.php'][7] = array( __( 'Widgets' ), 'edit_themes', 'widgets.php' );
     1511    ksort($submenu['themes.php'], SORT_NUMERIC);
     1512}
     1513
     1514// For PHP 5.2, make sure all output buffers are flushed
     1515// before our singletons our destroyed.
     1516function wp_ob_end_flush_all()
     1517{
     1518    while ( @ob_end_flush() );
     1519}
     1520
    12801521?>
  • tags/2.2/wp-includes/general-template.php

    r5468 r5480  
    2222
    2323function get_sidebar() {
     24    do_action( 'get_sidebar' );
    2425    if ( file_exists( TEMPLATEPATH . '/sidebar.php') )
    2526        load_template( TEMPLATEPATH . '/sidebar.php');
     
    6162function bloginfo($show='') {
    6263    $info = get_bloginfo($show);
    63     if (!strstr($show, 'url') && //don't filter URLs
    64         !strstr($show, 'directory') &&
    65         !strstr($show, 'home')) {
     64   
     65    // Don't filter URL's.
     66    if (strpos($show, 'url') === false ||
     67        strpos($show, 'directory') === false ||
     68        strpos($show, 'home') === false) {
    6669        $info = apply_filters('bloginfo', $info, $show);
    6770        $info = convert_chars($info);
     
    7376}
    7477
    75 
     78/**
     79 * Note: some of these values are DEPRECATED. Meaning they could be
     80 * taken out at any time and shouldn't be relied upon. Options
     81 * without "// DEPRECATED" are the preferred and recommended ways
     82 * to get the information.
     83 */
    7684function get_bloginfo($show='') {
    7785
    7886    switch($show) {
    7987        case 'url' :
    80         case 'home' :
    81         case 'siteurl' :
     88        case 'home' : // DEPRECATED
     89        case 'siteurl' : // DEPRECATED
    8290            $output = get_option('home');
    8391            break;
     
    100108            $output = get_feed_link('atom');
    101109            break;
     110        case 'comments_atom_url':
     111            $output = get_feed_link('comments_atom');
    102112        case 'comments_rss2_url':
    103113            $output = get_feed_link('comments_rss2');
     
    156166    $author = get_query_var('author');
    157167    $author_name = get_query_var('author_name');
    158     $m = (int) get_query_var('m');
    159     $year = (int) get_query_var('year');
    160     $monthnum = (int)get_query_var('monthnum');
    161     $day = (int) get_query_var('day');
     168    $m = get_query_var('m');
     169    $year = get_query_var('year');
     170    $monthnum = get_query_var('monthnum');
     171    $day = get_query_var('day');
    162172    $title = '';
    163173
     
    167177            if ( !stristr($cat,'-') )
    168178                $title = apply_filters('single_cat_title', get_the_category_by_ID($cat));
    169     }
    170     if ( !empty($category_name) ) {
     179    } elseif ( !empty($category_name) ) {
    171180        if ( stristr($category_name,'/') ) {
    172181                $category_name = explode('/',$category_name);
     
    193202    if ( !empty($m) ) {
    194203        $my_year = substr($m, 0, 4);
    195         $my_month = $wp_locale->get_month($m);
    196         $title = "$my_year $sep $my_month";
     204        $my_month = $wp_locale->get_month(substr($m, 4, 2));
     205        $my_day = intval(substr($m, 6, 2));
     206        $title = "$my_year" . ($my_month ? "$sep $my_month" : "") . ($my_day ? "$sep $my_day" : "");
    197207    }
    198208
     
    207217    // If there is a post
    208218    if ( is_single() || is_page() ) {
    209         $queried = $wp_query->get_queried_object();
    210         $title = strip_tags($queried->post_title);
     219        $post = $wp_query->get_queried_object();
    211220        $title = apply_filters('single_post_title', $title);
     221        $title = strip_tags($post->post_title);
    212222    }
    213223
     
    263273    global $wp_locale;
    264274
    265     $m = (int) get_query_var('m');
    266     $year = (int) get_query_var('year');
    267     $monthnum = (int) get_query_var('monthnum');
     275    $m = get_query_var('m');
     276    $year = get_query_var('year');
     277    $monthnum = get_query_var('monthnum');
    268278
    269279    if ( !empty($monthnum) && !empty($year) ) {
     
    345355    $add_minutes = intval(60 * (get_option('gmt_offset') - $add_hours));
    346356
     357    //filters
     358    $where = apply_filters('getarchives_where', "WHERE post_type = 'post' AND post_status = 'publish'", $r );
     359    $join = apply_filters('getarchives_join', "", $r);
     360
    347361    if ( 'monthly' == $type ) {
    348         $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);
     362        $arcresults = $wpdb->get_results("SELECT DISTINCT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts FROM $wpdb->posts $join $where GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC" . $limit);
    349363        if ( $arcresults ) {
    350364            $afterafter = $after;
     
    358372        }
    359373    } elseif ('yearly' == $type) {
    360          $arcresults = $wpdb->get_results("SELECT DISTINCT YEAR(post_date) AS `year`, count(ID) as posts FROM $wpdb->posts WHERE post_type ='post' AND post_status = 'publish' GROUP BY YEAR(post_date) ORDER BY post_date DESC" . $limit);
     374         $arcresults = $wpdb->get_results("SELECT DISTINCT YEAR(post_date) AS `year`, count(ID) as posts FROM $wpdb->posts $join $where GROUP BY YEAR(post_date) ORDER BY post_date DESC" . $limit);
    361375        if ($arcresults) {
    362             $afterafter = $after;
    363             foreach ($arcresults as $arcresult) {
    364                 $url = get_year_link($arcresult->year);
    365                 $text = sprintf('%d', $arcresult->year);
     376            $afterafter = $after;
     377            foreach ($arcresults as $arcresult) {
     378                $url = get_year_link($arcresult->year);
     379                $text = sprintf('%d', $arcresult->year);
    366380                if ($show_post_count)
    367                     $after = '&nbsp;('.$arcresult->posts.')' . $afterafter;
    368                 echo get_archives_link($url, $text, $format, $before, $after);
    369             }
    370         }           
     381                    $after = '&nbsp;('.$arcresult->posts.')' . $afterafter;
     382                echo get_archives_link($url, $text, $format, $before, $after);
     383            }
     384        }
    371385    } elseif ( 'daily' == $type ) {
    372         $arcresults = $wpdb->get_results("SELECT DISTINCT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, DAYOFMONTH(post_date) AS `dayofmonth`, count(ID) as posts FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' GROUP BY YEAR(post_date), MONTH(post_date), DAYOFMONTH(post_date) ORDER BY post_date DESC" . $limit);
     386        $arcresults = $wpdb->get_results("SELECT DISTINCT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, DAYOFMONTH(post_date) AS `dayofmonth`, count(ID) as posts FROM $wpdb->posts $join $where GROUP BY YEAR(post_date), MONTH(post_date), DAYOFMONTH(post_date) ORDER BY post_date DESC" . $limit);
    373387        if ( $arcresults ) {
    374388            $afterafter = $after;
     
    384398    } elseif ( 'weekly' == $type ) {
    385399        $start_of_week = get_option('start_of_week');
    386         $arcresults = $wpdb->get_results("SELECT DISTINCT WEEK(post_date, $start_of_week) AS `week`, YEAR(post_date) AS yr, DATE_FORMAT(post_date, '%Y-%m-%d') AS yyyymmdd, count(ID) as posts FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' GROUP BY WEEK(post_date, $start_of_week), YEAR(post_date) ORDER BY post_date DESC" . $limit);
     400        $arcresults = $wpdb->get_results("SELECT DISTINCT WEEK(post_date, $start_of_week) AS `week`, YEAR(post_date) AS yr, DATE_FORMAT(post_date, '%Y-%m-%d') AS yyyymmdd, count(ID) as posts FROM $wpdb->posts $join $where GROUP BY WEEK(post_date, $start_of_week), YEAR(post_date) ORDER BY post_date DESC" . $limit);
    387401        $arc_w_last = '';
    388402        $afterafter = $after;
     
    405419    } elseif ( ( 'postbypost' == $type ) || ('alpha' == $type) ) {
    406420        ('alpha' == $type) ? $orderby = "post_title ASC " : $orderby = "post_date DESC ";
    407         $arcresults = $wpdb->get_results("SELECT * FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' ORDER BY $orderby $limit");
     421        $arcresults = $wpdb->get_results("SELECT * FROM $wpdb->posts $join $where ORDER BY $orderby $limit");
    408422        if ( $arcresults ) {
    409423            foreach ( $arcresults as $arcresult ) {
     
    412426                    $arc_title = $arcresult->post_title;
    413427                    if ( $arc_title )
    414                         $text = strip_tags($arc_title);
     428                        $text = strip_tags(apply_filters('the_title', $arc_title));
    415429                    else
    416430                        $text = $arcresult->ID;
     
    495509            LIMIT 1");
    496510
    497     echo '<table id="wp-calendar">
     511    echo '<table id="wp-calendar" summary="' . __('Calendar') . '">
    498512    <caption>' . $wp_locale->get_month($thismonth) . ' ' . date('Y', $unixmonth) . '</caption>
    499513    <thead>
     
    557571    }
    558572
    559 
    560 
    561     if ( strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE') || strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'camino') || strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'safari') )
     573    if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false || strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'camino') !== false || strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'safari') !== false)
    562574        $ak_title_separator = "\n";
    563575    else
     
    574586    if ( $ak_post_titles ) {
    575587        foreach ( $ak_post_titles as $ak_post_title ) {
     588           
     589                $post_title = apply_filters( "the_title", $ak_post_title->post_title );
     590                $post_title = str_replace('"', '&quot;', wptexturize( $post_title ));
     591                               
    576592                if ( empty($ak_titles_for_day['day_'.$ak_post_title->dom]) )
    577593                    $ak_titles_for_day['day_'.$ak_post_title->dom] = '';
    578594                if ( empty($ak_titles_for_day["$ak_post_title->dom"]) ) // first one
    579                     $ak_titles_for_day["$ak_post_title->dom"] = str_replace('"', '&quot;', wptexturize($ak_post_title->post_title));
     595                    $ak_titles_for_day["$ak_post_title->dom"] = $post_title;
    580596                else
    581                     $ak_titles_for_day["$ak_post_title->dom"] .= $ak_title_separator . str_replace('"', '&quot;', wptexturize($ak_post_title->post_title));
     597                    $ak_titles_for_day["$ak_post_title->dom"] .= $ak_title_separator . $post_title;
    582598        }
    583599    }
     
    620636    echo $output;
    621637    $cache[ $key ] = $output;
    622     wp_cache_set( 'get_calendar', $cache, 'calendar' );
     638    wp_cache_add( 'get_calendar', $cache, 'calendar' );
    623639}
    624640
     
    794810function user_can_richedit() {
    795811    global $wp_rich_edit, $pagenow;
    796 
    797     if ( !isset($wp_rich_edit) )
    798         $wp_rich_edit = ( 'true' == get_user_option('rich_editing') && !preg_match('!opera[ /][2-8]|konqueror|safari!i', $_SERVER['HTTP_USER_AGENT']) && 'comment.php' != $pagenow && rich_edit_exists() ) ? true : false;
     812   
     813    if ( !isset( $wp_rich_edit) ) {
     814        if ( get_user_option( 'rich_editing' ) == 'true' &&
     815            ( ( preg_match( '!AppleWebKit/(\d+)!', $_SERVER['HTTP_USER_AGENT'], $match ) && intval($match[1]) >= 420 ) ||
     816                !preg_match( '!opera[ /][2-8]|konqueror|safari!i', $_SERVER['HTTP_USER_AGENT'] ) ) ) {
     817            $wp_rich_edit = true;
     818        } else {
     819            $wp_rich_edit = false;
     820        }
     821    }
    799822
    800823    return apply_filters('user_can_richedit', $wp_rich_edit);
  • tags/2.2/wp-includes/gettext.php

    r5468 r5480  
    11<?php
    22/*
    3   Copyright (c) 2003 Danilo Segan <danilo@kvota.net>.
    4   Copyright (c) 2005 Nico Kaiser <nico@siriux.net>
    5    
    6   This file is part of PHP-gettext.
    7 
    8   PHP-gettext is free software; you can redistribute it and/or modify
    9   it under the terms of the GNU General Public License as published by
    10   the Free Software Foundation; either version 2 of the License, or
    11   (at your option) any later version.
    12 
    13   PHP-gettext is distributed in the hope that it will be useful,
    14   but WITHOUT ANY WARRANTY; without even the implied warranty of
    15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    16   GNU General Public License for more details.
    17 
    18   You should have received a copy of the GNU General Public License
    19   along with PHP-gettext; if not, write to the Free Software
    20   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
     3    Copyright (c) 2003 Danilo Segan <danilo@kvota.net>.
     4    Copyright (c) 2005 Nico Kaiser <nico@siriux.net>
     5
     6    This file is part of PHP-gettext.
     7
     8    PHP-gettext is free software; you can redistribute it and/or modify
     9    it under the terms of the GNU General Public License as published by
     10    the Free Software Foundation; either version 2 of the License, or
     11    (at your option) any later version.
     12
     13    PHP-gettext is distributed in the hope that it will be useful,
     14    but WITHOUT ANY WARRANTY; without even the implied warranty of
     15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     16    GNU General Public License for more details.
     17
     18    You should have received a copy of the GNU General Public License
     19    along with PHP-gettext; if not, write to the Free Software
     20    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    2121
    2222*/
    23  
     23
    2424/**
    2525 * Provides a simple gettext replacement that works independently from
     
    2727 * It can read MO files and use them for translating strings.
    2828 * The files are passed to gettext_reader as a Stream (see streams.php)
    29  * 
     29 *
    3030 * This version has the ability to cache all strings and translations to
    3131 * speed up the string lookup.
     
    3535 */
    3636class gettext_reader {
    37   //public:
    38    var $error = 0; // public variable that holds error code (0 if no error)
    39    
    40    //private:
    41   var $BYTEORDER = 0;        // 0: low endian, 1: big endian
    42   var $STREAM = NULL;
    43   var $short_circuit = false;
    44   var $enable_cache = false;
    45   var $originals = NULL;      // offset of original table
    46   var $translations = NULL;    // offset of translation table
    47   var $pluralheader = NULL;    // cache header field for plural forms
    48   var $total = 0;          // total string count
    49   var $table_originals = NULL;  // table for original strings (offsets)
    50   var $table_translations = NULL;  // table for translated strings (offsets)
    51   var $cache_translations = NULL;  // original -> translation mapping
    52 
    53 
    54   /* Methods */
    55  
    56    
    57   /**
    58    * Reads a 32bit Integer from the Stream
    59    *
    60    * @access private
    61    * @return Integer from the Stream
    62    */
    63   function readint() {
    64       if ($this->BYTEORDER == 0) {
    65         // low endian
    66         $low_end = unpack('V', $this->STREAM->read(4));
    67         return array_shift($low_end);
    68       } else {
    69         // big endian
    70         $big_end = unpack('N', $this->STREAM->read(4));
    71         return array_shift($big_end);
    72       }
    73     }
    74 
    75   /**
    76    * Reads an array of Integers from the Stream
    77    *
    78    * @param int count How many elements should be read
    79    * @return Array of Integers
    80    */
    81   function readintarray($count) {
    82     if ($this->BYTEORDER == 0) {
    83         // low endian
    84         return unpack('V'.$count, $this->STREAM->read(4 * $count));
    85       } else {
    86         // big endian
    87         return unpack('N'.$count, $this->STREAM->read(4 * $count));
    88       }
    89   }
    90  
    91   /**
    92    * Constructor
    93    *
    94    * @param object Reader the StreamReader object
    95    * @param boolean enable_cache Enable or disable caching of strings (default on)
    96    */
    97   function gettext_reader($Reader, $enable_cache = true) {
    98     // If there isn't a StreamReader, turn on short circuit mode.
    99     if (! $Reader || isset($Reader->error) ) {
    100       $this->short_circuit = true;
    101       return;
    102     }
    103    
    104     // Caching can be turned off
    105     $this->enable_cache = $enable_cache;
    106 
    107     // $MAGIC1 = (int)0x950412de; //bug in PHP 5.0.2, see https://savannah.nongnu.org/bugs/?func=detailitem&item_id=10565
    108     $MAGIC1 = (int) - 1794895138;
    109     // $MAGIC2 = (int)0xde120495; //bug
    110     $MAGIC2 = (int) - 569244523;
    111 
    112     $this->STREAM = $Reader;
    113     $magic = $this->readint();
    114     if ($magic == ($MAGIC1 & 0xFFFFFFFF)) { // to make sure it works for 64-bit platforms
    115       $this->BYTEORDER = 0;
    116     } elseif ($magic == ($MAGIC2 & 0xFFFFFFFF)) {
    117       $this->BYTEORDER = 1;
    118     } else {
    119       $this->error = 1; // not MO file
    120       return false;
    121     }
    122    
    123     // FIXME: Do we care about revision? We should.
    124     $revision = $this->readint();
    125    
    126     $this->total = $this->readint();
    127     $this->originals = $this->readint();
    128     $this->translations = $this->readint();
    129   }
    130  
    131   /**
    132    * Loads the translation tables from the MO file into the cache
    133    * If caching is enabled, also loads all strings into a cache
    134    * to speed up translation lookups
    135    *
    136    * @access private
    137    */
    138   function load_tables() {
    139     if (is_array($this->cache_translations) &&
    140       is_array($this->table_originals) &&
    141       is_array($this->table_translations))
    142       return;
    143    
    144     /* get original and translations tables */
    145     $this->STREAM->seekto($this->originals);
    146     $this->table_originals = $this->readintarray($this->total * 2);
    147     $this->STREAM->seekto($this->translations);
    148     $this->table_translations = $this->readintarray($this->total * 2);
    149    
    150     if ($this->enable_cache) {
    151       $this->cache_translations = array ();
    152       /* read all strings in the cache */
    153       for ($i = 0; $i < $this->total; $i++) {
    154         $this->STREAM->seekto($this->table_originals[$i * 2 + 2]);
    155         $original = $this->STREAM->read($this->table_originals[$i * 2 + 1]);
    156         $this->STREAM->seekto($this->table_translations[$i * 2 + 2]);
    157         $translation = $this->STREAM->read($this->table_translations[$i * 2 + 1]);
    158         $this->cache_translations[$original] = $translation;
    159       }
    160     }
    161   }
    162  
    163   /**
    164    * Returns a string from the "originals" table
    165    *
    166    * @access private
    167    * @param int num Offset number of original string
    168    * @return string Requested string if found, otherwise ''
    169    */
    170   function get_original_string($num) {
    171     $length = $this->table_originals[$num * 2 + 1];
    172     $offset = $this->table_originals[$num * 2 + 2];
    173     if (! $length)
    174       return '';
    175     $this->STREAM->seekto($offset);
    176     $data = $this->STREAM->read($length);
    177     return (string)$data;
    178   }
    179  
    180   /**
    181    * Returns a string from the "translations" table
    182    *
    183    * @access private
    184    * @param int num Offset number of original string
    185    * @return string Requested string if found, otherwise ''
    186    */
    187   function get_translation_string($num) {
    188     $length = $this->table_translations[$num * 2 + 1];
    189     $offset = $this->table_translations[$num * 2 + 2];
    190     if (! $length)
    191       return '';
    192     $this->STREAM->seekto($offset);
    193     $data = $this->STREAM->read($length);
    194     return (string)$data;
    195   }
    196  
    197   /**
    198    * Binary search for string
    199    *
    200    * @access private
    201    * @param string string
    202    * @param int start (internally used in recursive function)
    203    * @param int end (internally used in recursive function)
    204    * @return int string number (offset in originals table)
    205    */
    206   function find_string($string, $start = -1, $end = -1) {
    207     if (($start == -1) or ($end == -1)) {
    208       // find_string is called with only one parameter, set start end end
    209       $start = 0;
    210       $end = $this->total;
    211     }
    212     if (abs($start - $end) <= 1) {
    213       // We're done, now we either found the string, or it doesn't exist
    214       $txt = $this->get_original_string($start);
    215       if ($string == $txt)
    216         return $start;
    217       else
    218         return -1;
    219     } else if ($start > $end) {
    220       // start > end -> turn around and start over
    221       return $this->find_string($string, $end, $start);
    222     } else {
    223       // Divide table in two parts
    224       $half = (int)(($start + $end) / 2);
    225       $cmp = strcmp($string, $this->get_original_string($half));
    226       if ($cmp == 0)
    227         // string is exactly in the middle => return it
    228         return $half;
    229       else if ($cmp < 0)
    230         // The string is in the upper half
    231         return $this->find_string($string, $start, $half);
    232       else
    233         // The string is in the lower half
    234         return $this->find_string($string, $half, $end);
    235     }
    236   }
    237  
    238   /**
    239    * Translates a string
    240    *
    241    * @access public
    242    * @param string string to be translated
    243    * @return string translated string (or original, if not found)
    244    */
    245   function translate($string) {
    246     if ($this->short_circuit)
    247       return $string;
    248     $this->load_tables();     
    249    
    250     if ($this->enable_cache) {
    251       // Caching enabled, get translated string from cache
    252       if (array_key_exists($string, $this->cache_translations))
    253         return $this->cache_translations[$string];
    254       else
    255         return $string;
    256     } else {
    257       // Caching not enabled, try to find string
    258       $num = $this->find_string($string);
    259       if ($num == -1)
    260         return $string;
    261       else
    262         return $this->get_translation_string($num);
    263     }
    264   }
    265 
    266   /**
    267    * Get possible plural forms from MO header
    268    *
    269    * @access private
    270    * @return string plural form header
    271    */
    272   function get_plural_forms() {
    273     // lets assume message number 0 is header 
    274     // this is true, right?
    275     $this->load_tables();
    276    
    277     // cache header field for plural forms
    278     if (! is_string($this->pluralheader)) {
    279       if ($this->enable_cache) {
    280         $header = $this->cache_translations[""];
    281       } else {
    282         $header = $this->get_translation_string(0);
    283       }
    284       if (eregi("plural-forms: ([^\n]*)\n", $header, $regs))
    285         $expr = $regs[1];
    286       else
    287         $expr = "nplurals=2; plural=n == 1 ? 0 : 1;";
    288       $this->pluralheader = $expr;
    289     }
    290     return $this->pluralheader;
    291   }
    292 
    293   /**
    294    * Detects which plural form to take
    295    *
    296    * @access private
    297    * @param n count
    298    * @return int array index of the right plural form
    299    */
    300   function select_string($n) {
    301     $string = $this->get_plural_forms();
    302     $string = str_replace('nplurals',"\$total",$string);
    303     $string = str_replace("n",$n,$string);
    304     $string = str_replace('plural',"\$plural",$string);
    305 
    306     # poEdit doesn't put any semicolons, which
    307     # results in parse error in eval
    308     $string .= ';';
    309    
    310     $total = 0;
    311     $plural = 0;
    312 
    313     eval("$string");
    314     if ($plural >= $total) $plural = $total - 1;
    315     return $plural;
    316   }
    317 
    318   /**
    319    * Plural version of gettext
    320    *
    321    * @access public
    322    * @param string single
    323    * @param string plural
    324    * @param string number
    325    * @return translated plural form
    326    */
    327   function ngettext($single, $plural, $number) {
    328     if ($this->short_circuit) {
    329       if ($number != 1)
    330         return $plural;
    331       else
    332         return $single;
    333     }
    334 
    335     // find out the appropriate form
    336     $select = $this->select_string($number);
    337    
    338     // this should contains all strings separated by NULLs
    339     $key = $single.chr(0).$plural;
    340    
    341    
    342     if ($this->enable_cache) {
    343       if (! array_key_exists($key, $this->cache_translations)) {
    344         return ($number != 1) ? $plural : $single;
    345       } else {
    346         $result = $this->cache_translations[$key];
    347         $list = explode(chr(0), $result);
    348         return $list[$select];
    349       }
    350     } else {
    351       $num = $this->find_string($key);
    352       if ($num == -1) {
    353         return ($number != 1) ? $plural : $single;
    354       } else {
    355         $result = $this->get_translation_string($num);
    356         $list = explode(chr(0), $result);
    357         return $list[$select];
    358       }
    359     }
    360   }
     37    //public:
     38     var $error = 0; // public variable that holds error code (0 if no error)
     39
     40     //private:
     41    var $BYTEORDER = 0;        // 0: low endian, 1: big endian
     42    var $STREAM = NULL;
     43    var $short_circuit = false;
     44    var $enable_cache = false;
     45    var $originals = NULL;      // offset of original table
     46    var $translations = NULL;    // offset of translation table
     47    var $pluralheader = NULL;    // cache header field for plural forms
     48    var $select_string_function = NULL; // cache function, which chooses plural forms
     49    var $total = 0;          // total string count
     50    var $table_originals = NULL;  // table for original strings (offsets)
     51    var $table_translations = NULL;  // table for translated strings (offsets)
     52    var $cache_translations = NULL;  // original -> translation mapping
     53
     54
     55    /* Methods */
     56
     57
     58    /**
     59     * Reads a 32bit Integer from the Stream
     60     *
     61     * @access private
     62     * @return Integer from the Stream
     63     */
     64    function readint() {
     65        if ($this->BYTEORDER == 0) {
     66            // low endian
     67            $low_end = unpack('V', $this->STREAM->read(4));
     68            return array_shift($low_end);
     69        } else {
     70            // big endian
     71            $big_end = unpack('N', $this->STREAM->read(4));
     72            return array_shift($big_end);
     73        }
     74    }
     75
     76    /**
     77     * Reads an array of Integers from the Stream
     78     *
     79     * @param int count How many elements should be read
     80     * @return Array of Integers
     81     */
     82    function readintarray($count) {
     83    if ($this->BYTEORDER == 0) {
     84            // low endian
     85            return unpack('V'.$count, $this->STREAM->read(4 * $count));
     86        } else {
     87            // big endian
     88            return unpack('N'.$count, $this->STREAM->read(4 * $count));
     89        }
     90    }
     91
     92    /**
     93     * Constructor
     94     *
     95     * @param object Reader the StreamReader object
     96     * @param boolean enable_cache Enable or disable caching of strings (default on)
     97     */
     98    function gettext_reader($Reader, $enable_cache = true) {
     99        // If there isn't a StreamReader, turn on short circuit mode.
     100        if (! $Reader || isset($Reader->error) ) {
     101            $this->short_circuit = true;
     102            return;
     103        }
     104
     105        // Caching can be turned off
     106        $this->enable_cache = $enable_cache;
     107
     108        // $MAGIC1 = (int)0x950412de; //bug in PHP 5.0.2, see https://savannah.nongnu.org/bugs/?func=detailitem&item_id=10565
     109        $MAGIC1 = (int) - 1794895138;
     110        // $MAGIC2 = (int)0xde120495; //bug
     111        $MAGIC2 = (int) - 569244523;
     112        // 64-bit fix
     113        $MAGIC3 = (int) 2500072158;
     114
     115        $this->STREAM = $Reader;
     116        $magic = $this->readint();
     117        if ($magic == ($MAGIC1 & 0xFFFFFFFF) || $magic == ($MAGIC3 & 0xFFFFFFFF)) { // to make sure it works for 64-bit platforms
     118            $this->BYTEORDER = 0;
     119        } elseif ($magic == ($MAGIC2 & 0xFFFFFFFF)) {
     120            $this->BYTEORDER = 1;
     121        } else {
     122            $this->error = 1; // not MO file
     123            return false;
     124        }
     125
     126        // FIXME: Do we care about revision? We should.
     127        $revision = $this->readint();
     128
     129        $this->total = $this->readint();
     130        $this->originals = $this->readint();
     131        $this->translations = $this->readint();
     132    }
     133
     134    /**
     135     * Loads the translation tables from the MO file into the cache
     136     * If caching is enabled, also loads all strings into a cache
     137     * to speed up translation lookups
     138     *
     139     * @access private
     140     */
     141    function load_tables() {
     142        if (is_array($this->cache_translations) &&
     143            is_array($this->table_originals) &&
     144            is_array($this->table_translations))
     145            return;
     146
     147        /* get original and translations tables */
     148        $this->STREAM->seekto($this->originals);
     149        $this->table_originals = $this->readintarray($this->total * 2);
     150        $this->STREAM->seekto($this->translations);
     151        $this->table_translations = $this->readintarray($this->total * 2);
     152
     153        if ($this->enable_cache) {
     154            $this->cache_translations = array ();
     155            /* read all strings in the cache */
     156            for ($i = 0; $i < $this->total; $i++) {
     157                $this->STREAM->seekto($this->table_originals[$i * 2 + 2]);
     158                $original = $this->STREAM->read($this->table_originals[$i * 2 + 1]);
     159                $this->STREAM->seekto($this->table_translations[$i * 2 + 2]);
     160                $translation = $this->STREAM->read($this->table_translations[$i * 2 + 1]);
     161                $this->cache_translations[$original] = $translation;
     162            }
     163        }
     164    }
     165
     166    /**
     167     * Returns a string from the "originals" table
     168     *
     169     * @access private
     170     * @param int num Offset number of original string
     171     * @return string Requested string if found, otherwise ''
     172     */
     173    function get_original_string($num) {
     174        $length = $this->table_originals[$num * 2 + 1];
     175        $offset = $this->table_originals[$num * 2 + 2];
     176        if (! $length)
     177            return '';
     178        $this->STREAM->seekto($offset);
     179        $data = $this->STREAM->read($length);
     180        return (string)$data;
     181    }
     182
     183    /**
     184     * Returns a string from the "translations" table
     185     *
     186     * @access private
     187     * @param int num Offset number of original string
     188     * @return string Requested string if found, otherwise ''
     189     */
     190    function get_translation_string($num) {
     191        $length = $this->table_translations[$num * 2 + 1];
     192        $offset = $this->table_translations[$num * 2 + 2];
     193        if (! $length)
     194            return '';
     195        $this->STREAM->seekto($offset);
     196        $data = $this->STREAM->read($length);
     197        return (string)$data;
     198    }
     199
     200    /**
     201     * Binary search for string
     202     *
     203     * @access private
     204     * @param string string
     205     * @param int start (internally used in recursive function)
     206     * @param int end (internally used in recursive function)
     207     * @return int string number (offset in originals table)
     208     */
     209    function find_string($string, $start = -1, $end = -1) {
     210        if (($start == -1) or ($end == -1)) {
     211            // find_string is called with only one parameter, set start end end
     212            $start = 0;
     213            $end = $this->total;
     214        }
     215        if (abs($start - $end) <= 1) {
     216            // We're done, now we either found the string, or it doesn't exist
     217            $txt = $this->get_original_string($start);
     218            if ($string == $txt)
     219                return $start;
     220            else
     221                return -1;
     222        } else if ($start > $end) {
     223            // start > end -> turn around and start over
     224            return $this->find_string($string, $end, $start);
     225        } else {
     226            // Divide table in two parts
     227            $half = (int)(($start + $end) / 2);
     228            $cmp = strcmp($string, $this->get_original_string($half));
     229            if ($cmp == 0)
     230                // string is exactly in the middle => return it
     231                return $half;
     232            else if ($cmp < 0)
     233                // The string is in the upper half
     234                return $this->find_string($string, $start, $half);
     235            else
     236                // The string is in the lower half
     237                return $this->find_string($string, $half, $end);
     238        }
     239    }
     240
     241    /**
     242     * Translates a string
     243     *
     244     * @access public
     245     * @param string string to be translated
     246     * @return string translated string (or original, if not found)
     247     */
     248    function translate($string) {
     249        if ($this->short_circuit)
     250            return $string;
     251        $this->load_tables();
     252
     253        if ($this->enable_cache) {
     254            // Caching enabled, get translated string from cache
     255            if (array_key_exists($string, $this->cache_translations))
     256                return $this->cache_translations[$string];
     257            else
     258                return $string;
     259        } else {
     260            // Caching not enabled, try to find string
     261            $num = $this->find_string($string);
     262            if ($num == -1)
     263                return $string;
     264            else
     265                return $this->get_translation_string($num);
     266        }
     267    }
     268
     269    /**
     270     * Get possible plural forms from MO header
     271     *
     272     * @access private
     273     * @return string plural form header
     274     */
     275    function get_plural_forms() {
     276        // lets assume message number 0 is header
     277        // this is true, right?
     278        $this->load_tables();
     279
     280        // cache header field for plural forms
     281        if (! is_string($this->pluralheader)) {
     282            if ($this->enable_cache) {
     283                $header = $this->cache_translations[""];
     284            } else {
     285                $header = $this->get_translation_string(0);
     286            }
     287            $header .= "\n"; //make sure our regex matches
     288            if (eregi("plural-forms: ([^\n]*)\n", $header, $regs))
     289                $expr = $regs[1];
     290            else
     291                $expr = "nplurals=2; plural=n == 1 ? 0 : 1;";
     292
     293            // add parentheses
     294            // important since PHP's ternary evaluates from left to right
     295            $expr.= ';';
     296            $res= '';
     297            $p= 0;
     298            for ($i= 0; $i < strlen($expr); $i++) {
     299                $ch= $expr[$i];
     300                switch ($ch) {
     301                    case '?':
     302                        $res.= ' ? (';
     303                        $p++;
     304                        break;
     305                    case ':':
     306                        $res.= ') : (';
     307                        break;
     308                    case ';':
     309                        $res.= str_repeat( ')', $p) . ';';
     310                        $p= 0;
     311                        break;
     312                    default:
     313                        $res.= $ch;
     314                }
     315            }
     316            $this->pluralheader = $res;
     317        }
     318
     319        return $this->pluralheader;
     320    }
     321
     322    /**
     323     * Detects which plural form to take
     324     *
     325     * @access private
     326     * @param n count
     327     * @return int array index of the right plural form
     328     */
     329    function select_string($n) {
     330        if (is_null($this->select_string_function)) {
     331            $string = $this->get_plural_forms();
     332            if (preg_match("/nplurals\s*=\s*(\d+)\s*\;\s*plural\s*=\s*(.*?)\;+/", $string, $matches)) {
     333                $nplurals = $matches[1];
     334                $expression = $matches[2];
     335                $expression = str_replace("n", '$n', $expression);
     336            } else {
     337                $nplurals = 2;
     338                $expression = ' $n == 1 ? 0 : 1 ';
     339            }
     340            $func_body = "
     341                \$plural = ($expression);
     342                return (\$plural <= $nplurals)? \$plural : \$plural - 1;";
     343            $this->select_string_function = create_function('$n', $func_body);
     344        }
     345        return call_user_func($this->select_string_function, $n);
     346    }
     347
     348    /**
     349     * Plural version of gettext
     350     *
     351     * @access public
     352     * @param string single
     353     * @param string plural
     354     * @param string number
     355     * @return translated plural form
     356     */
     357    function ngettext($single, $plural, $number) {
     358        if ($this->short_circuit) {
     359            if ($number != 1)
     360                return $plural;
     361            else
     362                return $single;
     363        }
     364
     365        // find out the appropriate form
     366        $select = $this->select_string($number);
     367
     368        // this should contains all strings separated by NULLs
     369        $key = $single.chr(0).$plural;
     370
     371
     372        if ($this->enable_cache) {
     373            if (! array_key_exists($key, $this->cache_translations)) {
     374                return ($number != 1) ? $plural : $single;
     375            } else {
     376                $result = $this->cache_translations[$key];
     377                $list = explode(chr(0), $result);
     378                return $list[$select];
     379            }
     380        } else {
     381            $num = $this->find_string($key);
     382            if ($num == -1) {
     383                return ($number != 1) ? $plural : $single;
     384            } else {
     385                $result = $this->get_translation_string($num);
     386                $list = explode(chr(0), $result);
     387                return $list[$select];
     388            }
     389        }
     390    }
    361391
    362392}
  • tags/2.2/wp-includes/js/crop/cropper.js

    • Property svn:eol-style set to native
  • tags/2.2/wp-includes/js/prototype.js

    • Property svn:eol-style set to native
    r5468 r5480  
    1 /*  Prototype JavaScript framework, version 1.5.0_rc0
    2  *  (c) 2005 Sam Stephenson <sam@conio.net>
     1/*  Prototype JavaScript framework, version 1.5.0
     2 *  (c) 2005-2007 Sam Stephenson
    33 *
    44 *  Prototype is freely distributable under the terms of an MIT-style license.
     
    88
    99var Prototype = {
    10   Version: '1.5.0_rc0',
     10  Version: '1.5.0',
     11  BrowserFeatures: {
     12    XPath: !!document.evaluate
     13  },
     14
    1115  ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',
    12 
    1316  emptyFunction: function() {},
    14   K: function(x) {return x}
     17  K: function(x) { return x }
    1518}
    1619
     
    3235}
    3336
    34 Object.inspect = function(object) {
    35   try {
    36     if (object == undefined) return 'undefined';
    37     if (object == null) return 'null';
    38     return object.inspect ? object.inspect() : object.toString();
    39   } catch (e) {
    40     if (e instanceof RangeError) return '...';
    41     throw e;
    42   }
    43 }
     37Object.extend(Object, {
     38  inspect: function(object) {
     39    try {
     40      if (object === undefined) return 'undefined';
     41      if (object === null) return 'null';
     42      return object.inspect ? object.inspect() : object.toString();
     43    } catch (e) {
     44      if (e instanceof RangeError) return '...';
     45      throw e;
     46    }
     47  },
     48
     49  keys: function(object) {
     50    var keys = [];
     51    for (var property in object)
     52      keys.push(property);
     53    return keys;
     54  },
     55
     56  values: function(object) {
     57    var values = [];
     58    for (var property in object)
     59      values.push(object[property]);
     60    return values;
     61  },
     62
     63  clone: function(object) {
     64    return Object.extend({}, object);
     65  }
     66});
    4467
    4568Function.prototype.bind = function() {
     
    5174
    5275Function.prototype.bindAsEventListener = function(object) {
    53   var __method = this;
     76  var __method = this, args = $A(arguments), object = args.shift();
    5477  return function(event) {
    55     return __method.call(object, event || window.event);
     78    return __method.apply(object, [( event || window.event)].concat(args).concat($A(arguments)));
    5679  }
    5780}
     
    78101    var returnValue;
    79102
    80     for (var i = 0; i < arguments.length; i++) {
     103    for (var i = 0, length = arguments.length; i < length; i++) {
    81104      var lambda = arguments[i];
    82105      try {
     
    103126
    104127  registerCallback: function() {
    105     setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
     128    this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
     129  },
     130
     131  stop: function() {
     132    if (!this.timer) return;
     133    clearInterval(this.timer);
     134    this.timer = null;
    106135  },
    107136
     
    110139      try {
    111140        this.currentlyExecuting = true;
    112         this.callback();
     141        this.callback(this);
    113142      } finally {
    114143        this.currentlyExecuting = false;
     
    117146  }
    118147}
     148String.interpret = function(value){
     149  return value == null ? '' : String(value);
     150}
     151
    119152Object.extend(String.prototype, {
    120153  gsub: function(pattern, replacement) {
     
    125158      if (match = source.match(pattern)) {
    126159        result += source.slice(0, match.index);
    127         result += (replacement(match) || '').toString();
     160        result += String.interpret(replacement(match));
    128161        source  = source.slice(match.index + match[0].length);
    129162      } else {
     
    190223    var div = document.createElement('div');
    191224    div.innerHTML = this.stripTags();
    192     return div.childNodes[0] ? div.childNodes[0].nodeValue : '';
    193   },
    194 
    195   toQueryParams: function() {
    196     var pairs = this.match(/^\??(.*)$/)[1].split('&');
    197     return pairs.inject({}, function(params, pairString) {
    198       var pair = pairString.split('=');
    199       params[pair[0]] = pair[1];
    200       return params;
     225    return div.childNodes[0] ? (div.childNodes.length > 1 ?
     226      $A(div.childNodes).inject('',function(memo,node){ return memo+node.nodeValue }) :
     227      div.childNodes[0].nodeValue) : '';
     228  },
     229
     230  toQueryParams: function(separator) {
     231    var match = this.strip().match(/([^?#]*)(#.*)?$/);
     232    if (!match) return {};
     233
     234    return match[1].split(separator || '&').inject({}, function(hash, pair) {
     235      if ((pair = pair.split('='))[0]) {
     236        var name = decodeURIComponent(pair[0]);
     237        var value = pair[1] ? decodeURIComponent(pair[1]) : undefined;
     238
     239        if (hash[name] !== undefined) {
     240          if (hash[name].constructor != Array)
     241            hash[name] = [hash[name]];
     242          if (value) hash[name].push(value);
     243        }
     244        else hash[name] = value;
     245      }
     246      return hash;
    201247    });
    202248  },
     
    206252  },
    207253
     254  succ: function() {
     255    return this.slice(0, this.length - 1) +
     256      String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
     257  },
     258
    208259  camelize: function() {
    209     var oStringList = this.split('-');
    210     if (oStringList.length == 1) return oStringList[0];
    211 
    212     var camelizedString = this.indexOf('-') == 0
    213       ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1)
    214       : oStringList[0];
    215 
    216     for (var i = 1, len = oStringList.length; i < len; i++) {
    217       var s = oStringList[i];
    218       camelizedString += s.charAt(0).toUpperCase() + s.substring(1);
    219     }
    220 
    221     return camelizedString;
    222   },
    223 
    224   inspect: function() {
    225     return "'" + this.replace(/\\/g, '\\\\').replace(/'/g, '\\\'') + "'";
     260    var parts = this.split('-'), len = parts.length;
     261    if (len == 1) return parts[0];
     262
     263    var camelized = this.charAt(0) == '-'
     264      ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
     265      : parts[0];
     266
     267    for (var i = 1; i < len; i++)
     268      camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
     269
     270    return camelized;
     271  },
     272
     273  capitalize: function(){
     274    return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
     275  },
     276
     277  underscore: function() {
     278    return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
     279  },
     280
     281  dasherize: function() {
     282    return this.gsub(/_/,'-');
     283  },
     284
     285  inspect: function(useDoubleQuotes) {
     286    var escapedString = this.replace(/\\/g, '\\\\');
     287    if (useDoubleQuotes)
     288      return '"' + escapedString.replace(/"/g, '\\"') + '"';
     289    else
     290      return "'" + escapedString.replace(/'/g, '\\\'') + "'";
    226291  }
    227292});
     
    247312      var before = match[1];
    248313      if (before == '\\') return match[2];
    249       return before + (object[match[3]] || '').toString();
     314      return before + String.interpret(object[match[3]]);
    250315    });
    251316  }
     
    269334      if (e != $break) throw e;
    270335    }
     336    return this;
     337  },
     338
     339  eachSlice: function(number, iterator) {
     340    var index = -number, slices = [], array = this.toArray();
     341    while ((index += number) < array.length)
     342      slices.push(array.slice(index, index+number));
     343    return slices.map(iterator);
    271344  },
    272345
     
    281354
    282355  any: function(iterator) {
    283     var result = true;
     356    var result = false;
    284357    this.each(function(value, index) {
    285358      if (result = !!(iterator || Prototype.K)(value, index))
     
    292365    var results = [];
    293366    this.each(function(value, index) {
    294       results.push(iterator(value, index));
     367      results.push((iterator || Prototype.K)(value, index));
    295368    });
    296369    return results;
    297370  },
    298371
    299   detect: function (iterator) {
     372  detect: function(iterator) {
    300373    var result;
    301374    this.each(function(value, index) {
     
    338411  },
    339412
     413  inGroupsOf: function(number, fillWith) {
     414    fillWith = fillWith === undefined ? null : fillWith;
     415    return this.eachSlice(number, function(slice) {
     416      while(slice.length < number) slice.push(fillWith);
     417      return slice;
     418    });
     419  },
     420
    340421  inject: function(memo, iterator) {
    341422    this.each(function(value, index) {
     
    347428  invoke: function(method) {
    348429    var args = $A(arguments).slice(1);
    349     return this.collect(function(value) {
     430    return this.map(function(value) {
    350431      return value[method].apply(value, args);
    351432    });
     
    399480
    400481  sortBy: function(iterator) {
    401     return this.collect(function(value, index) {
     482    return this.map(function(value, index) {
    402483      return {value: value, criteria: iterator(value, index)};
    403484    }).sort(function(left, right) {
     
    408489
    409490  toArray: function() {
    410     return this.collect(Prototype.K);
     491    return this.map();
    411492  },
    412493
     
    420501      return iterator(collections.pluck(index));
    421502    });
     503  },
     504
     505  size: function() {
     506    return this.toArray().length;
    422507  },
    423508
     
    440525  } else {
    441526    var results = [];
    442     for (var i = 0; i < iterable.length; i++)
     527    for (var i = 0, length = iterable.length; i < length; i++)
    443528      results.push(iterable[i]);
    444529    return results;
     
    453538Object.extend(Array.prototype, {
    454539  _each: function(iterator) {
    455     for (var i = 0; i < this.length; i++)
     540    for (var i = 0, length = this.length; i < length; i++)
    456541      iterator(this[i]);
    457542  },
     
    472557  compact: function() {
    473558    return this.select(function(value) {
    474       return value != undefined || value != null;
     559      return value != null;
    475560    });
    476561  },
     
    491576
    492577  indexOf: function(object) {
    493     for (var i = 0; i < this.length; i++)
     578    for (var i = 0, length = this.length; i < length; i++)
    494579      if (this[i] == object) return i;
    495580    return -1;
     
    500585  },
    501586
     587  reduce: function() {
     588    return this.length > 1 ? this : this[0];
     589  },
     590
     591  uniq: function() {
     592    return this.inject([], function(array, value) {
     593      return array.include(value) ? array : array.concat([value]);
     594    });
     595  },
     596
     597  clone: function() {
     598    return [].concat(this);
     599  },
     600
     601  size: function() {
     602    return this.length;
     603  },
     604
    502605  inspect: function() {
    503606    return '[' + this.map(Object.inspect).join(', ') + ']';
    504607  }
    505608});
    506 var Hash = {
     609
     610Array.prototype.toArray = Array.prototype.clone;
     611
     612function $w(string){
     613  string = string.strip();
     614  return string ? string.split(/\s+/) : [];
     615}
     616
     617if(window.opera){
     618  Array.prototype.concat = function(){
     619    var array = [];
     620    for(var i = 0, length = this.length; i < length; i++) array.push(this[i]);
     621    for(var i = 0, length = arguments.length; i < length; i++) {
     622      if(arguments[i].constructor == Array) {
     623        for(var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
     624          array.push(arguments[i][j]);
     625      } else {
     626        array.push(arguments[i]);
     627      }
     628    }
     629    return array;
     630  }
     631}
     632var Hash = function(obj) {
     633  Object.extend(this, obj || {});
     634};
     635
     636Object.extend(Hash, {
     637  toQueryString: function(obj) {
     638    var parts = [];
     639
     640      this.prototype._each.call(obj, function(pair) {
     641      if (!pair.key) return;
     642
     643      if (pair.value && pair.value.constructor == Array) {
     644        var values = pair.value.compact();
     645        if (values.length < 2) pair.value = values.reduce();
     646        else {
     647            key = encodeURIComponent(pair.key);
     648          values.each(function(value) {
     649            value = value != undefined ? encodeURIComponent(value) : '';
     650            parts.push(key + '=' + encodeURIComponent(value));
     651          });
     652          return;
     653        }
     654      }
     655      if (pair.value == undefined) pair[1] = '';
     656      parts.push(pair.map(encodeURIComponent).join('='));
     657      });
     658
     659    return parts.join('&');
     660  }
     661});
     662
     663Object.extend(Hash.prototype, Enumerable);
     664Object.extend(Hash.prototype, {
    507665  _each: function(iterator) {
    508666    for (var key in this) {
    509667      var value = this[key];
    510       if (typeof value == 'function') continue;
     668      if (value && value == Hash.prototype[key]) continue;
    511669
    512670      var pair = [key, value];
     
    526684
    527685  merge: function(hash) {
    528     return $H(hash).inject($H(this), function(mergedHash, pair) {
     686    return $H(hash).inject(this, function(mergedHash, pair) {
    529687      mergedHash[pair.key] = pair.value;
    530688      return mergedHash;
     
    532690  },
    533691
     692  remove: function() {
     693    var result;
     694    for(var i = 0, length = arguments.length; i < length; i++) {
     695      var value = this[arguments[i]];
     696      if (value !== undefined){
     697        if (result === undefined) result = value;
     698        else {
     699          if (result.constructor != Array) result = [result];
     700          result.push(value)
     701        }
     702      }
     703      delete this[arguments[i]];
     704    }
     705    return result;
     706  },
     707
    534708  toQueryString: function() {
    535     return this.map(function(pair) {
    536       return pair.map(encodeURIComponent).join('=');
    537     }).join('&');
     709    return Hash.toQueryString(this);
    538710  },
    539711
     
    543715    }).join(', ') + '}>';
    544716  }
    545 }
     717});
    546718
    547719function $H(object) {
    548   var hash = Object.extend({}, object || {});
    549   Object.extend(hash, Enumerable);
    550   Object.extend(hash, Hash);
    551   return hash;
    552 }
     720  if (object && object.constructor == Hash) return object;
     721  return new Hash(object);
     722};
    553723ObjectRange = Class.create();
    554724Object.extend(ObjectRange.prototype, Enumerable);
     
    562732  _each: function(iterator) {
    563733    var value = this.start;
    564     do {
     734    while (this.include(value)) {
    565735      iterator(value);
    566736      value = value.succ();
    567     } while (this.include(value));
     737    }
    568738  },
    569739
     
    600770  },
    601771
    602   register: function(responderToAdd) {
    603     if (!this.include(responderToAdd))
    604       this.responders.push(responderToAdd);
    605   },
    606 
    607   unregister: function(responderToRemove) {
    608     this.responders = this.responders.without(responderToRemove);
     772  register: function(responder) {
     773    if (!this.include(responder))
     774      this.responders.push(responder);
     775  },
     776
     777  unregister: function(responder) {
     778    this.responders = this.responders.without(responder);
    609779  },
    610780
    611781  dispatch: function(callback, request, transport, json) {
    612782    this.each(function(responder) {
    613       if (responder[callback] && typeof responder[callback] == 'function') {
     783      if (typeof responder[callback] == 'function') {
    614784        try {
    615785          responder[callback].apply(responder, [request, transport, json]);
     
    626796    Ajax.activeRequestCount++;
    627797  },
    628 
    629798  onComplete: function() {
    630799    Ajax.activeRequestCount--;
     
    639808      asynchronous: true,
    640809      contentType:  'application/x-www-form-urlencoded',
     810      encoding:     'UTF-8',
    641811      parameters:   ''
    642812    }
    643813    Object.extend(this.options, options || {});
    644   },
    645 
    646   responseIsSuccess: function() {
    647     return this.transport.status == undefined
    648         || this.transport.status == 0
    649         || (this.transport.status >= 200 && this.transport.status < 300);
    650   },
    651 
    652   responseIsFailure: function() {
    653     return !this.responseIsSuccess();
     814
     815    this.options.method = this.options.method.toLowerCase();
     816    if (typeof this.options.parameters == 'string')
     817      this.options.parameters = this.options.parameters.toQueryParams();
    654818  }
    655819}
     
    660824
    661825Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
     826  _complete: false,
     827
    662828  initialize: function(url, options) {
    663829    this.transport = Ajax.getTransport();
     
    667833
    668834  request: function(url) {
    669     var parameters = this.options.parameters || '';
    670     if (parameters.length > 0) parameters += '&_=';
     835    this.url = url;
     836    this.method = this.options.method;
     837    var params = this.options.parameters;
     838
     839    if (!['get', 'post'].include(this.method)) {
     840      // simulate other verbs over post
     841      params['_method'] = this.method;
     842      this.method = 'post';
     843    }
     844
     845    params = Hash.toQueryString(params);
     846    if (params && /Konqueror|Safari|KHTML/.test(navigator.userAgent)) params += '&_='
     847
     848    // when GET, append parameters to URL
     849    if (this.method == 'get' && params)
     850      this.url += (this.url.indexOf('?') > -1 ? '&' : '?') + params;
    671851
    672852    try {
    673       this.url = url;
    674       if (this.options.method == 'get' && parameters.length > 0)
    675         this.url += (this.url.match(/\?/) ? '&' : '?') + parameters;
    676 
    677853      Ajax.Responders.dispatch('onCreate', this, this.transport);
    678854
    679       this.transport.open(this.options.method, this.url,
     855      this.transport.open(this.method.toUpperCase(), this.url,
    680856        this.options.asynchronous);
    681857
    682       if (this.options.asynchronous) {
    683         this.transport.onreadystatechange = this.onStateChange.bind(this);
    684         setTimeout((function() {this.respondToReadyState(1)}).bind(this), 10);
     858      if (this.options.asynchronous)
     859        setTimeout(function() { this.respondToReadyState(1) }.bind(this), 10);
     860
     861      this.transport.onreadystatechange = this.onStateChange.bind(this);
     862      this.setRequestHeaders();
     863
     864      var body = this.method == 'post' ? (this.options.postBody || params) : null;
     865
     866      this.transport.send(body);
     867
     868      /* Force Firefox to handle ready state 4 for synchronous requests */
     869      if (!this.options.asynchronous && this.transport.overrideMimeType)
     870        this.onStateChange();
     871
     872    }
     873    catch (e) {
     874      this.dispatchException(e);
     875    }
     876  },
     877
     878  onStateChange: function() {
     879    var readyState = this.transport.readyState;
     880    if (readyState > 1 && !((readyState == 4) && this._complete))
     881      this.respondToReadyState(this.transport.readyState);
     882  },
     883
     884  setRequestHeaders: function() {
     885    var headers = {
     886      'X-Requested-With': 'XMLHttpRequest',
     887      'X-Prototype-Version': Prototype.Version,
     888      'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
     889    };
     890
     891    if (this.method == 'post') {
     892      headers['Content-type'] = this.options.contentType +
     893        (this.options.encoding ? '; charset=' + this.options.encoding : '');
     894
     895      /* Force "Connection: close" for older Mozilla browsers to work
     896       * around a bug where XMLHttpRequest sends an incorrect
     897       * Content-length header. See Mozilla Bugzilla #246651.
     898       */
     899      if (this.transport.overrideMimeType &&
     900          (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
     901            headers['Connection'] = 'close';
     902    }
     903
     904    // user-defined headers
     905    if (typeof this.options.requestHeaders == 'object') {
     906      var extras = this.options.requestHeaders;
     907
     908      if (typeof extras.push == 'function')
     909        for (var i = 0, length = extras.length; i < length; i += 2)
     910          headers[extras[i]] = extras[i+1];
     911      else
     912        $H(extras).each(function(pair) { headers[pair.key] = pair.value });
     913    }
     914
     915    for (var name in headers)
     916      this.transport.setRequestHeader(name, headers[name]);
     917  },
     918
     919  success: function() {
     920    return !this.transport.status
     921        || (this.transport.status >= 200 && this.transport.status < 300);
     922  },
     923
     924  respondToReadyState: function(readyState) {
     925    var state = Ajax.Request.Events[readyState];
     926    var transport = this.transport, json = this.evalJSON();
     927
     928    if (state == 'Complete') {
     929      try {
     930        this._complete = true;
     931        (this.options['on' + this.transport.status]
     932         || this.options['on' + (this.success() ? 'Success' : 'Failure')]
     933         || Prototype.emptyFunction)(transport, json);
     934      } catch (e) {
     935        this.dispatchException(e);
    685936      }
    686937
    687       this.setRequestHeaders();
    688 
    689       var body = this.options.postBody ? this.options.postBody : parameters;
    690       this.transport.send(this.options.method == 'post' ? body : null);
    691 
     938      if ((this.getHeader('Content-type') || 'text/javascript').strip().
     939        match(/^(text|application)\/(x-)?(java|ecma)script(;.*)?$/i))
     940          this.evalResponse();
     941    }
     942
     943    try {
     944      (this.options['on' + state] || Prototype.emptyFunction)(transport, json);
     945      Ajax.Responders.dispatch('on' + state, this, transport, json);
    692946    } catch (e) {
    693947      this.dispatchException(e);
    694948    }
    695   },
    696 
    697   setRequestHeaders: function() {
    698     var requestHeaders =
    699       ['X-Requested-With', 'XMLHttpRequest',
    700        'X-Prototype-Version', Prototype.Version,
    701        'Accept', 'text/javascript, text/html, application/xml, text/xml, */*'];
    702 
    703     if (this.options.method == 'post') {
    704       requestHeaders.push('Content-type', this.options.contentType);
    705 
    706       /* Force "Connection: close" for Mozilla browsers to work around
    707        * a bug where XMLHttpReqeuest sends an incorrect Content-length
    708        * header. See Mozilla Bugzilla #246651.
    709        */
    710       if (this.transport.overrideMimeType)
    711         requestHeaders.push('Connection', 'close');
    712     }
    713 
    714     if (this.options.requestHeaders)
    715       requestHeaders.push.apply(requestHeaders, this.options.requestHeaders);
    716 
    717     for (var i = 0; i < requestHeaders.length; i += 2)
    718       this.transport.setRequestHeader(requestHeaders[i], requestHeaders[i+1]);
    719   },
    720 
    721   onStateChange: function() {
    722     var readyState = this.transport.readyState;
    723     if (readyState != 1)
    724       this.respondToReadyState(this.transport.readyState);
    725   },
    726 
    727   header: function(name) {
     949
     950    if (state == 'Complete') {
     951      // avoid memory leak in MSIE: clean up
     952      this.transport.onreadystatechange = Prototype.emptyFunction;
     953    }
     954  },
     955
     956  getHeader: function(name) {
    728957    try {
    729958      return this.transport.getResponseHeader(name);
    730     } catch (e) {}
     959    } catch (e) { return null }
    731960  },
    732961
    733962  evalJSON: function() {
    734963    try {
    735       return eval('(' + this.header('X-JSON') + ')');
    736     } catch (e) {}
     964      var json = this.getHeader('X-JSON');
     965      return json ? eval('(' + json + ')') : null;
     966    } catch (e) { return null }
    737967  },
    738968
     
    745975  },
    746976
    747   respondToReadyState: function(readyState) {
    748     var event = Ajax.Request.Events[readyState];
    749     var transport = this.transport, json = this.evalJSON();
    750 
    751     if (event == 'Complete') {
    752       try {
    753         (this.options['on' + this.transport.status]
    754          || this.options['on' + (this.responseIsSuccess() ? 'Success' : 'Failure')]
    755          || Prototype.emptyFunction)(transport, json);
    756       } catch (e) {
    757         this.dispatchException(e);
    758       }
    759 
    760       if ((this.header('Content-type') || '').match(/^text\/javascript/i))
    761         this.evalResponse();
    762     }
    763 
    764     try {
    765       (this.options['on' + event] || Prototype.emptyFunction)(transport, json);
    766       Ajax.Responders.dispatch('on' + event, this, transport, json);
    767     } catch (e) {
    768       this.dispatchException(e);
    769     }
    770 
    771     /* Avoid memory leak in MSIE: clean up the oncomplete event handler */
    772     if (event == 'Complete')
    773       this.transport.onreadystatechange = Prototype.emptyFunction;
    774   },
    775 
    776977  dispatchException: function(exception) {
    777978    (this.options.onException || Prototype.emptyFunction)(this, exception);
     
    784985Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
    785986  initialize: function(container, url, options) {
    786     this.containers = {
    787       success: container.success ? $(container.success) : $(container),
    788       failure: container.failure ? $(container.failure) :
    789         (container.success ? null : $(container))
     987    this.container = {
     988      success: (container.success || container),
     989      failure: (container.failure || (container.success ? null : container))
    790990    }
    791991
     
    794994
    795995    var onComplete = this.options.onComplete || Prototype.emptyFunction;
    796     this.options.onComplete = (function(transport, object) {
     996    this.options.onComplete = (function(transport, param) {
    797997      this.updateContent();
    798       onComplete(transport, object);
     998      onComplete(transport, param);
    799999    }).bind(this);
    8001000
     
    8031003
    8041004  updateContent: function() {
    805     var receiver = this.responseIsSuccess() ?
    806       this.containers.success : this.containers.failure;
     1005    var receiver = this.container[this.success() ? 'success' : 'failure'];
    8071006    var response = this.transport.responseText;
    8081007
    809     if (!this.options.evalScripts)
    810       response = response.stripScripts();
    811 
    812     if (receiver) {
    813       if (this.options.insertion) {
     1008    if (!this.options.evalScripts) response = response.stripScripts();
     1009
     1010    if (receiver = $(receiver)) {
     1011      if (this.options.insertion)
    8141012        new this.options.insertion(receiver, response);
    815       } else {
    816         Element.update(receiver, response);
    817       }
    818     }
    819 
    820     if (this.responseIsSuccess()) {
     1013      else
     1014        receiver.update(response);
     1015    }
     1016
     1017    if (this.success()) {
    8211018      if (this.onComplete)
    8221019        setTimeout(this.onComplete.bind(this), 10);
     
    8471044
    8481045  stop: function() {
    849     this.updater.onComplete = undefined;
     1046    this.updater.options.onComplete = undefined;
    8501047    clearTimeout(this.timer);
    8511048    (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
     
    8671064  }
    8681065});
    869 function $() {
    870   var results = [], element;
    871   for (var i = 0; i < arguments.length; i++) {
    872     element = arguments[i];
    873     if (typeof element == 'string')
    874       element = document.getElementById(element);
    875     results.push(Element.extend(element));
    876   }
    877   return results.length < 2 ? results[0] : results;
     1066function $(element) {
     1067  if (arguments.length > 1) {
     1068    for (var i = 0, elements = [], length = arguments.length; i < length; i++)
     1069      elements.push($(arguments[i]));
     1070    return elements;
     1071  }
     1072  if (typeof element == 'string')
     1073    element = document.getElementById(element);
     1074  return Element.extend(element);
     1075}
     1076
     1077if (Prototype.BrowserFeatures.XPath) {
     1078  document._getElementsByXPath = function(expression, parentElement) {
     1079    var results = [];
     1080    var query = document.evaluate(expression, $(parentElement) || document,
     1081      null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
     1082    for (var i = 0, length = query.snapshotLength; i < length; i++)
     1083      results.push(query.snapshotItem(i));
     1084    return results;
     1085  };
    8781086}
    8791087
    8801088document.getElementsByClassName = function(className, parentElement) {
    881   var children = ($(parentElement) || document.body).getElementsByTagName('*');
    882   return $A(children).inject([], function(elements, child) {
    883     if (child.className.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
    884       elements.push(Element.extend(child));
     1089  if (Prototype.BrowserFeatures.XPath) {
     1090    var q = ".//*[contains(concat(' ', @class, ' '), ' " + className + " ')]";
     1091    return document._getElementsByXPath(q, parentElement);
     1092  } else {
     1093    var children = ($(parentElement) || document.body).getElementsByTagName('*');
     1094    var elements = [], child;
     1095    for (var i = 0, length = children.length; i < length; i++) {
     1096      child = children[i];
     1097      if (Element.hasClassName(child, className))
     1098        elements.push(Element.extend(child));
     1099    }
    8851100    return elements;
    886   });
    887 }
     1101  }
     1102};
    8881103
    8891104/*--------------------------------------------------------------------------*/
     
    8931108
    8941109Element.extend = function(element) {
    895   if (!element) return;
    896   if (_nativeExtensions) return element;
     1110  if (!element || _nativeExtensions || element.nodeType == 3) return element;
    8971111
    8981112  if (!element._extended && element.tagName && element != window) {
    899     var methods = Element.Methods, cache = Element.extend.cache;
    900     for (property in methods) {
     1113    var methods = Object.clone(Element.Methods), cache = Element.extend.cache;
     1114
     1115    if (element.tagName == 'FORM')
     1116      Object.extend(methods, Form.Methods);
     1117    if (['INPUT', 'TEXTAREA', 'SELECT'].include(element.tagName))
     1118      Object.extend(methods, Form.Element.Methods);
     1119
     1120    Object.extend(methods, Element.Methods.Simulated);
     1121
     1122    for (var property in methods) {
    9011123      var value = methods[property];
    902       if (typeof value == 'function')
     1124      if (typeof value == 'function' && !(property in element))
    9031125        element[property] = cache.findOrStore(value);
    9041126    }
     
    9071129  element._extended = true;
    9081130  return element;
    909 }
     1131};
    9101132
    9111133Element.extend.cache = {
     
    9151137    }
    9161138  }
    917 }
     1139};
    9181140
    9191141Element.Methods = {
     
    9221144  },
    9231145
    924   toggle: function() {
    925     for (var i = 0; i < arguments.length; i++) {
    926       var element = $(arguments[i]);
    927       Element[Element.visible(element) ? 'hide' : 'show'](element);
    928     }
    929   },
    930 
    931   hide: function() {
    932     for (var i = 0; i < arguments.length; i++) {
    933       var element = $(arguments[i]);
    934       element.style.display = 'none';
    935     }
    936   },
    937 
    938   show: function() {
    939     for (var i = 0; i < arguments.length; i++) {
    940       var element = $(arguments[i]);
    941       element.style.display = '';
    942     }
     1146  toggle: function(element) {
     1147    element = $(element);
     1148    Element[Element.visible(element) ? 'hide' : 'show'](element);
     1149    return element;
     1150  },
     1151
     1152  hide: function(element) {
     1153    $(element).style.display = 'none';
     1154    return element;
     1155  },
     1156
     1157  show: function(element) {
     1158    $(element).style.display = '';
     1159    return element;
    9431160  },
    9441161
     
    9461163    element = $(element);
    9471164    element.parentNode.removeChild(element);
     1165    return element;
    9481166  },
    9491167
    9501168  update: function(element, html) {
     1169    html = typeof html == 'undefined' ? '' : html.toString();
    9511170    $(element).innerHTML = html.stripScripts();
    9521171    setTimeout(function() {html.evalScripts()}, 10);
     1172    return element;
    9531173  },
    9541174
    9551175  replace: function(element, html) {
    9561176    element = $(element);
     1177    html = typeof html == 'undefined' ? '' : html.toString();
    9571178    if (element.outerHTML) {
    9581179      element.outerHTML = html.stripScripts();
     
    9641185    }
    9651186    setTimeout(function() {html.evalScripts()}, 10);
     1187    return element;
     1188  },
     1189
     1190  inspect: function(element) {
     1191    element = $(element);
     1192    var result = '<' + element.tagName.toLowerCase();
     1193    $H({'id': 'id', 'className': 'class'}).each(function(pair) {
     1194      var property = pair.first(), attribute = pair.last();
     1195      var value = (element[property] || '').toString();
     1196      if (value) result += ' ' + attribute + '=' + value.inspect(true);
     1197    });
     1198    return result + '>';
     1199  },
     1200
     1201  recursivelyCollect: function(element, property) {
     1202    element = $(element);
     1203    var elements = [];
     1204    while (element = element[property])
     1205      if (element.nodeType == 1)
     1206        elements.push(Element.extend(element));
     1207    return elements;
     1208  },
     1209
     1210  ancestors: function(element) {
     1211    return $(element).recursivelyCollect('parentNode');
     1212  },
     1213
     1214  descendants: function(element) {
     1215    return $A($(element).getElementsByTagName('*'));
     1216  },
     1217
     1218  immediateDescendants: function(element) {
     1219    if (!(element = $(element).firstChild)) return [];
     1220    while (element && element.nodeType != 1) element = element.nextSibling;
     1221    if (element) return [element].concat($(element).nextSiblings());
     1222    return [];
     1223  },
     1224
     1225  previousSiblings: function(element) {
     1226    return $(element).recursivelyCollect('previousSibling');
     1227  },
     1228
     1229  nextSiblings: function(element) {
     1230    return $(element).recursivelyCollect('nextSibling');
     1231  },
     1232
     1233  siblings: function(element) {
     1234    element = $(element);
     1235    return element.previousSiblings().reverse().concat(element.nextSiblings());
     1236  },
     1237
     1238  match: function(element, selector) {
     1239    if (typeof selector == 'string')
     1240      selector = new Selector(selector);
     1241    return selector.match($(element));
     1242  },
     1243
     1244  up: function(element, expression, index) {
     1245    return Selector.findElement($(element).ancestors(), expression, index);
     1246  },
     1247
     1248  down: function(element, expression, index) {
     1249    return Selector.findElement($(element).descendants(), expression, index);
     1250  },
     1251
     1252  previous: function(element, expression, index) {
     1253    return Selector.findElement($(element).previousSiblings(), expression, index);
     1254  },
     1255
     1256  next: function(element, expression, index) {
     1257    return Selector.findElement($(element).nextSiblings(), expression, index);
     1258  },
     1259
     1260  getElementsBySelector: function() {
     1261    var args = $A(arguments), element = $(args.shift());
     1262    return Selector.findChildElements(element, args);
     1263  },
     1264
     1265  getElementsByClassName: function(element, className) {
     1266    return document.getElementsByClassName(className, element);
     1267  },
     1268
     1269  readAttribute: function(element, name) {
     1270    element = $(element);
     1271    if (document.all && !window.opera) {
     1272      var t = Element._attributeTranslations;
     1273      if (t.values[name]) return t.values[name](element, name);
     1274      if (t.names[name])  name = t.names[name];
     1275      var attribute = element.attributes[name];
     1276      if(attribute) return attribute.nodeValue;
     1277    }
     1278    return element.getAttribute(name);
    9661279  },
    9671280
    9681281  getHeight: function(element) {
    969     element = $(element);
    970     return element.offsetHeight;
     1282    return $(element).getDimensions().height;
     1283  },
     1284
     1285  getWidth: function(element) {
     1286    return $(element).getDimensions().width;
    9711287  },
    9721288
     
    9771293  hasClassName: function(element, className) {
    9781294    if (!(element = $(element))) return;
    979     return Element.classNames(element).include(className);
     1295    var elementClassName = element.className;
     1296    if (elementClassName.length == 0) return false;
     1297    if (elementClassName == className ||
     1298        elementClassName.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
     1299      return true;
     1300    return false;
    9801301  },
    9811302
    9821303  addClassName: function(element, className) {
    9831304    if (!(element = $(element))) return;
    984     return Element.classNames(element).add(className);
     1305    Element.classNames(element).add(className);
     1306    return element;
    9851307  },
    9861308
    9871309  removeClassName: function(element, className) {
    9881310    if (!(element = $(element))) return;
    989     return Element.classNames(element).remove(className);
     1311    Element.classNames(element).remove(className);
     1312    return element;
     1313  },
     1314
     1315  toggleClassName: function(element, className) {
     1316    if (!(element = $(element))) return;
     1317    Element.classNames(element)[element.hasClassName(className) ? 'remove' : 'add'](className);
     1318    return element;
     1319  },
     1320
     1321  observe: function() {
     1322    Event.observe.apply(Event, arguments);
     1323    return $A(arguments).first();
     1324  },
     1325
     1326  stopObserving: function() {
     1327    Event.stopObserving.apply(Event, arguments);
     1328    return $A(arguments).first();
    9901329  },
    9911330
     
    9931332  cleanWhitespace: function(element) {
    9941333    element = $(element);
    995     for (var i = 0; i < element.childNodes.length; i++) {
    996       var node = element.childNodes[i];
     1334    var node = element.firstChild;
     1335    while (node) {
     1336      var nextNode = node.nextSibling;
    9971337      if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
    998         Element.remove(node);
    999     }
     1338        element.removeChild(node);
     1339      node = nextNode;
     1340    }
     1341    return element;
    10001342  },
    10011343
     
    10041346  },
    10051347
    1006   childOf: function(element, ancestor) {
     1348  descendantOf: function(element, ancestor) {
    10071349    element = $(element), ancestor = $(ancestor);
    10081350    while (element = element.parentNode)
     
    10131355  scrollTo: function(element) {
    10141356    element = $(element);
    1015     var x = element.x ? element.x : element.offsetLeft,
    1016         y = element.y ? element.y : element.offsetTop;
    1017     window.scrollTo(x, y);
     1357    var pos = Position.cumulativeOffset(element);
     1358    window.scrollTo(pos[0], pos[1]);
     1359    return element;
    10181360  },
    10191361
    10201362  getStyle: function(element, style) {
    10211363    element = $(element);
    1022     var value = element.style[style.camelize()];
     1364    if (['float','cssFloat'].include(style))
     1365      style = (typeof element.style.styleFloat != 'undefined' ? 'styleFloat' : 'cssFloat');
     1366    style = style.camelize();
     1367    var value = element.style[style];
    10231368    if (!value) {
    10241369      if (document.defaultView && document.defaultView.getComputedStyle) {
    10251370        var css = document.defaultView.getComputedStyle(element, null);
    1026         value = css ? css.getPropertyValue(style) : null;
     1371        value = css ? css[style] : null;
    10271372      } else if (element.currentStyle) {
    1028         value = element.currentStyle[style.camelize()];
     1373        value = element.currentStyle[style];
    10291374      }
    10301375    }
     1376
     1377    if((value == 'auto') && ['width','height'].include(style) && (element.getStyle('display') != 'none'))
     1378      value = element['offset'+style.capitalize()] + 'px';
    10311379
    10321380    if (window.opera && ['left', 'top', 'right', 'bottom'].include(style))
    10331381      if (Element.getStyle(element, 'position') == 'static') value = 'auto';
    1034 
     1382    if(style == 'opacity') {
     1383      if(value) return parseFloat(value);
     1384      if(value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
     1385        if(value[1]) return parseFloat(value[1]) / 100;
     1386      return 1.0;
     1387    }
    10351388    return value == 'auto' ? null : value;
    10361389  },
     
    10381391  setStyle: function(element, style) {
    10391392    element = $(element);
    1040     for (var name in style)
    1041       element.style[name.camelize()] = style[name];
     1393    for (var name in style) {
     1394      var value = style[name];
     1395      if(name == 'opacity') {
     1396        if (value == 1) {
     1397          value = (/Gecko/.test(navigator.userAgent) &&
     1398            !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ? 0.999999 : 1.0;
     1399          if(/MSIE/.test(navigator.userAgent) && !window.opera)
     1400            element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'');
     1401        } else if(value == '') {
     1402          if(/MSIE/.test(navigator.userAgent) && !window.opera)
     1403            element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'');
     1404        } else {
     1405          if(value < 0.00001) value = 0;
     1406          if(/MSIE/.test(navigator.userAgent) && !window.opera)
     1407            element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'') +
     1408              'alpha(opacity='+value*100+')';
     1409        }
     1410      } else if(['float','cssFloat'].include(name)) name = (typeof element.style.styleFloat != 'undefined') ? 'styleFloat' : 'cssFloat';
     1411      element.style[name.camelize()] = value;
     1412    }
     1413    return element;
    10421414  },
    10431415
    10441416  getDimensions: function(element) {
    10451417    element = $(element);
    1046     if (Element.getStyle(element, 'display') != 'none')
     1418    var display = $(element).getStyle('display');
     1419    if (display != 'none' && display != null) // Safari bug
    10471420      return {width: element.offsetWidth, height: element.offsetHeight};
    10481421
     
    10521425    var originalVisibility = els.visibility;
    10531426    var originalPosition = els.position;
     1427    var originalDisplay = els.display;
    10541428    els.visibility = 'hidden';
    10551429    els.position = 'absolute';
    1056     els.display = '';
     1430    els.display = 'block';
    10571431    var originalWidth = element.clientWidth;
    10581432    var originalHeight = element.clientHeight;
    1059     els.display = 'none';
     1433    els.display = originalDisplay;
    10601434    els.position = originalPosition;
    10611435    els.visibility = originalVisibility;
     
    10761450      }
    10771451    }
     1452    return element;
    10781453  },
    10791454
     
    10881463        element.style.right = '';
    10891464    }
     1465    return element;
    10901466  },
    10911467
    10921468  makeClipping: function(element) {
    10931469    element = $(element);
    1094     if (element._overflow) return;
    1095     element._overflow = element.style.overflow;
     1470    if (element._overflow) return element;
     1471    element._overflow = element.style.overflow || 'auto';
    10961472    if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden')
    10971473      element.style.overflow = 'hidden';
     1474    return element;
    10981475  },
    10991476
    11001477  undoClipping: function(element) {
    11011478    element = $(element);
    1102     if (element._overflow) return;
    1103     element.style.overflow = element._overflow;
    1104     element._overflow = undefined;
    1105   }
    1106 }
     1479    if (!element._overflow) return element;
     1480    element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
     1481    element._overflow = null;
     1482    return element;
     1483  }
     1484};
     1485
     1486Object.extend(Element.Methods, {childOf: Element.Methods.descendantOf});
     1487
     1488Element._attributeTranslations = {};
     1489
     1490Element._attributeTranslations.names = {
     1491  colspan:   "colSpan",
     1492  rowspan:   "rowSpan",
     1493  valign:    "vAlign",
     1494  datetime:  "dateTime",
     1495  accesskey: "accessKey",
     1496  tabindex:  "tabIndex",
     1497  enctype:   "encType",
     1498  maxlength: "maxLength",
     1499  readonly:  "readOnly",
     1500  longdesc:  "longDesc"
     1501};
     1502
     1503Element._attributeTranslations.values = {
     1504  _getAttr: function(element, attribute) {
     1505    return element.getAttribute(attribute, 2);
     1506  },
     1507
     1508  _flag: function(element, attribute) {
     1509    return $(element).hasAttribute(attribute) ? attribute : null;
     1510  },
     1511
     1512  style: function(element) {
     1513    return element.style.cssText.toLowerCase();
     1514  },
     1515
     1516  title: function(element) {
     1517    var node = element.getAttributeNode('title');
     1518    return node.specified ? node.nodeValue : null;
     1519  }
     1520};
     1521
     1522Object.extend(Element._attributeTranslations.values, {
     1523  href: Element._attributeTranslations.values._getAttr,
     1524  src:  Element._attributeTranslations.values._getAttr,
     1525  disabled: Element._attributeTranslations.values._flag,
     1526  checked:  Element._attributeTranslations.values._flag,
     1527  readonly: Element._attributeTranslations.values._flag,
     1528  multiple: Element._attributeTranslations.values._flag
     1529});
     1530
     1531Element.Methods.Simulated = {
     1532  hasAttribute: function(element, attribute) {
     1533    var t = Element._attributeTranslations;
     1534    attribute = t.names[attribute] || attribute;
     1535    return $(element).getAttributeNode(attribute).specified;
     1536  }
     1537};
     1538
     1539// IE is missing .innerHTML support for TABLE-related elements
     1540if (document.all && !window.opera){
     1541  Element.Methods.update = function(element, html) {
     1542    element = $(element);
     1543    html = typeof html == 'undefined' ? '' : html.toString();
     1544    var tagName = element.tagName.toUpperCase();
     1545    if (['THEAD','TBODY','TR','TD'].include(tagName)) {
     1546      var div = document.createElement('div');
     1547      switch (tagName) {
     1548        case 'THEAD':
     1549        case 'TBODY':
     1550          div.innerHTML = '<table><tbody>' +  html.stripScripts() + '</tbody></table>';
     1551          depth = 2;
     1552          break;
     1553        case 'TR':
     1554          div.innerHTML = '<table><tbody><tr>' +  html.stripScripts() + '</tr></tbody></table>';
     1555          depth = 3;
     1556          break;
     1557        case 'TD':
     1558          div.innerHTML = '<table><tbody><tr><td>' +  html.stripScripts() + '</td></tr></tbody></table>';
     1559          depth = 4;
     1560      }
     1561      $A(element.childNodes).each(function(node){
     1562        element.removeChild(node)
     1563      });
     1564      depth.times(function(){ div = div.firstChild });
     1565
     1566      $A(div.childNodes).each(
     1567        function(node){ element.appendChild(node) });
     1568    } else {
     1569      element.innerHTML = html.stripScripts();
     1570    }
     1571    setTimeout(function() {html.evalScripts()}, 10);
     1572    return element;
     1573  }
     1574};
    11071575
    11081576Object.extend(Element, Element.Methods);
     
    11101578var _nativeExtensions = false;
    11111579
    1112 if(!HTMLElement && /Konqueror|Safari|KHTML/.test(navigator.userAgent)) {
    1113   var HTMLElement = {}
    1114   HTMLElement.prototype = document.createElement('div').__proto__;
    1115 }
     1580if(/Konqueror|Safari|KHTML/.test(navigator.userAgent))
     1581  ['', 'Form', 'Input', 'TextArea', 'Select'].each(function(tag) {
     1582    var className = 'HTML' + tag + 'Element';
     1583    if(window[className]) return;
     1584    var klass = window[className] = {};
     1585    klass.prototype = document.createElement(tag ? tag.toLowerCase() : 'div').__proto__;
     1586  });
    11161587
    11171588Element.addMethods = function(methods) {
    11181589  Object.extend(Element.Methods, methods || {});
    11191590
    1120   if(typeof HTMLElement != 'undefined') {
    1121     var methods = Element.Methods, cache = Element.extend.cache;
    1122     for (property in methods) {
     1591  function copy(methods, destination, onlyIfAbsent) {
     1592    onlyIfAbsent = onlyIfAbsent || false;
     1593    var cache = Element.extend.cache;
     1594    for (var property in methods) {
    11231595      var value = methods[property];
    1124       if (typeof value == 'function')
    1125         HTMLElement.prototype[property] = cache.findOrStore(value);
    1126     }
     1596      if (!onlyIfAbsent || !(property in destination))
     1597        destination[property] = cache.findOrStore(value);
     1598    }
     1599  }
     1600
     1601  if (typeof HTMLElement != 'undefined') {
     1602    copy(Element.Methods, HTMLElement.prototype);
     1603    copy(Element.Methods.Simulated, HTMLElement.prototype, true);
     1604    copy(Form.Methods, HTMLFormElement.prototype);
     1605    [HTMLInputElement, HTMLTextAreaElement, HTMLSelectElement].each(function(klass) {
     1606      copy(Form.Element.Methods, klass.prototype);
     1607    });
    11271608    _nativeExtensions = true;
    11281609  }
    11291610}
    1130 
    1131 Element.addMethods();
    11321611
    11331612var Toggle = new Object();
     
    11491628        this.element.insertAdjacentHTML(this.adjacency, this.content);
    11501629      } catch (e) {
    1151         var tagName = this.element.tagName.toLowerCase();
    1152         if (tagName == 'tbody' || tagName == 'tr') {
     1630        var tagName = this.element.tagName.toUpperCase();
     1631        if (['TBODY', 'TR'].include(tagName)) {
    11531632          this.insertContent(this.contentFromAnonymousTable());
    11541633        } else {
     
    12491728  add: function(classNameToAdd) {
    12501729    if (this.include(classNameToAdd)) return;
    1251     this.set(this.toArray().concat(classNameToAdd).join(' '));
     1730    this.set($A(this).concat(classNameToAdd).join(' '));
    12521731  },
    12531732
    12541733  remove: function(classNameToRemove) {
    12551734    if (!this.include(classNameToRemove)) return;
    1256     this.set(this.select(function(className) {
    1257       return className != classNameToRemove;
    1258     }).join(' '));
     1735    this.set($A(this).without(classNameToRemove).join(' '));
    12591736  },
    12601737
    12611738  toString: function() {
    1262     return this.toArray().join(' ');
    1263   }
    1264 }
     1739    return $A(this).join(' ');
     1740  }
     1741};
    12651742
    12661743Object.extend(Element.ClassNames.prototype, Enumerable);
     
    13091786      conditions.push('true');
    13101787    if (clause = params.id)
    1311       conditions.push('element.id == ' + clause.inspect());
     1788      conditions.push('element.readAttribute("id") == ' + clause.inspect());
    13121789    if (clause = params.tagName)
    13131790      conditions.push('element.tagName.toUpperCase() == ' + clause.inspect());
    13141791    if ((clause = params.classNames).length > 0)
    1315       for (var i = 0; i < clause.length; i++)
    1316         conditions.push('Element.hasClassName(element, ' + clause[i].inspect() + ')');
     1792      for (var i = 0, length = clause.length; i < length; i++)
     1793        conditions.push('element.hasClassName(' + clause[i].inspect() + ')');
    13171794    if (clause = params.attributes) {
    13181795      clause.each(function(attribute) {
    1319         var value = 'element.getAttribute(' + attribute.name.inspect() + ')';
     1796        var value = 'element.readAttribute(' + attribute.name.inspect() + ')';
    13201797        var splitValueBy = function(delimiter) {
    13211798          return value + ' && ' + value + '.split(' + delimiter.inspect() + ')';
     
    13301807          case '!=':      conditions.push(value + ' != ' + attribute.value.inspect()); break;
    13311808          case '':
    1332           case undefined: conditions.push(value + ' != null'); break;
     1809          case undefined: conditions.push('element.hasAttribute(' + attribute.name.inspect() + ')'); break;
    13331810          default:        throw 'Unknown operator ' + attribute.operator + ' in selector';
    13341811        }
     
    13411818  compileMatcher: function() {
    13421819    this.match = new Function('element', 'if (!element.tagName) return false; \
     1820      element = $(element); \
    13431821      return ' + this.buildMatchExpression());
    13441822  },
     
    13551833
    13561834    var results = [];
    1357     for (var i = 0; i < scope.length; i++)
     1835    for (var i = 0, length = scope.length; i < length; i++)
    13581836      if (this.match(element = scope[i]))
    13591837        results.push(Element.extend(element));
     
    13671845}
    13681846
     1847Object.extend(Selector, {
     1848  matchElements: function(elements, expression) {
     1849    var selector = new Selector(expression);
     1850    return elements.select(selector.match.bind(selector)).map(Element.extend);
     1851  },
     1852
     1853  findElement: function(elements, expression, index) {
     1854    if (typeof expression == 'number') index = expression, expression = false;
     1855    return Selector.matchElements(elements, expression || '*')[index || 0];
     1856  },
     1857
     1858  findChildElements: function(element, expressions) {
     1859    return expressions.map(function(expression) {
     1860      return expression.match(/[^\s"]+(?:"[^"]*"[^\s"]+)*/g).inject([null], function(results, expr) {
     1861        var selector = new Selector(expr);
     1862        return results.inject([], function(elements, result) {
     1863          return elements.concat(selector.findElements(result || element));
     1864        });
     1865      });
     1866    }).flatten();
     1867  }
     1868});
     1869
    13691870function $$() {
    1370   return $A(arguments).map(function(expression) {
    1371     return expression.strip().split(/\s+/).inject([null], function(results, expr) {
    1372       var selector = new Selector(expr);
    1373       return results.map(selector.findElements.bind(selector)).flatten();
    1374     });
    1375   }).flatten();
    1376 }
    1377 var Field = {
    1378   clear: function() {
    1379     for (var i = 0; i < arguments.length; i++)
    1380       $(arguments[i]).value = '';
    1381   },
    1382 
     1871  return Selector.findChildElements(document, $A(arguments));
     1872}
     1873var Form = {
     1874  reset: function(form) {
     1875    $(form).reset();
     1876    return form;
     1877  },
     1878
     1879  serializeElements: function(elements, getHash) {
     1880    var data = elements.inject({}, function(result, element) {
     1881      if (!element.disabled && element.name) {
     1882        var key = element.name, value = $(element).getValue();
     1883        if (value != undefined) {
     1884          if (result[key]) {
     1885            if (result[key].constructor != Array) result[key] = [result[key]];
     1886            result[key].push(value);
     1887          }
     1888          else result[key] = value;
     1889        }
     1890      }
     1891      return result;
     1892    });
     1893
     1894    return getHash ? data : Hash.toQueryString(data);
     1895  }
     1896};
     1897
     1898Form.Methods = {
     1899  serialize: function(form, getHash) {
     1900    return Form.serializeElements(Form.getElements(form), getHash);
     1901  },
     1902
     1903  getElements: function(form) {
     1904    return $A($(form).getElementsByTagName('*')).inject([],
     1905      function(elements, child) {
     1906        if (Form.Element.Serializers[child.tagName.toLowerCase()])
     1907          elements.push(Element.extend(child));
     1908        return elements;
     1909      }
     1910    );
     1911  },
     1912
     1913  getInputs: function(form, typeName, name) {
     1914    form = $(form);
     1915    var inputs = form.getElementsByTagName('input');
     1916
     1917    if (!typeName && !name) return $A(inputs).map(Element.extend);
     1918
     1919    for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
     1920      var input = inputs[i];
     1921      if ((typeName && input.type != typeName) || (name && input.name != name))
     1922        continue;
     1923      matchingInputs.push(Element.extend(input));
     1924    }
     1925
     1926    return matchingInputs;
     1927  },
     1928
     1929  disable: function(form) {
     1930    form = $(form);
     1931    form.getElements().each(function(element) {
     1932      element.blur();
     1933      element.disabled = 'true';
     1934    });
     1935    return form;
     1936  },
     1937
     1938  enable: function(form) {
     1939    form = $(form);
     1940    form.getElements().each(function(element) {
     1941      element.disabled = '';
     1942    });
     1943    return form;
     1944  },
     1945
     1946  findFirstElement: function(form) {
     1947    return $(form).getElements().find(function(element) {
     1948      return element.type != 'hidden' && !element.disabled &&
     1949        ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
     1950    });
     1951  },
     1952
     1953  focusFirstElement: function(form) {
     1954    form = $(form);
     1955    form.findFirstElement().activate();
     1956    return form;
     1957  }
     1958}
     1959
     1960Object.extend(Form, Form.Methods);
     1961
     1962/*--------------------------------------------------------------------------*/
     1963
     1964Form.Element = {
    13831965  focus: function(element) {
    13841966    $(element).focus();
    1385   },
    1386 
    1387   present: function() {
    1388     for (var i = 0; i < arguments.length; i++)
    1389       if ($(arguments[i]).value == '') return false;
    1390     return true;
     1967    return element;
    13911968  },
    13921969
    13931970  select: function(element) {
    13941971    $(element).select();
     1972    return element;
     1973  }
     1974}
     1975
     1976Form.Element.Methods = {
     1977  serialize: function(element) {
     1978    element = $(element);
     1979    if (!element.disabled && element.name) {
     1980      var value = element.getValue();
     1981      if (value != undefined) {
     1982        var pair = {};
     1983        pair[element.name] = value;
     1984        return Hash.toQueryString(pair);
     1985      }
     1986    }
     1987    return '';
     1988  },
     1989
     1990  getValue: function(element) {
     1991    element = $(element);
     1992    var method = element.tagName.toLowerCase();
     1993    return Form.Element.Serializers[method](element);
     1994  },
     1995
     1996  clear: function(element) {
     1997    $(element).value = '';
     1998    return element;
     1999  },
     2000
     2001  present: function(element) {
     2002    return $(element).value != '';
    13952003  },
    13962004
     
    13982006    element = $(element);
    13992007    element.focus();
    1400     if (element.select)
     2008    if (element.select && ( element.tagName.toLowerCase() != 'input' ||
     2009      !['button', 'reset', 'submit'].include(element.type) ) )
    14012010      element.select();
    1402   }
    1403 }
     2011    return element;
     2012  },
     2013
     2014  disable: function(element) {
     2015    element = $(element);
     2016    element.disabled = true;
     2017    return element;
     2018  },
     2019
     2020  enable: function(element) {
     2021    element = $(element);
     2022    element.blur();
     2023    element.disabled = false;
     2024    return element;
     2025  }
     2026}
     2027
     2028Object.extend(Form.Element, Form.Element.Methods);
     2029var Field = Form.Element;
     2030var $F = Form.Element.getValue;
    14042031
    14052032/*--------------------------------------------------------------------------*/
    1406 
    1407 var Form = {
    1408   serialize: function(form) {
    1409     var elements = Form.getElements($(form));
    1410     var queryComponents = new Array();
    1411 
    1412     for (var i = 0; i < elements.length; i++) {
    1413       var queryComponent = Form.Element.serialize(elements[i]);
    1414       if (queryComponent)
    1415         queryComponents.push(queryComponent);
    1416     }
    1417 
    1418     return queryComponents.join('&');
    1419   },
    1420 
    1421   getElements: function(form) {
    1422     form = $(form);
    1423     var elements = new Array();
    1424 
    1425     for (var tagName in Form.Element.Serializers) {
    1426       var tagElements = form.getElementsByTagName(tagName);
    1427       for (var j = 0; j < tagElements.length; j++)
    1428         elements.push(tagElements[j]);
    1429     }
    1430     return elements;
    1431   },
    1432 
    1433   getInputs: function(form, typeName, name) {
    1434     form = $(form);
    1435     var inputs = form.getElementsByTagName('input');
    1436 
    1437     if (!typeName && !name)
    1438       return inputs;
    1439 
    1440     var matchingInputs = new Array();
    1441     for (var i = 0; i < inputs.length; i++) {
    1442       var input = inputs[i];
    1443       if ((typeName && input.type != typeName) ||
    1444           (name && input.name != name))
    1445         continue;
    1446       matchingInputs.push(input);
    1447     }
    1448 
    1449     return matchingInputs;
    1450   },
    1451 
    1452   disable: function(form) {
    1453     var elements = Form.getElements(form);
    1454     for (var i = 0; i < elements.length; i++) {
    1455       var element = elements[i];
    1456       element.blur();
    1457       element.disabled = 'true';
    1458     }
    1459   },
    1460 
    1461   enable: function(form) {
    1462     var elements = Form.getElements(form);
    1463     for (var i = 0; i < elements.length; i++) {
    1464       var element = elements[i];
    1465       element.disabled = '';
    1466     }
    1467   },
    1468 
    1469   findFirstElement: function(form) {
    1470     return Form.getElements(form).find(function(element) {
    1471       return element.type != 'hidden' && !element.disabled &&
    1472         ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
    1473     });
    1474   },
    1475 
    1476   focusFirstElement: function(form) {
    1477     Field.activate(Form.findFirstElement(form));
    1478   },
    1479 
    1480   reset: function(form) {
    1481     $(form).reset();
    1482   }
    1483 }
    1484 
    1485 Form.Element = {
    1486   serialize: function(element) {
    1487     element = $(element);
    1488     var method = element.tagName.toLowerCase();
    1489     var parameter = Form.Element.Serializers[method](element);
    1490 
    1491     if (parameter) {
    1492       var key = encodeURIComponent(parameter[0]);
    1493       if (key.length == 0) return;
    1494 
    1495       if (parameter[1].constructor != Array)
    1496         parameter[1] = [parameter[1]];
    1497 
    1498       return parameter[1].map(function(value) {
    1499         return key + '=' + encodeURIComponent(value);
    1500       }).join('&');
    1501     }
    1502   },
    1503 
    1504   getValue: function(element) {
    1505     element = $(element);
    1506     var method = element.tagName.toLowerCase();
    1507     var parameter = Form.Element.Serializers[method](element);
    1508 
    1509     if (parameter)
    1510       return parameter[1];
    1511   }
    1512 }
    15132033
    15142034Form.Element.Serializers = {
    15152035  input: function(element) {
    15162036    switch (element.type.toLowerCase()) {
    1517       case 'submit':
    1518       case 'hidden':
    1519       case 'password':
    1520       case 'text':
    1521         return Form.Element.Serializers.textarea(element);
    15222037      case 'checkbox':
    15232038      case 'radio':
    15242039        return Form.Element.Serializers.inputSelector(element);
    1525     }
    1526     return false;
     2040      default:
     2041        return Form.Element.Serializers.textarea(element);
     2042    }
    15272043  },
    15282044
    15292045  inputSelector: function(element) {
    1530     if (element.checked)
    1531       return [element.name, element.value];
     2046    return element.checked ? element.value : null;
    15322047  },
    15332048
    15342049  textarea: function(element) {
    1535     return [element.name, element.value];
     2050    return element.value;
    15362051  },
    15372052
    15382053  select: function(element) {
    1539     return Form.Element.Serializers[element.type == 'select-one' ?
     2054    return this[element.type == 'select-one' ?
    15402055      'selectOne' : 'selectMany'](element);
    15412056  },
    15422057
    15432058  selectOne: function(element) {
    1544     var value = '', opt, index = element.selectedIndex;
    1545     if (index >= 0) {
    1546       opt = element.options[index];
    1547       value = opt.value || opt.text;
    1548     }
    1549     return [element.name, value];
     2059    var index = element.selectedIndex;
     2060    return index >= 0 ? this.optionValue(element.options[index]) : null;
    15502061  },
    15512062
    15522063  selectMany: function(element) {
    1553     var value = [];
    1554     for (var i = 0; i < element.length; i++) {
     2064    var values, length = element.length;
     2065    if (!length) return null;
     2066
     2067    for (var i = 0, values = []; i < length; i++) {
    15552068      var opt = element.options[i];
    1556       if (opt.selected)
    1557         value.push(opt.value || opt.text);
    1558     }
    1559     return [element.name, value];
    1560   }
    1561 }
    1562 
    1563 /*--------------------------------------------------------------------------*/
    1564 
    1565 var $F = Form.Element.getValue;
     2069      if (opt.selected) values.push(this.optionValue(opt));
     2070    }
     2071    return values;
     2072  },
     2073
     2074  optionValue: function(opt) {
     2075    // extend element because hasAttribute may not be native
     2076    return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
     2077  }
     2078}
    15662079
    15672080/*--------------------------------------------------------------------------*/
     
    15842097  onTimerEvent: function() {
    15852098    var value = this.getValue();
    1586     if (this.lastValue != value) {
     2099    var changed = ('string' == typeof this.lastValue && 'string' == typeof value
     2100      ? this.lastValue != value : String(this.lastValue) != String(value));
     2101    if (changed) {
    15872102      this.callback(this.element, value);
    15882103      this.lastValue = value;
     
    16292144
    16302145  registerFormCallbacks: function() {
    1631     var elements = Form.getElements(this.element);
    1632     for (var i = 0; i < elements.length; i++)
    1633       this.registerCallback(elements[i]);
     2146    Form.getElements(this.element).each(this.registerCallback.bind(this));
    16342147  },
    16352148
     
    16412154          Event.observe(element, 'click', this.onElementEvent.bind(this));
    16422155          break;
    1643         case 'password':
    1644         case 'text':
    1645         case 'textarea':
    1646         case 'select-one':
    1647         case 'select-multiple':
     2156        default:
    16482157          Event.observe(element, 'change', this.onElementEvent.bind(this));
    16492158          break;
     
    16802189  KEY_DOWN:     40,
    16812190  KEY_DELETE:   46,
     2191  KEY_HOME:     36,
     2192  KEY_END:      35,
     2193  KEY_PAGEUP:   33,
     2194  KEY_PAGEDOWN: 34,
    16822195
    16832196  element: function(event) {
     
    17352248  unloadCache: function() {
    17362249    if (!Event.observers) return;
    1737     for (var i = 0; i < Event.observers.length; i++) {
     2250    for (var i = 0, length = Event.observers.length; i < length; i++) {
    17382251      Event.stopObserving.apply(this, Event.observers[i]);
    17392252      Event.observers[i][0] = null;
     
    17432256
    17442257  observe: function(element, name, observer, useCapture) {
    1745     var element = $(element);
     2258    element = $(element);
    17462259    useCapture = useCapture || false;
    17472260
     
    17512264      name = 'keydown';
    17522265
    1753     this._observeAndCache(element, name, observer, useCapture);
     2266    Event._observeAndCache(element, name, observer, useCapture);
    17542267  },
    17552268
    17562269  stopObserving: function(element, name, observer, useCapture) {
    1757     var element = $(element);
     2270    element = $(element);
    17582271    useCapture = useCapture || false;
    17592272
     
    18222335      element = element.offsetParent;
    18232336      if (element) {
    1824         p = Element.getStyle(element, 'position');
     2337        if(element.tagName=='BODY') break;
     2338        var p = Element.getStyle(element, 'position');
    18252339        if (p == 'relative' || p == 'absolute') break;
    18262340      }
     
    18782392  },
    18792393
    1880   clone: function(source, target) {
    1881     source = $(source);
    1882     target = $(target);
    1883     target.style.position = 'absolute';
    1884     var offsets = this.cumulativeOffset(source);
    1885     target.style.top    = offsets[1] + 'px';
    1886     target.style.left   = offsets[0] + 'px';
    1887     target.style.width  = source.offsetWidth + 'px';
    1888     target.style.height = source.offsetHeight + 'px';
    1889   },
    1890 
    18912394  page: function(forElement) {
    18922395    var valueT = 0, valueL = 0;
     
    19052408    element = forElement;
    19062409    do {
    1907       valueT -= element.scrollTop  || 0;
    1908       valueL -= element.scrollLeft || 0;
     2410      if (!window.opera || element.tagName=='BODY') {
     2411        valueT -= element.scrollTop  || 0;
     2412        valueL -= element.scrollLeft || 0;
     2413      }
    19092414    } while (element = element.parentNode);
    19102415
     
    19672472
    19682473    element.style.position = 'absolute';
    1969     element.style.top    = top + 'px';;
    1970     element.style.left   = left + 'px';;
    1971     element.style.width  = width + 'px';;
    1972     element.style.height = height + 'px';;
     2474    element.style.top    = top + 'px';
     2475    element.style.left   = left + 'px';
     2476    element.style.width  = width + 'px';
     2477    element.style.height = height + 'px';
    19732478  },
    19742479
     
    20072512  }
    20082513}
     2514
     2515Element.addMethods();
  • tags/2.2/wp-includes/js/quicktags.js

    r5468 r5480  
    169169
    170170function edShowLinks() {
    171     var tempStr = '<select onchange="edQuickLink(this.options[this.selectedIndex].value, this);"><option value="-1" selected>(Quick Links)</option>';
     171    var tempStr = '<select onchange="edQuickLink(this.options[this.selectedIndex].value, this);"><option value="-1" selected>' + quicktagsL10n.quickLinks + '</option>';
    172172    for (i = 0; i < edLinks.length; i++) {
    173173        tempStr += '<option value="' + i + '">' + edLinks[i].display + '</option>';
     
    249249    }
    250250    if (word == '') {
    251         word = prompt('Enter a word to look up:', '');
     251        word = prompt(quicktagsL10n.wordLookup, '');
    252252    }
    253253    if (word !== null && /^\w[\w ]*$/.test(word)) {
     
    261261        edShowButton(edButtons[i], i);
    262262    }
    263     document.write('<input type="button" id="ed_spell" class="ed_button" onclick="edSpell(edCanvas);" title="Dictionary lookup" value="lookup" />');
    264     document.write('<input type="button" id="ed_close" class="ed_button" onclick="edCloseAllTags();" title="Close all open tags" value="Close Tags" />');
     263    document.write('<input type="button" id="ed_spell" class="ed_button" onclick="edSpell(edCanvas);" title="' + quicktagsL10n.dictionaryLookup + '" value="' + quicktagsL10n.lookup + '" />');
     264    document.write('<input type="button" id="ed_close" class="ed_button" onclick="edCloseAllTags();" title="' + quicktagsL10n.closeAllOpenTags + '" value="' + quicktagsL10n.closeTags + '" />');
    265265//  edShowLinks(); // disabled by default
    266266    document.write('</div>');
     
    367367    }
    368368    if (!edCheckOpenTags(i)) {
    369         var URL = prompt('Enter the URL' ,defaultValue);
     369        var URL = prompt(quicktagsL10n.enterURL, defaultValue);
    370370        if (URL) {
    371371            edButtons[i].tagStart = '<a href="' + URL + '">';
     
    379379
    380380function edInsertImage(myField) {
    381     var myValue = prompt('Enter the URL of the image', 'http://');
     381    var myValue = prompt(quicktagsL10n.enterImageURL, 'http://');
    382382    if (myValue) {
    383383        myValue = '<img src="'
    384384                + myValue
    385                 + '" alt="' + prompt('Enter a description of the image', '')
     385                + '" alt="' + prompt(quicktagsL10n.enterImageDescription, '')
    386386                + '" />';
    387387        edInsertContent(myField, myValue);
  • tags/2.2/wp-includes/js/scriptaculous/MIT-LICENSE

    r5468 r5480  
    1 Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
     1Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
    22
    33Permission is hereby granted, free of charge, to any person obtaining
  • tags/2.2/wp-includes/js/scriptaculous/builder.js

    r5468 r5480  
    1 // Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
     1// script.aculo.us builder.js v1.7.0, Fri Jan 19 19:16:36 CET 2007
     2
     3// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
    24//
    3 // See scriptaculous.js for full license.
     5// script.aculo.us is freely distributable under the terms of an MIT-style license.
     6// For details, see the script.aculo.us web site: http://script.aculo.us/
    47
    58var Builder = {
     
    3437     
    3538    // see if browser added wrapping tags
    36     if(element && (element.tagName != elementName))
     39    if(element && (element.tagName.toUpperCase() != elementName))
    3740      element = element.getElementsByTagName(elementName)[0];
    3841   
     
    6265                element[attr == 'class' ? 'className' : attr] = arguments[1][attr];
    6366            }
    64             if(element.tagName != elementName)
     67            if(element.tagName.toUpperCase() != elementName)
    6568              element = parentElement.getElementsByTagName(elementName)[0];
    6669            }
     
    7679     return document.createTextNode(text);
    7780  },
     81
     82  ATTR_MAP: {
     83    'className': 'class',
     84    'htmlFor': 'for'
     85  },
     86
    7887  _attributes: function(attributes) {
    7988    var attrs = [];
    8089    for(attribute in attributes)
    81       attrs.push((attribute=='className' ? 'class' : attribute) +
     90      attrs.push((attribute in this.ATTR_MAP ? this.ATTR_MAP[attribute] : attribute) +
    8291          '="' + attributes[attribute].toString().escapeHTML() + '"');
    8392    return attrs.join(" ");
     
    98107  _isStringOrNumber: function(param) {
    99108    return(typeof param=='string' || typeof param=='number');
     109  },
     110  build: function(html) {
     111    var element = this.node('div');
     112    $(element).update(html.strip());
     113    return element.down();
     114  },
     115  dump: function(scope) {
     116    if(typeof scope != 'object' && typeof scope != 'function') scope = window; //global scope
     117 
     118    var tags = ("A ABBR ACRONYM ADDRESS APPLET AREA B BASE BASEFONT BDO BIG BLOCKQUOTE BODY " +
     119      "BR BUTTON CAPTION CENTER CITE CODE COL COLGROUP DD DEL DFN DIR DIV DL DT EM FIELDSET " +
     120      "FONT FORM FRAME FRAMESET H1 H2 H3 H4 H5 H6 HEAD HR HTML I IFRAME IMG INPUT INS ISINDEX "+
     121      "KBD LABEL LEGEND LI LINK MAP MENU META NOFRAMES NOSCRIPT OBJECT OL OPTGROUP OPTION P "+
     122      "PARAM PRE Q S SAMP SCRIPT SELECT SMALL SPAN STRIKE STRONG STYLE SUB SUP TABLE TBODY TD "+
     123      "TEXTAREA TFOOT TH THEAD TITLE TR TT U UL VAR").split(/\s+/);
     124 
     125    tags.each( function(tag){
     126      scope[tag] = function() {
     127        return Builder.node.apply(Builder, [tag].concat($A(arguments))); 
     128      }
     129    });
    100130  }
    101131}
  • tags/2.2/wp-includes/js/scriptaculous/controls.js

    r5468 r5480  
    1 // Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
    2 //           (c) 2005 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
    3 //           (c) 2005 Jon Tirsen (http://www.tirsen.com)
     1// script.aculo.us controls.js v1.7.0, Fri Jan 19 19:16:36 CET 2007
     2
     3// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
     4//           (c) 2005, 2006 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
     5//           (c) 2005, 2006 Jon Tirsen (http://www.tirsen.com)
    46// Contributors:
    57//  Richard Livsey
     
    79//  Rob Wills
    810//
    9 // See scriptaculous.js for full license.
     11// script.aculo.us is freely distributable under the terms of an MIT-style license.
     12// For details, see the script.aculo.us web site: http://script.aculo.us/
    1013
    1114// Autocompleter.Base handles all the autocompletion functionality
     
    3336// useful when one of the tokens is \n (a newline), as it
    3437// allows smart autocompletion after linebreaks.
     38
     39if(typeof Effect == 'undefined')
     40  throw("controls.js requires including script.aculo.us' effects.js library");
    3541
    3642var Autocompleter = {}
     
    4652    this.entryCount  = 0;
    4753
    48     if (this.setOptions)
     54    if(this.setOptions)
    4955      this.setOptions(options);
    5056    else
     
    5662    this.options.minChars     = this.options.minChars || 1;
    5763    this.options.onShow       = this.options.onShow ||
    58     function(element, update){
    59       if(!update.style.position || update.style.position=='absolute') {
    60         update.style.position = 'absolute';
    61         Position.clone(element, update, {setHeight: false, offsetTop: element.offsetHeight});
    62       }
    63       Effect.Appear(update,{duration:0.15});
    64     };
     64      function(element, update){
     65        if(!update.style.position || update.style.position=='absolute') {
     66          update.style.position = 'absolute';
     67          Position.clone(element, update, {
     68            setHeight: false,
     69            offsetTop: element.offsetHeight
     70          });
     71        }
     72        Effect.Appear(update,{duration:0.15});
     73      };
    6574    this.options.onHide = this.options.onHide ||
    66     function(element, update){ new Effect.Fade(update,{duration:0.15}) };
    67 
    68     if (typeof(this.options.tokens) == 'string')
     75      function(element, update){ new Effect.Fade(update,{duration:0.15}) };
     76
     77    if(typeof(this.options.tokens) == 'string')
    6978      this.options.tokens = new Array(this.options.tokens);
    7079
     
    95104 
    96105  fixIEOverlapping: function() {
    97     Position.clone(this.update, this.iefix);
     106    Position.clone(this.update, this.iefix, {setTop:(!this.update.style.height)});
    98107    this.iefix.style.zIndex = 1;
    99108    this.update.style.zIndex = 2;
     
    203212    if(this.index > 0) this.index--
    204213      else this.index = this.entryCount-1;
     214    this.getEntry(this.index).scrollIntoView(true);
    205215  },
    206216 
     
    208218    if(this.index < this.entryCount-1) this.index++
    209219      else this.index = 0;
     220    this.getEntry(this.index).scrollIntoView(false);
    210221  },
    211222 
     
    255266      this.update.innerHTML = choices;
    256267      Element.cleanWhitespace(this.update);
    257       Element.cleanWhitespace(this.update.firstChild);
    258 
    259       if(this.update.firstChild && this.update.firstChild.childNodes) {
     268      Element.cleanWhitespace(this.update.down());
     269
     270      if(this.update.firstChild && this.update.down().childNodes) {
    260271        this.entryCount =
    261           this.update.firstChild.childNodes.length;
     272          this.update.down().childNodes.length;
    262273        for (var i = 0; i < this.entryCount; i++) {
    263274          var entry = this.getEntry(i);
     
    270281
    271282      this.stopIndicator();
    272 
    273283      this.index = 0;
    274       this.render();
     284     
     285      if(this.entryCount==1 && this.options.autoSelect) {
     286        this.selectEntry();
     287        this.hide();
     288      } else {
     289        this.render();
     290      }
    275291    }
    276292  },
     
    460476
    461477    this.options = Object.extend({
     478      paramName: "value",
    462479      okButton: true,
    463480      okText: "ok",
     
    532549    this.createForm();
    533550    this.element.parentNode.insertBefore(this.form, this.element);
    534     Field.scrollFreeActivate(this.editField);
     551    if (!this.options.loadTextURL) Field.scrollFreeActivate(this.editField);
    535552    // stop the event to avoid a page refresh in Safari
    536553    if (evt) {
     
    591608      textField.obj = this;
    592609      textField.type = "text";
    593       textField.name = "value";
     610      textField.name = this.options.paramName;
    594611      textField.value = text;
    595612      textField.style.backgroundColor = this.options.highlightcolor;
     
    604621      var textArea = document.createElement("textarea");
    605622      textArea.obj = this;
    606       textArea.name = "value";
     623      textArea.name = this.options.paramName;
    607624      textArea.value = this.convertHTMLLineBreaks(text);
    608625      textArea.rows = this.options.rows;
     
    637654    this.editField.disabled = false;
    638655    this.editField.value = transport.responseText.stripTags();
     656    Field.scrollFreeActivate(this.editField);
    639657  },
    640658  onclickCancel: function() {
     
    773791        optionTag = document.createElement("option");
    774792        optionTag.value = (e instanceof Array) ? e[0] : e;
     793        if((typeof this.options.value == 'undefined') &&
     794          ((e instanceof Array) ? this.element.innerHTML == e[1] : e == optionTag.value)) optionTag.selected = true;
    775795        if(this.options.value==optionTag.value) optionTag.selected = true;
    776796        optionTag.appendChild(document.createTextNode((e instanceof Array) ? e[1] : e));
  • tags/2.2/wp-includes/js/scriptaculous/dragdrop.js

    r5468 r5480  
    1 // Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
    2 //           (c) 2005 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz)
     1// script.aculo.us dragdrop.js v1.7.0, Fri Jan 19 19:16:36 CET 2007
     2
     3// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
     4//           (c) 2005, 2006 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz)
    35//
    4 // See scriptaculous.js for full license.
    5 
    6 /*--------------------------------------------------------------------------*/
     6// script.aculo.us is freely distributable under the terms of an MIT-style license.
     7// For details, see the script.aculo.us web site: http://script.aculo.us/
     8
     9if(typeof Effect == 'undefined')
     10  throw("dragdrop.js requires including script.aculo.us' effects.js library");
    711
    812var Droppables = {
     
    146150 
    147151  activate: function(draggable) {
    148     window.focus(); // allows keypress events if window isn't currently focused, fails for Safari
    149     this.activeDraggable = draggable;
     152    if(draggable.options.delay) {
     153      this._timeout = setTimeout(function() {
     154        Draggables._timeout = null;
     155        window.focus();
     156        Draggables.activeDraggable = draggable;
     157      }.bind(this), draggable.options.delay);
     158    } else {
     159      window.focus(); // allows keypress events if window isn't currently focused, fails for Safari
     160      this.activeDraggable = draggable;
     161    }
    150162  },
    151163 
     
    161173    if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return;
    162174    this._lastPointer = pointer;
     175   
    163176    this.activeDraggable.updateDrag(event, pointer);
    164177  },
    165178 
    166179  endDrag: function(event) {
     180    if(this._timeout) {
     181      clearTimeout(this._timeout);
     182      this._timeout = null;
     183    }
    167184    if(!this.activeDraggable) return;
    168185    this._lastPointer = null;
     
    191208        if(o[eventName]) o[eventName](eventName, draggable, event);
    192209      });
     210    if(draggable.options[eventName]) draggable.options[eventName](draggable, event);
    193211  },
    194212 
     
    205223
    206224var Draggable = Class.create();
     225Draggable._dragging    = {};
     226
    207227Draggable.prototype = {
    208228  initialize: function(element) {
    209     var options = Object.extend({
     229    var defaults = {
    210230      handle: false,
    211       starteffect: function(element) {
    212         element._opacity = Element.getOpacity(element);
    213         new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7});
    214       },
    215231      reverteffect: function(element, top_offset, left_offset) {
    216232        var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;
    217         element._revert = new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur});
     233        new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur,
     234          queue: {scope:'_draggable', position:'end'}
     235        });
    218236      },
    219237      endeffect: function(element) {
    220         var toOpacity = typeof element._opacity == 'number' ? element._opacity : 1.0
    221         new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity});
     238        var toOpacity = typeof element._opacity == 'number' ? element._opacity : 1.0;
     239        new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity,
     240          queue: {scope:'_draggable', position:'end'},
     241          afterFinish: function(){
     242            Draggable._dragging[element] = false
     243          }
     244        });
    222245      },
    223246      zindex: 1000,
     
    226249      scrollSensitivity: 20,
    227250      scrollSpeed: 15,
    228       snap: false   // false, or xy or [x,y] or function(x,y){ return [x,y] }
    229     }, arguments[1] || {});
     251      snap: false,  // false, or xy or [x,y] or function(x,y){ return [x,y] }
     252      delay: 0
     253    };
     254   
     255    if(!arguments[1] || typeof arguments[1].endeffect == 'undefined')
     256      Object.extend(defaults, {
     257        starteffect: function(element) {
     258          element._opacity = Element.getOpacity(element);
     259          Draggable._dragging[element] = true;
     260          new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7});
     261        }
     262      });
     263   
     264    var options = Object.extend(defaults, arguments[1] || {});
    230265
    231266    this.element = $(element);
    232267   
    233     if(options.handle && (typeof options.handle == 'string')) {
    234       var h = Element.childrenWithClassName(this.element, options.handle, true);
    235       if(h.length>0) this.handle = h[0];
    236     }
     268    if(options.handle && (typeof options.handle == 'string'))
     269      this.handle = this.element.down('.'+options.handle, 0);
     270   
    237271    if(!this.handle) this.handle = $(options.handle);
    238272    if(!this.handle) this.handle = this.element;
    239273   
    240     if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML)
     274    if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML) {
    241275      options.scroll = $(options.scroll);
     276      this._isScrollChild = Element.childOf(this.element, options.scroll);
     277    }
    242278
    243279    Element.makePositioned(this.element); // fix IE   
     
    265301 
    266302  initDrag: function(event) {
     303    if(typeof Draggable._dragging[this.element] != 'undefined' &&
     304      Draggable._dragging[this.element]) return;
    267305    if(Event.isLeftClick(event)) {   
    268306      // abort on form elements, fixes a Firefox issue
    269307      var src = Event.element(event);
    270       if(src.tagName && (
    271         src.tagName=='INPUT' ||
    272         src.tagName=='SELECT' ||
    273         src.tagName=='OPTION' ||
    274         src.tagName=='BUTTON' ||
    275         src.tagName=='TEXTAREA')) return;
     308      if((tag_name = src.tagName.toUpperCase()) && (
     309        tag_name=='INPUT' ||
     310        tag_name=='SELECT' ||
     311        tag_name=='OPTION' ||
     312        tag_name=='BUTTON' ||
     313        tag_name=='TEXTAREA')) return;
    276314       
    277       if(this.element._revert) {
    278         this.element._revert.cancel();
    279         this.element._revert = null;
    280       }
    281      
    282315      var pointer = [Event.pointerX(event), Event.pointerY(event)];
    283316      var pos     = Position.cumulativeOffset(this.element);
     
    315348   
    316349    Draggables.notify('onStart', this, event);
     350       
    317351    if(this.options.starteffect) this.options.starteffect(this.element);
    318352  },
     
    323357    Droppables.show(pointer, this.element);
    324358    Draggables.notify('onDrag', this, event);
     359   
    325360    this.draw(pointer);
    326361    if(this.options.change) this.options.change(this);
     
    334369      } else {
    335370        p = Position.page(this.options.scroll);
    336         p[0] += this.options.scroll.scrollLeft;
    337         p[1] += this.options.scroll.scrollTop;
     371        p[0] += this.options.scroll.scrollLeft + Position.deltaX;
     372        p[1] += this.options.scroll.scrollTop + Position.deltaY;
    338373        p.push(p[0]+this.options.scroll.offsetWidth);
    339374        p.push(p[1]+this.options.scroll.offsetHeight);
     
    381416    if(this.options.endeffect)
    382417      this.options.endeffect(this.element);
    383 
     418     
    384419    Draggables.deactivate(this);
    385420    Droppables.reset();
     
    401436  draw: function(point) {
    402437    var pos = Position.cumulativeOffset(this.element);
     438    if(this.options.ghosting) {
     439      var r   = Position.realOffset(this.element);
     440      pos[0] += r[0] - Position.deltaX; pos[1] += r[1] - Position.deltaY;
     441    }
     442   
    403443    var d = this.currentDelta();
    404444    pos[0] -= d[0]; pos[1] -= d[1];
    405445   
    406     if(this.options.scroll && (this.options.scroll != window)) {
     446    if(this.options.scroll && (this.options.scroll != window && this._isScrollChild)) {
    407447      pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft;
    408448      pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop;
     
    431471    if((!this.options.constraint) || (this.options.constraint=='vertical'))
    432472      style.top  = p[1] + "px";
     473   
    433474    if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering
    434475  },
     
    443484 
    444485  startScrolling: function(speed) {
     486    if(!(speed[0] || speed[1])) return;
    445487    this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];
    446488    this.lastScrolled = new Date();
     
    467509    Droppables.show(Draggables._lastPointer, this.element);
    468510    Draggables.notify('onDrag', this);
    469     Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer);
    470     Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000;
    471     Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000;
    472     if (Draggables._lastScrollPointer[0] < 0)
    473       Draggables._lastScrollPointer[0] = 0;
    474     if (Draggables._lastScrollPointer[1] < 0)
    475       Draggables._lastScrollPointer[1] = 0;
    476     this.draw(Draggables._lastScrollPointer);
     511    if (this._isScrollChild) {
     512      Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer);
     513      Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000;
     514      Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000;
     515      if (Draggables._lastScrollPointer[0] < 0)
     516        Draggables._lastScrollPointer[0] = 0;
     517      if (Draggables._lastScrollPointer[1] < 0)
     518        Draggables._lastScrollPointer[1] = 0;
     519      this.draw(Draggables._lastScrollPointer);
     520    }
    477521   
    478522    if(this.options.change) this.options.change(this);
     
    526570
    527571var Sortable = {
     572  SERIALIZE_RULE: /^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,
     573 
    528574  sortables: {},
    529575 
    530576  _findRootElement: function(element) {
    531     while (element.tagName != "BODY") { 
     577    while (element.tagName.toUpperCase() != "BODY") { 
    532578      if(element.id && Sortable.sortables[element.id]) return element;
    533579      element = element.parentNode;
     
    566612      handle:      false,      // or a CSS class
    567613      only:        false,
     614      delay:       0,
    568615      hoverclass:  null,
    569616      ghosting:    false,
     
    571618      scrollSensitivity: 20,
    572619      scrollSpeed: 15,
    573       format:      /^[^_]*_(.*)$/,
     620      format:      this.SERIALIZE_RULE,
    574621      onChange:    Prototype.emptyFunction,
    575622      onUpdate:    Prototype.emptyFunction
     
    585632      scrollSpeed: options.scrollSpeed,
    586633      scrollSensitivity: options.scrollSensitivity,
     634      delay:       options.delay,
    587635      ghosting:    options.ghosting,
    588636      constraint:  options.constraint,
     
    613661      hoverclass:  options.hoverclass,
    614662      onHover:     Sortable.onHover
    615       //greedy:      !options.dropOnEmpty
    616663    }
    617664   
     
    638685      // handles are per-draggable
    639686      var handle = options.handle ?
    640         Element.childrenWithClassName(e, options.handle)[0] : e;   
     687        $(e).down('.'+options.handle,0) : e;   
    641688      options.draggables.push(
    642689        new Draggable(e, Object.extend(options_for_draggable, { handle: handle })));
     
    709756      var index;
    710757     
    711       var children = Sortable.findElements(dropon, {tag: droponOptions.tag});
     758      var children = Sortable.findElements(dropon, {tag: droponOptions.tag, only: droponOptions.only});
    712759      var child = null;
    713760           
     
    736783
    737784  unmark: function() {
    738     if(Sortable._marker) Element.hide(Sortable._marker);
     785    if(Sortable._marker) Sortable._marker.hide();
    739786  },
    740787
     
    745792
    746793    if(!Sortable._marker) {
    747       Sortable._marker = $('dropmarker') || document.createElement('DIV');
    748       Element.hide(Sortable._marker);
    749       Element.addClassName(Sortable._marker, 'dropmarker');
    750       Sortable._marker.style.position = 'absolute';
     794      Sortable._marker =
     795        ($('dropmarker') || Element.extend(document.createElement('DIV'))).
     796          hide().addClassName('dropmarker').setStyle({position:'absolute'});
    751797      document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);
    752798    }   
    753799    var offsets = Position.cumulativeOffset(dropon);
    754     Sortable._marker.style.left = offsets[0] + 'px';
    755     Sortable._marker.style.top = offsets[1] + 'px';
     800    Sortable._marker.setStyle({left: offsets[0]+'px', top: offsets[1] + 'px'});
    756801   
    757802    if(position=='after')
    758803      if(sortable.overlap == 'horizontal')
    759         Sortable._marker.style.left = (offsets[0]+dropon.clientWidth) + 'px';
     804        Sortable._marker.setStyle({left: (offsets[0]+dropon.clientWidth) + 'px'});
    760805      else
    761         Sortable._marker.style.top = (offsets[1]+dropon.clientHeight) + 'px';
    762    
    763     Element.show(Sortable._marker);
     806        Sortable._marker.setStyle({top: (offsets[1]+dropon.clientHeight) + 'px'});
     807   
     808    Sortable._marker.show();
    764809  },
    765810 
     
    776821        element: element,
    777822        parent: parent,
    778         children: new Array,
     823        children: [],
    779824        position: parent.children.length,
    780         container: Sortable._findChildrenElement(children[i], options.treeTag.toUpperCase())
     825        container: $(children[i]).down(options.treeTag)
    781826      }
    782827     
     
    789834
    790835    return parent;
    791   },
    792 
    793   /* Finds the first element of the given tag type within a parent element.
    794     Used for finding the first LI[ST] within a L[IST]I[TEM].*/
    795   _findChildrenElement: function (element, containerTag) {
    796     if (element && element.hasChildNodes)
    797       for (var i = 0; i < element.childNodes.length; ++i)
    798         if (element.childNodes[i].tagName == containerTag)
    799           return element.childNodes[i];
    800  
    801     return null;
    802836  },
    803837
     
    816850      id: null,
    817851      parent: null,
    818       children: new Array,
     852      children: [],
    819853      container: element,
    820854      position: 0
    821855    }
    822856   
    823     return Sortable._tree (element, options, root);
     857    return Sortable._tree(element, options, root);
    824858  },
    825859
     
    870904    if (options.tree) {
    871905      return Sortable.tree(element, arguments[1]).children.map( function (item) {
    872         return [name + Sortable._constructIndex(item) + "=" +
     906        return [name + Sortable._constructIndex(item) + "[id]=" +
    873907                encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));
    874908      }).flatten().join('&');
     
    881915}
    882916
    883 /* Returns true if child is contained within element */
     917// Returns true if child is contained within element
    884918Element.isParent = function(child, element) {
    885919  if (!child.parentNode || child == element) return false;
    886 
    887920  if (child.parentNode == element) return true;
    888 
    889921  return Element.isParent(child.parentNode, element);
    890922}
     
    909941
    910942Element.offsetSize = function (element, type) {
    911   if (type == 'vertical' || type == 'height')
    912     return element.offsetHeight;
    913   else
    914     return element.offsetWidth;
     943  return element['offset' + ((type=='vertical' || type=='height') ? 'Height' : 'Width')];
    915944}
  • tags/2.2/wp-includes/js/scriptaculous/effects.js

    r5468 r5480  
    1 // Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
     1// script.aculo.us effects.js v1.7.0, Fri Jan 19 19:16:36 CET 2007
     2
     3// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
    24// Contributors:
    35//  Justin Palmer (http://encytemedia.com/)
     
    57//  Martin Bialasinki
    68//
    7 // See scriptaculous.js for full license. 
     9// script.aculo.us is freely distributable under the terms of an MIT-style license.
     10// For details, see the script.aculo.us web site: http://script.aculo.us/
    811
    912// converts rgb() and #xxx to #xxxxxx format, 
    1013// returns self (or first argument) if not convertable 
    1114String.prototype.parseColor = function() { 
    12   var color = '#'; 
     15  var color = '#';
    1316  if(this.slice(0,4) == 'rgb(') { 
    1417    var cols = this.slice(4,this.length-1).split(','); 
     
    4245Element.setContentZoom = function(element, percent) {
    4346  element = $(element); 
    44   Element.setStyle(element, {fontSize: (percent/100) + 'em'});   
     47  element.setStyle({fontSize: (percent/100) + 'em'});   
    4548  if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0);
    46 }
    47 
    48 Element.getOpacity = function(element){ 
    49   var opacity;
    50   if (opacity = Element.getStyle(element, 'opacity')) 
    51     return parseFloat(opacity); 
    52   if (opacity = (Element.getStyle(element, 'filter') || '').match(/alpha\(opacity=(.*)\)/)) 
    53     if(opacity[1]) return parseFloat(opacity[1]) / 100; 
    54   return 1.0; 
    55 }
    56 
    57 Element.setOpacity = function(element, value){ 
    58   element= $(element); 
    59   if (value == 1){
    60     Element.setStyle(element, { opacity:
    61       (/Gecko/.test(navigator.userAgent) && !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ?
    62       0.999999 : null });
    63     if(/MSIE/.test(navigator.userAgent)) 
    64       Element.setStyle(element, {filter: Element.getStyle(element,'filter').replace(/alpha\([^\)]*\)/gi,'')}); 
    65   } else { 
    66     if(value < 0.00001) value = 0; 
    67     Element.setStyle(element, {opacity: value});
    68     if(/MSIE/.test(navigator.userAgent)) 
    69      Element.setStyle(element,
    70        { filter: Element.getStyle(element,'filter').replace(/alpha\([^\)]*\)/gi,'') +
    71                  'alpha(opacity='+value*100+')' }); 
    72   }
    73 
    74  
    75 Element.getInlineOpacity = function(element){ 
     49  return element;
     50}
     51
     52Element.getOpacity = function(element){
     53  return $(element).getStyle('opacity');
     54}
     55
     56Element.setOpacity = function(element, value){
     57  return $(element).setStyle({opacity:value});
     58}
     59
     60Element.getInlineOpacity = function(element){
    7661  return $(element).style.opacity || '';
    77 
    78 
    79 Element.childrenWithClassName = function(element, className, findFirst) {
    80   var classNameRegExp = new RegExp("(^|\\s)" + className + "(\\s|$)");
    81   var results = $A($(element).getElementsByTagName('*'))[findFirst ? 'detect' : 'select']( function(c) {
    82     return (c.className && c.className.match(classNameRegExp));
    83   });
    84   if(!results) results = [];
    85   return results;
    8662}
    8763
     
    10581
    10682var Effect = {
     83  _elementDoesNotExistError: {
     84    name: 'ElementDoesNotExistError',
     85    message: 'The specified DOM element does not exist, but is required for this effect to operate'
     86  },
    10787  tagifyText: function(element) {
     88    if(typeof Builder == 'undefined')
     89      throw("Effect.tagifyText requires including script.aculo.us' builder.js library");
     90     
    10891    var tagifyStyle = 'position:relative';
    109     if(/MSIE/.test(navigator.userAgent)) tagifyStyle += ';zoom:1';
     92    if(/MSIE/.test(navigator.userAgent) && !window.opera) tagifyStyle += ';zoom:1';
     93   
    11094    element = $(element);
    11195    $A(element.childNodes).each( function(child) {
     
    160144/* ------------- transitions ------------- */
    161145
    162 Effect.Transitions = {}
    163 
    164 Effect.Transitions.linear = function(pos) {
    165   return pos;
    166 }
    167 Effect.Transitions.sinoidal = function(pos) {
    168   return (-Math.cos(pos*Math.PI)/2) + 0.5;
    169 }
    170 Effect.Transitions.reverse  = function(pos) {
    171   return 1-pos;
    172 }
    173 Effect.Transitions.flicker = function(pos) {
    174   return ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4;
    175 }
    176 Effect.Transitions.wobble = function(pos) {
    177   return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5;
    178 }
    179 Effect.Transitions.pulse = function(pos) {
    180   return (Math.floor(pos*10) % 2 == 0 ?
    181     (pos*10-Math.floor(pos*10)) : 1-(pos*10-Math.floor(pos*10)));
    182 }
    183 Effect.Transitions.none = function(pos) {
    184   return 0;
    185 }
    186 Effect.Transitions.full = function(pos) {
    187   return 1;
    188 }
     146Effect.Transitions = {
     147  linear: Prototype.K,
     148  sinoidal: function(pos) {
     149    return (-Math.cos(pos*Math.PI)/2) + 0.5;
     150  },
     151  reverse: function(pos) {
     152    return 1-pos;
     153  },
     154  flicker: function(pos) {
     155    return ((-Math.cos(pos*Math.PI)/4) + 0.75) + Math.random()/4;
     156  },
     157  wobble: function(pos) {
     158    return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5;
     159  },
     160  pulse: function(pos, pulses) {
     161    pulses = pulses || 5;
     162    return (
     163      Math.round((pos % (1/pulses)) * pulses) == 0 ?
     164            ((pos * pulses * 2) - Math.floor(pos * pulses * 2)) :
     165        1 - ((pos * pulses * 2) - Math.floor(pos * pulses * 2))
     166      );
     167  },
     168  none: function(pos) {
     169    return 0;
     170  },
     171  full: function(pos) {
     172    return 1;
     173  }
     174};
    189175
    190176/* ------------- core effects ------------- */
     
    213199          });
    214200        break;
     201      case 'with-last':
     202        timestamp = this.effects.pluck('startOn').max() || timestamp;
     203        break;
    215204      case 'end':
    216205        // start effect after last queued effect has finished
     
    226215   
    227216    if(!this.interval)
    228       this.interval = setInterval(this.loop.bind(this), 40);
     217      this.interval = setInterval(this.loop.bind(this), 15);
    229218  },
    230219  remove: function(effect) {
     
    237226  loop: function() {
    238227    var timePos = new Date().getTime();
    239     this.effects.invoke('loop', timePos);
     228    for(var i=0, len=this.effects.length;i<len;i++)
     229      if(this.effects[i]) this.effects[i].loop(timePos);
    240230  }
    241231});
     
    257247  transition: Effect.Transitions.sinoidal,
    258248  duration:   1.0,   // seconds
    259   fps:        25.0,  // max. 25fps due to Effect.Queue implementation
     249  fps:        60.0,  // max. 60fps due to Effect.Queue implementation
    260250  sync:       false, // true for combining
    261251  from:       0.0,
     
    325315  },
    326316  inspect: function() {
    327     return '#<Effect:' + $H(this).inspect() + ',options:' + $H(this.options).inspect() + '>';
     317    var data = $H();
     318    for(property in this)
     319      if(typeof this[property] != 'function') data[property] = this[property];
     320    return '#<Effect:' + data.inspect() + ',options:' + $H(this.options).inspect() + '>';
    328321  }
    329322}
     
    349342});
    350343
     344Effect.Event = Class.create();
     345Object.extend(Object.extend(Effect.Event.prototype, Effect.Base.prototype), {
     346  initialize: function() {
     347    var options = Object.extend({
     348      duration: 0
     349    }, arguments[0] || {});
     350    this.start(options);
     351  },
     352  update: Prototype.emptyFunction
     353});
     354
    351355Effect.Opacity = Class.create();
    352356Object.extend(Object.extend(Effect.Opacity.prototype, Effect.Base.prototype), {
    353357  initialize: function(element) {
    354358    this.element = $(element);
     359    if(!this.element) throw(Effect._elementDoesNotExistError);
    355360    // make this work on IE on elements without 'layout'
    356     if(/MSIE/.test(navigator.userAgent) && (!this.element.hasLayout))
     361    if(/MSIE/.test(navigator.userAgent) && !window.opera && (!this.element.currentStyle.hasLayout))
    357362      this.element.setStyle({zoom: 1});
    358363    var options = Object.extend({
     
    371376  initialize: function(element) {
    372377    this.element = $(element);
     378    if(!this.element) throw(Effect._elementDoesNotExistError);
    373379    var options = Object.extend({
    374380      x:    0,
     
    394400  update: function(position) {
    395401    this.element.setStyle({
    396       left: this.options.x  * position + this.originalLeft + 'px',
    397       top:  this.options.y  * position + this.originalTop  + 'px'
     402      left: Math.round(this.options.x  * position + this.originalLeft) + 'px',
     403      top:  Math.round(this.options.y  * position + this.originalTop)  + 'px'
    398404    });
    399405  }
     
    409415Object.extend(Object.extend(Effect.Scale.prototype, Effect.Base.prototype), {
    410416  initialize: function(element, percent) {
    411     this.element = $(element)
     417    this.element = $(element);
     418    if(!this.element) throw(Effect._elementDoesNotExistError);
    412419    var options = Object.extend({
    413420      scaleX: true,
     
    434441   
    435442    var fontSize = this.element.getStyle('font-size') || '100%';
    436     ['em','px','%'].each( function(fontSizeType) {
     443    ['em','px','%','pt'].each( function(fontSizeType) {
    437444      if(fontSize.indexOf(fontSizeType)>0) {
    438445        this.fontSize     = parseFloat(fontSize);
     
    459466  },
    460467  finish: function(position) {
    461     if (this.restoreAfterFinish) this.element.setStyle(this.originalStyle);
     468    if(this.restoreAfterFinish) this.element.setStyle(this.originalStyle);
    462469  },
    463470  setDimensions: function(height, width) {
    464471    var d = {};
    465     if(this.options.scaleX) d.width = width + 'px';
    466     if(this.options.scaleY) d.height = height + 'px';
     472    if(this.options.scaleX) d.width = Math.round(width) + 'px';
     473    if(this.options.scaleY) d.height = Math.round(height) + 'px';
    467474    if(this.options.scaleFromCenter) {
    468475      var topd  = (height - this.dims[0])/2;
     
    484491  initialize: function(element) {
    485492    this.element = $(element);
     493    if(!this.element) throw(Effect._elementDoesNotExistError);
    486494    var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || {});
    487495    this.start(options);
     
    491499    if(this.element.getStyle('display')=='none') { this.cancel(); return; }
    492500    // Disable background image during the effect
    493     this.oldStyle = {
    494       backgroundImage: this.element.getStyle('background-image') };
    495     this.element.setStyle({backgroundImage: 'none'});
     501    this.oldStyle = {};
     502    if (!this.options.keepBackgroundImage) {
     503      this.oldStyle.backgroundImage = this.element.getStyle('background-image');
     504      this.element.setStyle({backgroundImage: 'none'});
     505    }
    496506    if(!this.options.endcolor)
    497507      this.options.endcolor = this.element.getStyle('background-color').parseColor('#ffffff');
     
    548558  afterFinishInternal: function(effect) {
    549559    if(effect.options.to!=0) return;
    550     effect.element.hide();
    551     effect.element.setStyle({opacity: oldOpacity});
     560    effect.element.hide().setStyle({opacity: oldOpacity});
    552561  }}, arguments[1] || {});
    553562  return new Effect.Opacity(element,options);
     
    564573  },
    565574  beforeSetup: function(effect) {
    566     effect.element.setOpacity(effect.options.from);
    567     effect.element.show();
     575    effect.element.setOpacity(effect.options.from).show();
    568576  }}, arguments[1] || {});
    569577  return new Effect.Opacity(element,options);
     
    572580Effect.Puff = function(element) {
    573581  element = $(element);
    574   var oldStyle = { opacity: element.getInlineOpacity(), position: element.getStyle('position') };
     582  var oldStyle = {
     583    opacity: element.getInlineOpacity(),
     584    position: element.getStyle('position'),
     585    top:  element.style.top,
     586    left: element.style.left,
     587    width: element.style.width,
     588    height: element.style.height
     589  };
    575590  return new Effect.Parallel(
    576591   [ new Effect.Scale(element, 200,
     
    579594     Object.extend({ duration: 1.0,
    580595      beforeSetupInternal: function(effect) {
    581         effect.effects[0].element.setStyle({position: 'absolute'}); },
     596        Position.absolutize(effect.effects[0].element)
     597      },
    582598      afterFinishInternal: function(effect) {
    583          effect.effects[0].element.hide();
    584          effect.effects[0].element.setStyle(oldStyle); }
     599         effect.effects[0].element.hide().setStyle(oldStyle); }
    585600     }, arguments[1] || {})
    586601   );
     
    590605  element = $(element);
    591606  element.makeClipping();
    592   return new Effect.Scale(element, 0, 
     607  return new Effect.Scale(element, 0,
    593608    Object.extend({ scaleContent: false,
    594609      scaleX: false,
    595610      restoreAfterFinish: true,
    596611      afterFinishInternal: function(effect) {
    597         effect.element.hide();
    598         effect.element.undoClipping();
     612        effect.element.hide().undoClipping();
    599613      }
    600614    }, arguments[1] || {})
     
    605619  element = $(element);
    606620  var elementDimensions = element.getDimensions();
    607   return new Effect.Scale(element, 100,
    608     Object.extend({ scaleContent: false,
    609       scaleX: false,
    610       scaleFrom: 0,
    611       scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    612       restoreAfterFinish: true,
    613       afterSetup: function(effect) {
    614         effect.element.makeClipping();
    615         effect.element.setStyle({height: '0px'});
    616         effect.element.show();
    617       }, 
    618       afterFinishInternal: function(effect) {
    619         effect.element.undoClipping();
    620       }
    621     }, arguments[1] || {})
    622   );
     621  return new Effect.Scale(element, 100, Object.extend({
     622    scaleContent: false,
     623    scaleX: false,
     624    scaleFrom: 0,
     625    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
     626    restoreAfterFinish: true,
     627    afterSetup: function(effect) {
     628      effect.element.makeClipping().setStyle({height: '0px'}).show();
     629    }, 
     630    afterFinishInternal: function(effect) {
     631      effect.element.undoClipping();
     632    }
     633  }, arguments[1] || {}));
    623634}
    624635
     
    626637  element = $(element);
    627638  var oldOpacity = element.getInlineOpacity();
    628   return new Effect.Appear(element, {
     639  return new Effect.Appear(element, Object.extend({
    629640    duration: 0.4,
    630641    from: 0,
     
    635646        scaleX: false, scaleContent: false, restoreAfterFinish: true,
    636647        beforeSetup: function(effect) {
    637           effect.element.makePositioned();
    638           effect.element.makeClipping();
     648          effect.element.makePositioned().makeClipping();
    639649        },
    640650        afterFinishInternal: function(effect) {
    641           effect.element.hide();
    642           effect.element.undoClipping();
    643           effect.element.undoPositioned();
    644           effect.element.setStyle({opacity: oldOpacity});
     651          effect.element.hide().undoClipping().undoPositioned().setStyle({opacity: oldOpacity});
    645652        }
    646653      })
    647654    }
    648   });
     655  }, arguments[1] || {}));
    649656}
    650657
     
    664671        },
    665672        afterFinishInternal: function(effect) {
    666           effect.effects[0].element.hide();
    667           effect.effects[0].element.undoPositioned();
    668           effect.effects[0].element.setStyle(oldStyle);
     673          effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);
    669674        }
    670675      }, arguments[1] || {}));
     
    688693    new Effect.Move(effect.element,
    689694      { x: -20, y: 0, duration: 0.05, afterFinishInternal: function(effect) {
    690         effect.element.undoPositioned();
    691         effect.element.setStyle(oldStyle);
     695        effect.element.undoPositioned().setStyle(oldStyle);
    692696  }}) }}) }}) }}) }}) }});
    693697}
    694698
    695699Effect.SlideDown = function(element) {
    696   element = $(element);
    697   element.cleanWhitespace();
     700  element = $(element).cleanWhitespace();
    698701  // SlideDown need to have the content of the element wrapped in a container element with fixed height!
    699   var oldInnerBottom = $(element.firstChild).getStyle('bottom');
     702  var oldInnerBottom = element.down().getStyle('bottom');
    700703  var elementDimensions = element.getDimensions();
    701704  return new Effect.Scale(element, 100, Object.extend({
     
    707710    afterSetup: function(effect) {
    708711      effect.element.makePositioned();
    709       effect.element.firstChild.makePositioned();
     712      effect.element.down().makePositioned();
    710713      if(window.opera) effect.element.setStyle({top: ''});
    711       effect.element.makeClipping();
    712       effect.element.setStyle({height: '0px'});
    713       effect.element.show(); },
     714      effect.element.makeClipping().setStyle({height: '0px'}).show();
     715    },
    714716    afterUpdateInternal: function(effect) {
    715       effect.element.firstChild.setStyle({bottom:
     717      effect.element.down().setStyle({bottom:
    716718        (effect.dims[0] - effect.element.clientHeight) + 'px' });
    717719    },
    718720    afterFinishInternal: function(effect) {
    719       effect.element.undoClipping();
    720       // IE will crash if child is undoPositioned first
    721       if(/MSIE/.test(navigator.userAgent)){
    722         effect.element.undoPositioned();
    723         effect.element.firstChild.undoPositioned();
    724       }else{
    725         effect.element.firstChild.undoPositioned();
    726         effect.element.undoPositioned();
    727       }
    728       effect.element.firstChild.setStyle({bottom: oldInnerBottom}); }
     721      effect.element.undoClipping().undoPositioned();
     722      effect.element.down().undoPositioned().setStyle({bottom: oldInnerBottom}); }
    729723    }, arguments[1] || {})
    730724  );
    731725}
    732  
     726
    733727Effect.SlideUp = function(element) {
    734   element = $(element);
    735   element.cleanWhitespace();
    736   var oldInnerBottom = $(element.firstChild).getStyle('bottom');
     728  element = $(element).cleanWhitespace();
     729  var oldInnerBottom = element.down().getStyle('bottom');
    737730  return new Effect.Scale(element, window.opera ? 0 : 1,
    738731   Object.extend({ scaleContent: false,
     
    743736    beforeStartInternal: function(effect) {
    744737      effect.element.makePositioned();
    745       effect.element.firstChild.makePositioned();
     738      effect.element.down().makePositioned();
    746739      if(window.opera) effect.element.setStyle({top: ''});
    747       effect.element.makeClipping();
    748       effect.element.show(); }, 
     740      effect.element.makeClipping().show();
     741    }, 
    749742    afterUpdateInternal: function(effect) {
    750       effect.element.firstChild.setStyle({bottom:
    751         (effect.dims[0] - effect.element.clientHeight) + 'px' }); },
     743      effect.element.down().setStyle({bottom:
     744        (effect.dims[0] - effect.element.clientHeight) + 'px' });
     745    },
    752746    afterFinishInternal: function(effect) {
    753       effect.element.hide();
    754       effect.element.undoClipping();
    755       effect.element.firstChild.undoPositioned();
    756       effect.element.undoPositioned();
    757       effect.element.setStyle({bottom: oldInnerBottom}); }
     747      effect.element.hide().undoClipping().undoPositioned().setStyle({bottom: oldInnerBottom});
     748      effect.element.down().undoPositioned();
     749    }
    758750   }, arguments[1] || {})
    759751  );
     
    762754// Bug in opera makes the TD containing this element expand for a instance after finish
    763755Effect.Squish = function(element) {
    764   return new Effect.Scale(element, window.opera ? 1 : 0,
    765     { restoreAfterFinish: true,
    766       beforeSetup: function(effect) {
    767         effect.element.makeClipping(effect.element); }, 
    768       afterFinishInternal: function(effect) {
    769         effect.element.hide(effect.element);
    770         effect.element.undoClipping(effect.element); }
     756  return new Effect.Scale(element, window.opera ? 1 : 0, {
     757    restoreAfterFinish: true,
     758    beforeSetup: function(effect) {
     759      effect.element.makeClipping();
     760    }, 
     761    afterFinishInternal: function(effect) {
     762      effect.element.hide().undoClipping();
     763    }
    771764  });
    772765}
     
    824817    duration: 0.01,
    825818    beforeSetup: function(effect) {
    826       effect.element.hide();
    827       effect.element.makeClipping();
    828       effect.element.makePositioned();
     819      effect.element.hide().makeClipping().makePositioned();
    829820    },
    830821    afterFinishInternal: function(effect) {
     
    837828        ], Object.extend({
    838829             beforeSetup: function(effect) {
    839                effect.effects[0].element.setStyle({height: '0px'});
    840                effect.effects[0].element.show();
     830               effect.effects[0].element.setStyle({height: '0px'}).show();
    841831             },
    842832             afterFinishInternal: function(effect) {
    843                effect.effects[0].element.undoClipping();
    844                effect.effects[0].element.undoPositioned();
    845                effect.effects[0].element.setStyle(oldStyle);
     833               effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle);
    846834             }
    847835           }, options)
     
    897885    ], Object.extend({           
    898886         beforeStartInternal: function(effect) {
    899            effect.effects[0].element.makePositioned();
    900            effect.effects[0].element.makeClipping(); },
     887           effect.effects[0].element.makePositioned().makeClipping();
     888         },
    901889         afterFinishInternal: function(effect) {
    902            effect.effects[0].element.hide();
    903            effect.effects[0].element.undoClipping();
    904            effect.effects[0].element.undoPositioned();
    905            effect.effects[0].element.setStyle(oldStyle); }
     890           effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle); }
    906891       }, options)
    907892  );
     
    913898  var oldOpacity = element.getInlineOpacity();
    914899  var transition = options.transition || Effect.Transitions.sinoidal;
    915   var reverser   = function(pos){ return transition(1-Effect.Transitions.pulse(pos)) };
     900  var reverser   = function(pos){ return transition(1-Effect.Transitions.pulse(pos, options.pulses)) };
    916901  reverser.bind(transition);
    917902  return new Effect.Opacity(element,
    918     Object.extend(Object.extend({  duration: 3.0, from: 0,
     903    Object.extend(Object.extend({  duration: 2.0, from: 0,
    919904      afterFinishInternal: function(effect) { effect.element.setStyle({opacity: oldOpacity}); }
    920905    }, options), {transition: reverser}));
     
    928913    width: element.style.width,
    929914    height: element.style.height };
    930   Element.makeClipping(element);
     915  element.makeClipping();
    931916  return new Effect.Scale(element, 5, Object.extend({   
    932917    scaleContent: false,
     
    937922      scaleY: false,
    938923      afterFinishInternal: function(effect) {
    939         effect.element.hide();
    940         effect.element.undoClipping();
    941         effect.element.setStyle(oldStyle);
     924        effect.element.hide().undoClipping().setStyle(oldStyle);
    942925      } });
    943926  }}, arguments[1] || {}));
    944927};
    945928
     929Effect.Morph = Class.create();
     930Object.extend(Object.extend(Effect.Morph.prototype, Effect.Base.prototype), {
     931  initialize: function(element) {
     932    this.element = $(element);
     933    if(!this.element) throw(Effect._elementDoesNotExistError);
     934    var options = Object.extend({
     935      style: {}
     936    }, arguments[1] || {});
     937    if (typeof options.style == 'string') {
     938      if(options.style.indexOf(':') == -1) {
     939        var cssText = '', selector = '.' + options.style;
     940        $A(document.styleSheets).reverse().each(function(styleSheet) {
     941          if (styleSheet.cssRules) cssRules = styleSheet.cssRules;
     942          else if (styleSheet.rules) cssRules = styleSheet.rules;
     943          $A(cssRules).reverse().each(function(rule) {
     944            if (selector == rule.selectorText) {
     945              cssText = rule.style.cssText;
     946              throw $break;
     947            }
     948          });
     949          if (cssText) throw $break;
     950        });
     951        this.style = cssText.parseStyle();
     952        options.afterFinishInternal = function(effect){
     953          effect.element.addClassName(effect.options.style);
     954          effect.transforms.each(function(transform) {
     955            if(transform.style != 'opacity')
     956              effect.element.style[transform.style.camelize()] = '';
     957          });
     958        }
     959      } else this.style = options.style.parseStyle();
     960    } else this.style = $H(options.style)
     961    this.start(options);
     962  },
     963  setup: function(){
     964    function parseColor(color){
     965      if(!color || ['rgba(0, 0, 0, 0)','transparent'].include(color)) color = '#ffffff';
     966      color = color.parseColor();
     967      return $R(0,2).map(function(i){
     968        return parseInt( color.slice(i*2+1,i*2+3), 16 )
     969      });
     970    }
     971    this.transforms = this.style.map(function(pair){
     972      var property = pair[0].underscore().dasherize(), value = pair[1], unit = null;
     973
     974      if(value.parseColor('#zzzzzz') != '#zzzzzz') {
     975        value = value.parseColor();
     976        unit  = 'color';
     977      } else if(property == 'opacity') {
     978        value = parseFloat(value);
     979        if(/MSIE/.test(navigator.userAgent) && !window.opera && (!this.element.currentStyle.hasLayout))
     980          this.element.setStyle({zoom: 1});
     981      } else if(Element.CSS_LENGTH.test(value))
     982        var components = value.match(/^([\+\-]?[0-9\.]+)(.*)$/),
     983          value = parseFloat(components[1]), unit = (components.length == 3) ? components[2] : null;
     984
     985      var originalValue = this.element.getStyle(property);
     986      return $H({
     987        style: property,
     988        originalValue: unit=='color' ? parseColor(originalValue) : parseFloat(originalValue || 0),
     989        targetValue: unit=='color' ? parseColor(value) : value,
     990        unit: unit
     991      });
     992    }.bind(this)).reject(function(transform){
     993      return (
     994        (transform.originalValue == transform.targetValue) ||
     995        (
     996          transform.unit != 'color' &&
     997          (isNaN(transform.originalValue) || isNaN(transform.targetValue))
     998        )
     999      )
     1000    });
     1001  },
     1002  update: function(position) {
     1003    var style = $H(), value = null;
     1004    this.transforms.each(function(transform){
     1005      value = transform.unit=='color' ?
     1006        $R(0,2).inject('#',function(m,v,i){
     1007          return m+(Math.round(transform.originalValue[i]+
     1008            (transform.targetValue[i] - transform.originalValue[i])*position)).toColorPart() }) :
     1009        transform.originalValue + Math.round(
     1010          ((transform.targetValue - transform.originalValue) * position) * 1000)/1000 + transform.unit;
     1011      style[transform.style] = value;
     1012    });
     1013    this.element.setStyle(style);
     1014  }
     1015});
     1016
     1017Effect.Transform = Class.create();
     1018Object.extend(Effect.Transform.prototype, {
     1019  initialize: function(tracks){
     1020    this.tracks  = [];
     1021    this.options = arguments[1] || {};
     1022    this.addTracks(tracks);
     1023  },
     1024  addTracks: function(tracks){
     1025    tracks.each(function(track){
     1026      var data = $H(track).values().first();
     1027      this.tracks.push($H({
     1028        ids:     $H(track).keys().first(),
     1029        effect:  Effect.Morph,
     1030        options: { style: data }
     1031      }));
     1032    }.bind(this));
     1033    return this;
     1034  },
     1035  play: function(){
     1036    return new Effect.Parallel(
     1037      this.tracks.map(function(track){
     1038        var elements = [$(track.ids) || $$(track.ids)].flatten();
     1039        return elements.map(function(e){ return new track.effect(e, Object.extend({ sync:true }, track.options)) });
     1040      }).flatten(),
     1041      this.options
     1042    );
     1043  }
     1044});
     1045
     1046Element.CSS_PROPERTIES = $w(
     1047  'backgroundColor backgroundPosition borderBottomColor borderBottomStyle ' +
     1048  'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth ' +
     1049  'borderRightColor borderRightStyle borderRightWidth borderSpacing ' +
     1050  'borderTopColor borderTopStyle borderTopWidth bottom clip color ' +
     1051  'fontSize fontWeight height left letterSpacing lineHeight ' +
     1052  'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+
     1053  'maxWidth minHeight minWidth opacity outlineColor outlineOffset ' +
     1054  'outlineWidth paddingBottom paddingLeft paddingRight paddingTop ' +
     1055  'right textIndent top width wordSpacing zIndex');
     1056 
     1057Element.CSS_LENGTH = /^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;
     1058
     1059String.prototype.parseStyle = function(){
     1060  var element = Element.extend(document.createElement('div'));
     1061  element.innerHTML = '<div style="' + this + '"></div>';
     1062  var style = element.down().style, styleRules = $H();
     1063 
     1064  Element.CSS_PROPERTIES.each(function(property){
     1065    if(style[property]) styleRules[property] = style[property];
     1066  });
     1067  if(/MSIE/.test(navigator.userAgent) && !window.opera && this.indexOf('opacity') > -1) {
     1068    styleRules.opacity = this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1];
     1069  }
     1070  return styleRules;
     1071};
     1072
     1073Element.morph = function(element, style) {
     1074  new Effect.Morph(element, Object.extend({ style: style }, arguments[2] || {}));
     1075  return element;
     1076};
     1077
    9461078['setOpacity','getOpacity','getInlineOpacity','forceRerendering','setContentZoom',
    947  'collectTextNodes','collectTextNodesIgnoreClass','childrenWithClassName'].each(
     1079 'collectTextNodes','collectTextNodesIgnoreClass','morph'].each(
    9481080  function(f) { Element.Methods[f] = Element[f]; }
    9491081);
  • tags/2.2/wp-includes/js/scriptaculous/prototype.js

    r5468 r5480  
    1 /*  Prototype JavaScript framework, version 1.5.0_rc0
    2  *  (c) 2005 Sam Stephenson <sam@conio.net>
     1/*  Prototype JavaScript framework, version 1.5.0
     2 *  (c) 2005-2007 Sam Stephenson
    33 *
    44 *  Prototype is freely distributable under the terms of an MIT-style license.
     
    88
    99var Prototype = {
    10   Version: '1.5.0_rc0',
     10  Version: '1.5.0',
     11  BrowserFeatures: {
     12    XPath: !!document.evaluate
     13  },
     14
    1115  ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',
    12 
    1316  emptyFunction: function() {},
    14   K: function(x) {return x}
     17  K: function(x) { return x }
    1518}
    1619
     
    3235}
    3336
    34 Object.inspect = function(object) {
    35   try {
    36     if (object == undefined) return 'undefined';
    37     if (object == null) return 'null';
    38     return object.inspect ? object.inspect() : object.toString();
    39   } catch (e) {
    40     if (e instanceof RangeError) return '...';
    41     throw e;
    42   }
    43 }
     37Object.extend(Object, {
     38  inspect: function(object) {
     39    try {
     40      if (object === undefined) return 'undefined';
     41      if (object === null) return 'null';
     42      return object.inspect ? object.inspect() : object.toString();
     43    } catch (e) {
     44      if (e instanceof RangeError) return '...';
     45      throw e;
     46    }
     47  },
     48
     49  keys: function(object) {
     50    var keys = [];
     51    for (var property in object)
     52      keys.push(property);
     53    return keys;
     54  },
     55
     56  values: function(object) {
     57    var values = [];
     58    for (var property in object)
     59      values.push(object[property]);
     60    return values;
     61  },
     62
     63  clone: function(object) {
     64    return Object.extend({}, object);
     65  }
     66});
    4467
    4568Function.prototype.bind = function() {
     
    5174
    5275Function.prototype.bindAsEventListener = function(object) {
    53   var __method = this;
     76  var __method = this, args = $A(arguments), object = args.shift();
    5477  return function(event) {
    55     return __method.call(object, event || window.event);
     78    return __method.apply(object, [( event || window.event)].concat(args).concat($A(arguments)));
    5679  }
    5780}
     
    78101    var returnValue;
    79102
    80     for (var i = 0; i < arguments.length; i++) {
     103    for (var i = 0, length = arguments.length; i < length; i++) {
    81104      var lambda = arguments[i];
    82105      try {
     
    103126
    104127  registerCallback: function() {
    105     setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
     128    this.timer = setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
     129  },
     130
     131  stop: function() {
     132    if (!this.timer) return;
     133    clearInterval(this.timer);
     134    this.timer = null;
    106135  },
    107136
     
    110139      try {
    111140        this.currentlyExecuting = true;
    112         this.callback();
     141        this.callback(this);
    113142      } finally {
    114143        this.currentlyExecuting = false;
     
    117146  }
    118147}
     148String.interpret = function(value){
     149  return value == null ? '' : String(value);
     150}
     151
    119152Object.extend(String.prototype, {
    120153  gsub: function(pattern, replacement) {
     
    125158      if (match = source.match(pattern)) {
    126159        result += source.slice(0, match.index);
    127         result += (replacement(match) || '').toString();
     160        result += String.interpret(replacement(match));
    128161        source  = source.slice(match.index + match[0].length);
    129162      } else {
     
    190223    var div = document.createElement('div');
    191224    div.innerHTML = this.stripTags();
    192     return div.childNodes[0] ? div.childNodes[0].nodeValue : '';
    193   },
    194 
    195   toQueryParams: function() {
    196     var pairs = this.match(/^\??(.*)$/)[1].split('&');
    197     return pairs.inject({}, function(params, pairString) {
    198       var pair = pairString.split('=');
    199       params[pair[0]] = pair[1];
    200       return params;
     225    return div.childNodes[0] ? (div.childNodes.length > 1 ?
     226      $A(div.childNodes).inject('',function(memo,node){ return memo+node.nodeValue }) :
     227      div.childNodes[0].nodeValue) : '';
     228  },
     229
     230  toQueryParams: function(separator) {
     231    var match = this.strip().match(/([^?#]*)(#.*)?$/);
     232    if (!match) return {};
     233
     234    return match[1].split(separator || '&').inject({}, function(hash, pair) {
     235      if ((pair = pair.split('='))[0]) {
     236        var name = decodeURIComponent(pair[0]);
     237        var value = pair[1] ? decodeURIComponent(pair[1]) : undefined;
     238
     239        if (hash[name] !== undefined) {
     240          if (hash[name].constructor != Array)
     241            hash[name] = [hash[name]];
     242          if (value) hash[name].push(value);
     243        }
     244        else hash[name] = value;
     245      }
     246      return hash;
    201247    });
    202248  },
     
    206252  },
    207253
     254  succ: function() {
     255    return this.slice(0, this.length - 1) +
     256      String.fromCharCode(this.charCodeAt(this.length - 1) + 1);
     257  },
     258
    208259  camelize: function() {
    209     var oStringList = this.split('-');
    210     if (oStringList.length == 1) return oStringList[0];
    211 
    212     var camelizedString = this.indexOf('-') == 0
    213       ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1)
    214       : oStringList[0];
    215 
    216     for (var i = 1, len = oStringList.length; i < len; i++) {
    217       var s = oStringList[i];
    218       camelizedString += s.charAt(0).toUpperCase() + s.substring(1);
    219     }
    220 
    221     return camelizedString;
    222   },
    223 
    224   inspect: function() {
    225     return "'" + this.replace(/\\/g, '\\\\').replace(/'/g, '\\\'') + "'";
     260    var parts = this.split('-'), len = parts.length;
     261    if (len == 1) return parts[0];
     262
     263    var camelized = this.charAt(0) == '-'
     264      ? parts[0].charAt(0).toUpperCase() + parts[0].substring(1)
     265      : parts[0];
     266
     267    for (var i = 1; i < len; i++)
     268      camelized += parts[i].charAt(0).toUpperCase() + parts[i].substring(1);
     269
     270    return camelized;
     271  },
     272
     273  capitalize: function(){
     274    return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
     275  },
     276
     277  underscore: function() {
     278    return this.gsub(/::/, '/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();
     279  },
     280
     281  dasherize: function() {
     282    return this.gsub(/_/,'-');
     283  },
     284
     285  inspect: function(useDoubleQuotes) {
     286    var escapedString = this.replace(/\\/g, '\\\\');
     287    if (useDoubleQuotes)
     288      return '"' + escapedString.replace(/"/g, '\\"') + '"';
     289    else
     290      return "'" + escapedString.replace(/'/g, '\\\'') + "'";
    226291  }
    227292});
     
    247312      var before = match[1];
    248313      if (before == '\\') return match[2];
    249       return before + (object[match[3]] || '').toString();
     314      return before + String.interpret(object[match[3]]);
    250315    });
    251316  }
     
    269334      if (e != $break) throw e;
    270335    }
     336    return this;
     337  },
     338
     339  eachSlice: function(number, iterator) {
     340    var index = -number, slices = [], array = this.toArray();
     341    while ((index += number) < array.length)
     342      slices.push(array.slice(index, index+number));
     343    return slices.map(iterator);
    271344  },
    272345
     
    281354
    282355  any: function(iterator) {
    283     var result = true;
     356    var result = false;
    284357    this.each(function(value, index) {
    285358      if (result = !!(iterator || Prototype.K)(value, index))
     
    292365    var results = [];
    293366    this.each(function(value, index) {
    294       results.push(iterator(value, index));
     367      results.push((iterator || Prototype.K)(value, index));
    295368    });
    296369    return results;
    297370  },
    298371
    299   detect: function (iterator) {
     372  detect: function(iterator) {
    300373    var result;
    301374    this.each(function(value, index) {
     
    338411  },
    339412
     413  inGroupsOf: function(number, fillWith) {
     414    fillWith = fillWith === undefined ? null : fillWith;
     415    return this.eachSlice(number, function(slice) {
     416      while(slice.length < number) slice.push(fillWith);
     417      return slice;
     418    });
     419  },
     420
    340421  inject: function(memo, iterator) {
    341422    this.each(function(value, index) {
     
    347428  invoke: function(method) {
    348429    var args = $A(arguments).slice(1);
    349     return this.collect(function(value) {
     430    return this.map(function(value) {
    350431      return value[method].apply(value, args);
    351432    });
     
    399480
    400481  sortBy: function(iterator) {
    401     return this.collect(function(value, index) {
     482    return this.map(function(value, index) {
    402483      return {value: value, criteria: iterator(value, index)};
    403484    }).sort(function(left, right) {
     
    408489
    409490  toArray: function() {
    410     return this.collect(Prototype.K);
     491    return this.map();
    411492  },
    412493
     
    420501      return iterator(collections.pluck(index));
    421502    });
     503  },
     504
     505  size: function() {
     506    return this.toArray().length;
    422507  },
    423508
     
    440525  } else {
    441526    var results = [];
    442     for (var i = 0; i < iterable.length; i++)
     527    for (var i = 0, length = iterable.length; i < length; i++)
    443528      results.push(iterable[i]);
    444529    return results;
     
    453538Object.extend(Array.prototype, {
    454539  _each: function(iterator) {
    455     for (var i = 0; i < this.length; i++)
     540    for (var i = 0, length = this.length; i < length; i++)
    456541      iterator(this[i]);
    457542  },
     
    472557  compact: function() {
    473558    return this.select(function(value) {
    474       return value != undefined || value != null;
     559      return value != null;
    475560    });
    476561  },
     
    491576
    492577  indexOf: function(object) {
    493     for (var i = 0; i < this.length; i++)
     578    for (var i = 0, length = this.length; i < length; i++)
    494579      if (this[i] == object) return i;
    495580    return -1;
     
    500585  },
    501586
     587  reduce: function() {
     588    return this.length > 1 ? this : this[0];
     589  },
     590
     591  uniq: function() {
     592    return this.inject([], function(array, value) {
     593      return array.include(value) ? array : array.concat([value]);
     594    });
     595  },
     596
     597  clone: function() {
     598    return [].concat(this);
     599  },
     600
     601  size: function() {
     602    return this.length;
     603  },
     604
    502605  inspect: function() {
    503606    return '[' + this.map(Object.inspect).join(', ') + ']';
    504607  }
    505608});
    506 var Hash = {
     609
     610Array.prototype.toArray = Array.prototype.clone;
     611
     612function $w(string){
     613  string = string.strip();
     614  return string ? string.split(/\s+/) : [];
     615}
     616
     617if(window.opera){
     618  Array.prototype.concat = function(){
     619    var array = [];
     620    for(var i = 0, length = this.length; i < length; i++) array.push(this[i]);
     621    for(var i = 0, length = arguments.length; i < length; i++) {
     622      if(arguments[i].constructor == Array) {
     623        for(var j = 0, arrayLength = arguments[i].length; j < arrayLength; j++)
     624          array.push(arguments[i][j]);
     625      } else {
     626        array.push(arguments[i]);
     627      }
     628    }
     629    return array;
     630  }
     631}
     632var Hash = function(obj) {
     633  Object.extend(this, obj || {});
     634};
     635
     636Object.extend(Hash, {
     637  toQueryString: function(obj) {
     638    var parts = [];
     639
     640      this.prototype._each.call(obj, function(pair) {
     641      if (!pair.key) return;
     642
     643      if (pair.value && pair.value.constructor == Array) {
     644        var values = pair.value.compact();
     645        if (values.length < 2) pair.value = values.reduce();
     646        else {
     647            key = encodeURIComponent(pair.key);
     648          values.each(function(value) {
     649            value = value != undefined ? encodeURIComponent(value) : '';
     650            parts.push(key + '=' + encodeURIComponent(value));
     651          });
     652          return;
     653        }
     654      }
     655      if (pair.value == undefined) pair[1] = '';
     656      parts.push(pair.map(encodeURIComponent).join('='));
     657      });
     658
     659    return parts.join('&');
     660  }
     661});
     662
     663Object.extend(Hash.prototype, Enumerable);
     664Object.extend(Hash.prototype, {
    507665  _each: function(iterator) {
    508666    for (var key in this) {
    509667      var value = this[key];
    510       if (typeof value == 'function') continue;
     668      if (value && value == Hash.prototype[key]) continue;
    511669
    512670      var pair = [key, value];
     
    526684
    527685  merge: function(hash) {
    528     return $H(hash).inject($H(this), function(mergedHash, pair) {
     686    return $H(hash).inject(this, function(mergedHash, pair) {
    529687      mergedHash[pair.key] = pair.value;
    530688      return mergedHash;
     
    532690  },
    533691
     692  remove: function() {
     693    var result;
     694    for(var i = 0, length = arguments.length; i < length; i++) {
     695      var value = this[arguments[i]];
     696      if (value !== undefined){
     697        if (result === undefined) result = value;
     698        else {
     699          if (result.constructor != Array) result = [result];
     700          result.push(value)
     701        }
     702      }
     703      delete this[arguments[i]];
     704    }
     705    return result;
     706  },
     707
    534708  toQueryString: function() {
    535     return this.map(function(pair) {
    536       return pair.map(encodeURIComponent).join('=');
    537     }).join('&');
     709    return Hash.toQueryString(this);
    538710  },
    539711
     
    543715    }).join(', ') + '}>';
    544716  }
    545 }
     717});
    546718
    547719function $H(object) {
    548   var hash = Object.extend({}, object || {});
    549   Object.extend(hash, Enumerable);
    550   Object.extend(hash, Hash);
    551   return hash;
    552 }
     720  if (object && object.constructor == Hash) return object;
     721  return new Hash(object);
     722};
    553723ObjectRange = Class.create();
    554724Object.extend(ObjectRange.prototype, Enumerable);
     
    562732  _each: function(iterator) {
    563733    var value = this.start;
    564     do {
     734    while (this.include(value)) {
    565735      iterator(value);
    566736      value = value.succ();
    567     } while (this.include(value));
     737    }
    568738  },
    569739
     
    600770  },
    601771
    602   register: function(responderToAdd) {
    603     if (!this.include(responderToAdd))
    604       this.responders.push(responderToAdd);
    605   },
    606 
    607   unregister: function(responderToRemove) {
    608     this.responders = this.responders.without(responderToRemove);
     772  register: function(responder) {
     773    if (!this.include(responder))
     774      this.responders.push(responder);
     775  },
     776
     777  unregister: function(responder) {
     778    this.responders = this.responders.without(responder);
    609779  },
    610780
    611781  dispatch: function(callback, request, transport, json) {
    612782    this.each(function(responder) {
    613       if (responder[callback] && typeof responder[callback] == 'function') {
     783      if (typeof responder[callback] == 'function') {
    614784        try {
    615785          responder[callback].apply(responder, [request, transport, json]);
     
    626796    Ajax.activeRequestCount++;
    627797  },
    628 
    629798  onComplete: function() {
    630799    Ajax.activeRequestCount--;
     
    639808      asynchronous: true,
    640809      contentType:  'application/x-www-form-urlencoded',
     810      encoding:     'UTF-8',
    641811      parameters:   ''
    642812    }
    643813    Object.extend(this.options, options || {});
    644   },
    645 
    646   responseIsSuccess: function() {
    647     return this.transport.status == undefined
    648         || this.transport.status == 0
    649         || (this.transport.status >= 200 && this.transport.status < 300);
    650   },
    651 
    652   responseIsFailure: function() {
    653     return !this.responseIsSuccess();
     814
     815    this.options.method = this.options.method.toLowerCase();
     816    if (typeof this.options.parameters == 'string')
     817      this.options.parameters = this.options.parameters.toQueryParams();
    654818  }
    655819}
     
    660824
    661825Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
     826  _complete: false,
     827
    662828  initialize: function(url, options) {
    663829    this.transport = Ajax.getTransport();
     
    667833
    668834  request: function(url) {
    669     var parameters = this.options.parameters || '';
    670     if (parameters.length > 0) parameters += '&_=';
     835    this.url = url;
     836    this.method = this.options.method;
     837    var params = this.options.parameters;
     838
     839    if (!['get', 'post'].include(this.method)) {
     840      // simulate other verbs over post
     841      params['_method'] = this.method;
     842      this.method = 'post';
     843    }
     844
     845    params = Hash.toQueryString(params);
     846    if (params && /Konqueror|Safari|KHTML/.test(navigator.userAgent)) params += '&_='
     847
     848    // when GET, append parameters to URL
     849    if (this.method == 'get' && params)
     850      this.url += (this.url.indexOf('?') > -1 ? '&' : '?') + params;
    671851
    672852    try {
    673       this.url = url;
    674       if (this.options.method == 'get' && parameters.length > 0)
    675         this.url += (this.url.match(/\?/) ? '&' : '?') + parameters;
    676 
    677853      Ajax.Responders.dispatch('onCreate', this, this.transport);
    678854
    679       this.transport.open(this.options.method, this.url,
     855      this.transport.open(this.method.toUpperCase(), this.url,
    680856        this.options.asynchronous);
    681857
    682       if (this.options.asynchronous) {
    683         this.transport.onreadystatechange = this.onStateChange.bind(this);
    684         setTimeout((function() {this.respondToReadyState(1)}).bind(this), 10);
     858      if (this.options.asynchronous)
     859        setTimeout(function() { this.respondToReadyState(1) }.bind(this), 10);
     860
     861      this.transport.onreadystatechange = this.onStateChange.bind(this);
     862      this.setRequestHeaders();
     863
     864      var body = this.method == 'post' ? (this.options.postBody || params) : null;
     865
     866      this.transport.send(body);
     867
     868      /* Force Firefox to handle ready state 4 for synchronous requests */
     869      if (!this.options.asynchronous && this.transport.overrideMimeType)
     870        this.onStateChange();
     871
     872    }
     873    catch (e) {
     874      this.dispatchException(e);
     875    }
     876  },
     877
     878  onStateChange: function() {
     879    var readyState = this.transport.readyState;
     880    if (readyState > 1 && !((readyState == 4) && this._complete))
     881      this.respondToReadyState(this.transport.readyState);
     882  },
     883
     884  setRequestHeaders: function() {
     885    var headers = {
     886      'X-Requested-With': 'XMLHttpRequest',
     887      'X-Prototype-Version': Prototype.Version,
     888      'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
     889    };
     890
     891    if (this.method == 'post') {
     892      headers['Content-type'] = this.options.contentType +
     893        (this.options.encoding ? '; charset=' + this.options.encoding : '');
     894
     895      /* Force "Connection: close" for older Mozilla browsers to work
     896       * around a bug where XMLHttpRequest sends an incorrect
     897       * Content-length header. See Mozilla Bugzilla #246651.
     898       */
     899      if (this.transport.overrideMimeType &&
     900          (navigator.userAgent.match(/Gecko\/(\d{4})/) || [0,2005])[1] < 2005)
     901            headers['Connection'] = 'close';
     902    }
     903
     904    // user-defined headers
     905    if (typeof this.options.requestHeaders == 'object') {
     906      var extras = this.options.requestHeaders;
     907
     908      if (typeof extras.push == 'function')
     909        for (var i = 0, length = extras.length; i < length; i += 2)
     910          headers[extras[i]] = extras[i+1];
     911      else
     912        $H(extras).each(function(pair) { headers[pair.key] = pair.value });
     913    }
     914
     915    for (var name in headers)
     916      this.transport.setRequestHeader(name, headers[name]);
     917  },
     918
     919  success: function() {
     920    return !this.transport.status
     921        || (this.transport.status >= 200 && this.transport.status < 300);
     922  },
     923
     924  respondToReadyState: function(readyState) {
     925    var state = Ajax.Request.Events[readyState];
     926    var transport = this.transport, json = this.evalJSON();
     927
     928    if (state == 'Complete') {
     929      try {
     930        this._complete = true;
     931        (this.options['on' + this.transport.status]
     932         || this.options['on' + (this.success() ? 'Success' : 'Failure')]
     933         || Prototype.emptyFunction)(transport, json);
     934      } catch (e) {
     935        this.dispatchException(e);
    685936      }
    686937
    687       this.setRequestHeaders();
    688 
    689       var body = this.options.postBody ? this.options.postBody : parameters;
    690       this.transport.send(this.options.method == 'post' ? body : null);
    691 
     938      if ((this.getHeader('Content-type') || 'text/javascript').strip().
     939        match(/^(text|application)\/(x-)?(java|ecma)script(;.*)?$/i))
     940          this.evalResponse();
     941    }
     942
     943    try {
     944      (this.options['on' + state] || Prototype.emptyFunction)(transport, json);
     945      Ajax.Responders.dispatch('on' + state, this, transport, json);
    692946    } catch (e) {
    693947      this.dispatchException(e);
    694948    }
    695   },
    696 
    697   setRequestHeaders: function() {
    698     var requestHeaders =
    699       ['X-Requested-With', 'XMLHttpRequest',
    700        'X-Prototype-Version', Prototype.Version,
    701        'Accept', 'text/javascript, text/html, application/xml, text/xml, */*'];
    702 
    703     if (this.options.method == 'post') {
    704       requestHeaders.push('Content-type', this.options.contentType);
    705 
    706       /* Force "Connection: close" for Mozilla browsers to work around
    707        * a bug where XMLHttpReqeuest sends an incorrect Content-length
    708        * header. See Mozilla Bugzilla #246651.
    709        */
    710       if (this.transport.overrideMimeType)
    711         requestHeaders.push('Connection', 'close');
    712     }
    713 
    714     if (this.options.requestHeaders)
    715       requestHeaders.push.apply(requestHeaders, this.options.requestHeaders);
    716 
    717     for (var i = 0; i < requestHeaders.length; i += 2)
    718       this.transport.setRequestHeader(requestHeaders[i], requestHeaders[i+1]);
    719   },
    720 
    721   onStateChange: function() {
    722     var readyState = this.transport.readyState;
    723     if (readyState != 1)
    724       this.respondToReadyState(this.transport.readyState);
    725   },
    726 
    727   header: function(name) {
     949
     950    if (state == 'Complete') {
     951      // avoid memory leak in MSIE: clean up
     952      this.transport.onreadystatechange = Prototype.emptyFunction;
     953    }
     954  },
     955
     956  getHeader: function(name) {
    728957    try {
    729958      return this.transport.getResponseHeader(name);
    730     } catch (e) {}
     959    } catch (e) { return null }
    731960  },
    732961
    733962  evalJSON: function() {
    734963    try {
    735       return eval('(' + this.header('X-JSON') + ')');
    736     } catch (e) {}
     964      var json = this.getHeader('X-JSON');
     965      return json ? eval('(' + json + ')') : null;
     966    } catch (e) { return null }
    737967  },
    738968
     
    745975  },
    746976
    747   respondToReadyState: function(readyState) {
    748     var event = Ajax.Request.Events[readyState];
    749     var transport = this.transport, json = this.evalJSON();
    750 
    751     if (event == 'Complete') {
    752       try {
    753         (this.options['on' + this.transport.status]
    754          || this.options['on' + (this.responseIsSuccess() ? 'Success' : 'Failure')]
    755          || Prototype.emptyFunction)(transport, json);
    756       } catch (e) {
    757         this.dispatchException(e);
    758       }
    759 
    760       if ((this.header('Content-type') || '').match(/^text\/javascript/i))
    761         this.evalResponse();
    762     }
    763 
    764     try {
    765       (this.options['on' + event] || Prototype.emptyFunction)(transport, json);
    766       Ajax.Responders.dispatch('on' + event, this, transport, json);
    767     } catch (e) {
    768       this.dispatchException(e);
    769     }
    770 
    771     /* Avoid memory leak in MSIE: clean up the oncomplete event handler */
    772     if (event == 'Complete')
    773       this.transport.onreadystatechange = Prototype.emptyFunction;
    774   },
    775 
    776977  dispatchException: function(exception) {
    777978    (this.options.onException || Prototype.emptyFunction)(this, exception);
     
    784985Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
    785986  initialize: function(container, url, options) {
    786     this.containers = {
    787       success: container.success ? $(container.success) : $(container),
    788       failure: container.failure ? $(container.failure) :
    789         (container.success ? null : $(container))
     987    this.container = {
     988      success: (container.success || container),
     989      failure: (container.failure || (container.success ? null : container))
    790990    }
    791991
     
    794994
    795995    var onComplete = this.options.onComplete || Prototype.emptyFunction;
    796     this.options.onComplete = (function(transport, object) {
     996    this.options.onComplete = (function(transport, param) {
    797997      this.updateContent();
    798       onComplete(transport, object);
     998      onComplete(transport, param);
    799999    }).bind(this);
    8001000
     
    8031003
    8041004  updateContent: function() {
    805     var receiver = this.responseIsSuccess() ?
    806       this.containers.success : this.containers.failure;
     1005    var receiver = this.container[this.success() ? 'success' : 'failure'];
    8071006    var response = this.transport.responseText;
    8081007
    809     if (!this.options.evalScripts)
    810       response = response.stripScripts();
    811 
    812     if (receiver) {
    813       if (this.options.insertion) {
     1008    if (!this.options.evalScripts) response = response.stripScripts();
     1009
     1010    if (receiver = $(receiver)) {
     1011      if (this.options.insertion)
    8141012        new this.options.insertion(receiver, response);
    815       } else {
    816         Element.update(receiver, response);
    817       }
    818     }
    819 
    820     if (this.responseIsSuccess()) {
     1013      else
     1014        receiver.update(response);
     1015    }
     1016
     1017    if (this.success()) {
    8211018      if (this.onComplete)
    8221019        setTimeout(this.onComplete.bind(this), 10);
     
    8471044
    8481045  stop: function() {
    849     this.updater.onComplete = undefined;
     1046    this.updater.options.onComplete = undefined;
    8501047    clearTimeout(this.timer);
    8511048    (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
     
    8671064  }
    8681065});
    869 function $() {
    870   var results = [], element;
    871   for (var i = 0; i < arguments.length; i++) {
    872     element = arguments[i];
    873     if (typeof element == 'string')
    874       element = document.getElementById(element);
    875     results.push(Element.extend(element));
    876   }
    877   return results.length < 2 ? results[0] : results;
     1066function $(element) {
     1067  if (arguments.length > 1) {
     1068    for (var i = 0, elements = [], length = arguments.length; i < length; i++)
     1069      elements.push($(arguments[i]));
     1070    return elements;
     1071  }
     1072  if (typeof element == 'string')
     1073    element = document.getElementById(element);
     1074  return Element.extend(element);
     1075}
     1076
     1077if (Prototype.BrowserFeatures.XPath) {
     1078  document._getElementsByXPath = function(expression, parentElement) {
     1079    var results = [];
     1080    var query = document.evaluate(expression, $(parentElement) || document,
     1081      null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
     1082    for (var i = 0, length = query.snapshotLength; i < length; i++)
     1083      results.push(query.snapshotItem(i));
     1084    return results;
     1085  };
    8781086}
    8791087
    8801088document.getElementsByClassName = function(className, parentElement) {
    881   var children = ($(parentElement) || document.body).getElementsByTagName('*');
    882   return $A(children).inject([], function(elements, child) {
    883     if (child.className.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
    884       elements.push(Element.extend(child));
     1089  if (Prototype.BrowserFeatures.XPath) {
     1090    var q = ".//*[contains(concat(' ', @class, ' '), ' " + className + " ')]";
     1091    return document._getElementsByXPath(q, parentElement);
     1092  } else {
     1093    var children = ($(parentElement) || document.body).getElementsByTagName('*');
     1094    var elements = [], child;
     1095    for (var i = 0, length = children.length; i < length; i++) {
     1096      child = children[i];
     1097      if (Element.hasClassName(child, className))
     1098        elements.push(Element.extend(child));
     1099    }
    8851100    return elements;
    886   });
    887 }
     1101  }
     1102};
    8881103
    8891104/*--------------------------------------------------------------------------*/
     
    8931108
    8941109Element.extend = function(element) {
    895   if (!element) return;
    896   if (_nativeExtensions) return element;
     1110  if (!element || _nativeExtensions || element.nodeType == 3) return element;
    8971111
    8981112  if (!element._extended && element.tagName && element != window) {
    899     var methods = Element.Methods, cache = Element.extend.cache;
    900     for (property in methods) {
     1113    var methods = Object.clone(Element.Methods), cache = Element.extend.cache;
     1114
     1115    if (element.tagName == 'FORM')
     1116      Object.extend(methods, Form.Methods);
     1117    if (['INPUT', 'TEXTAREA', 'SELECT'].include(element.tagName))
     1118      Object.extend(methods, Form.Element.Methods);
     1119
     1120    Object.extend(methods, Element.Methods.Simulated);
     1121
     1122    for (var property in methods) {
    9011123      var value = methods[property];
    902       if (typeof value == 'function')
     1124      if (typeof value == 'function' && !(property in element))
    9031125        element[property] = cache.findOrStore(value);
    9041126    }
     
    9071129  element._extended = true;
    9081130  return element;
    909 }
     1131};
    9101132
    9111133Element.extend.cache = {
     
    9151137    }
    9161138  }
    917 }
     1139};
    9181140
    9191141Element.Methods = {
     
    9221144  },
    9231145
    924   toggle: function() {
    925     for (var i = 0; i < arguments.length; i++) {
    926       var element = $(arguments[i]);
    927       Element[Element.visible(element) ? 'hide' : 'show'](element);
    928     }
    929   },
    930 
    931   hide: function() {
    932     for (var i = 0; i < arguments.length; i++) {
    933       var element = $(arguments[i]);
    934       element.style.display = 'none';
    935     }
    936   },
    937 
    938   show: function() {
    939     for (var i = 0; i < arguments.length; i++) {
    940       var element = $(arguments[i]);
    941       element.style.display = '';
    942     }
     1146  toggle: function(element) {
     1147    element = $(element);
     1148    Element[Element.visible(element) ? 'hide' : 'show'](element);
     1149    return element;
     1150  },
     1151
     1152  hide: function(element) {
     1153    $(element).style.display = 'none';
     1154    return element;
     1155  },
     1156
     1157  show: function(element) {
     1158    $(element).style.display = '';
     1159    return element;
    9431160  },
    9441161
     
    9461163    element = $(element);
    9471164    element.parentNode.removeChild(element);
     1165    return element;
    9481166  },
    9491167
    9501168  update: function(element, html) {
     1169    html = typeof html == 'undefined' ? '' : html.toString();
    9511170    $(element).innerHTML = html.stripScripts();
    9521171    setTimeout(function() {html.evalScripts()}, 10);
     1172    return element;
    9531173  },
    9541174
    9551175  replace: function(element, html) {
    9561176    element = $(element);
     1177    html = typeof html == 'undefined' ? '' : html.toString();
    9571178    if (element.outerHTML) {
    9581179      element.outerHTML = html.stripScripts();
     
    9641185    }
    9651186    setTimeout(function() {html.evalScripts()}, 10);
     1187    return element;
     1188  },
     1189
     1190  inspect: function(element) {
     1191    element = $(element);
     1192    var result = '<' + element.tagName.toLowerCase();
     1193    $H({'id': 'id', 'className': 'class'}).each(function(pair) {
     1194      var property = pair.first(), attribute = pair.last();
     1195      var value = (element[property] || '').toString();
     1196      if (value) result += ' ' + attribute + '=' + value.inspect(true);
     1197    });
     1198    return result + '>';
     1199  },
     1200
     1201  recursivelyCollect: function(element, property) {
     1202    element = $(element);
     1203    var elements = [];
     1204    while (element = element[property])
     1205      if (element.nodeType == 1)
     1206        elements.push(Element.extend(element));
     1207    return elements;
     1208  },
     1209
     1210  ancestors: function(element) {
     1211    return $(element).recursivelyCollect('parentNode');
     1212  },
     1213
     1214  descendants: function(element) {
     1215    return $A($(element).getElementsByTagName('*'));
     1216  },
     1217
     1218  immediateDescendants: function(element) {
     1219    if (!(element = $(element).firstChild)) return [];
     1220    while (element && element.nodeType != 1) element = element.nextSibling;
     1221    if (element) return [element].concat($(element).nextSiblings());
     1222    return [];
     1223  },
     1224
     1225  previousSiblings: function(element) {
     1226    return $(element).recursivelyCollect('previousSibling');
     1227  },
     1228
     1229  nextSiblings: function(element) {
     1230    return $(element).recursivelyCollect('nextSibling');
     1231  },
     1232
     1233  siblings: function(element) {
     1234    element = $(element);
     1235    return element.previousSiblings().reverse().concat(element.nextSiblings());
     1236  },
     1237
     1238  match: function(element, selector) {
     1239    if (typeof selector == 'string')
     1240      selector = new Selector(selector);
     1241    return selector.match($(element));
     1242  },
     1243
     1244  up: function(element, expression, index) {
     1245    return Selector.findElement($(element).ancestors(), expression, index);
     1246  },
     1247
     1248  down: function(element, expression, index) {
     1249    return Selector.findElement($(element).descendants(), expression, index);
     1250  },
     1251
     1252  previous: function(element, expression, index) {
     1253    return Selector.findElement($(element).previousSiblings(), expression, index);
     1254  },
     1255
     1256  next: function(element, expression, index) {
     1257    return Selector.findElement($(element).nextSiblings(), expression, index);
     1258  },
     1259
     1260  getElementsBySelector: function() {
     1261    var args = $A(arguments), element = $(args.shift());
     1262    return Selector.findChildElements(element, args);
     1263  },
     1264
     1265  getElementsByClassName: function(element, className) {
     1266    return document.getElementsByClassName(className, element);
     1267  },
     1268
     1269  readAttribute: function(element, name) {
     1270    element = $(element);
     1271    if (document.all && !window.opera) {
     1272      var t = Element._attributeTranslations;
     1273      if (t.values[name]) return t.values[name](element, name);
     1274      if (t.names[name])  name = t.names[name];
     1275      var attribute = element.attributes[name];
     1276      if(attribute) return attribute.nodeValue;
     1277    }
     1278    return element.getAttribute(name);
    9661279  },
    9671280
    9681281  getHeight: function(element) {
    969     element = $(element);
    970     return element.offsetHeight;
     1282    return $(element).getDimensions().height;
     1283  },
     1284
     1285  getWidth: function(element) {
     1286    return $(element).getDimensions().width;
    9711287  },
    9721288
     
    9771293  hasClassName: function(element, className) {
    9781294    if (!(element = $(element))) return;
    979     return Element.classNames(element).include(className);
     1295    var elementClassName = element.className;
     1296    if (elementClassName.length == 0) return false;
     1297    if (elementClassName == className ||
     1298        elementClassName.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
     1299      return true;
     1300    return false;
    9801301  },
    9811302
    9821303  addClassName: function(element, className) {
    9831304    if (!(element = $(element))) return;
    984     return Element.classNames(element).add(className);
     1305    Element.classNames(element).add(className);
     1306    return element;
    9851307  },
    9861308
    9871309  removeClassName: function(element, className) {
    9881310    if (!(element = $(element))) return;
    989     return Element.classNames(element).remove(className);
     1311    Element.classNames(element).remove(className);
     1312    return element;
     1313  },
     1314
     1315  toggleClassName: function(element, className) {
     1316    if (!(element = $(element))) return;
     1317    Element.classNames(element)[element.hasClassName(className) ? 'remove' : 'add'](className);
     1318    return element;
     1319  },
     1320
     1321  observe: function() {
     1322    Event.observe.apply(Event, arguments);
     1323    return $A(arguments).first();
     1324  },
     1325
     1326  stopObserving: function() {
     1327    Event.stopObserving.apply(Event, arguments);
     1328    return $A(arguments).first();
    9901329  },
    9911330
     
    9931332  cleanWhitespace: function(element) {
    9941333    element = $(element);
    995     for (var i = 0; i < element.childNodes.length; i++) {
    996       var node = element.childNodes[i];
     1334    var node = element.firstChild;
     1335    while (node) {
     1336      var nextNode = node.nextSibling;
    9971337      if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
    998         Element.remove(node);
    999     }
     1338        element.removeChild(node);
     1339      node = nextNode;
     1340    }
     1341    return element;
    10001342  },
    10011343
     
    10041346  },
    10051347
    1006   childOf: function(element, ancestor) {
     1348  descendantOf: function(element, ancestor) {
    10071349    element = $(element), ancestor = $(ancestor);
    10081350    while (element = element.parentNode)
     
    10131355  scrollTo: function(element) {
    10141356    element = $(element);
    1015     var x = element.x ? element.x : element.offsetLeft,
    1016         y = element.y ? element.y : element.offsetTop;
    1017     window.scrollTo(x, y);
     1357    var pos = Position.cumulativeOffset(element);
     1358    window.scrollTo(pos[0], pos[1]);
     1359    return element;
    10181360  },
    10191361
    10201362  getStyle: function(element, style) {
    10211363    element = $(element);
    1022     var value = element.style[style.camelize()];
     1364    if (['float','cssFloat'].include(style))
     1365      style = (typeof element.style.styleFloat != 'undefined' ? 'styleFloat' : 'cssFloat');
     1366    style = style.camelize();
     1367    var value = element.style[style];
    10231368    if (!value) {
    10241369      if (document.defaultView && document.defaultView.getComputedStyle) {
    10251370        var css = document.defaultView.getComputedStyle(element, null);
    1026         value = css ? css.getPropertyValue(style) : null;
     1371        value = css ? css[style] : null;
    10271372      } else if (element.currentStyle) {
    1028         value = element.currentStyle[style.camelize()];
     1373        value = element.currentStyle[style];
    10291374      }
    10301375    }
     1376
     1377    if((value == 'auto') && ['width','height'].include(style) && (element.getStyle('display') != 'none'))
     1378      value = element['offset'+style.capitalize()] + 'px';
    10311379
    10321380    if (window.opera && ['left', 'top', 'right', 'bottom'].include(style))
    10331381      if (Element.getStyle(element, 'position') == 'static') value = 'auto';
    1034 
     1382    if(style == 'opacity') {
     1383      if(value) return parseFloat(value);
     1384      if(value = (element.getStyle('filter') || '').match(/alpha\(opacity=(.*)\)/))
     1385        if(value[1]) return parseFloat(value[1]) / 100;
     1386      return 1.0;
     1387    }
    10351388    return value == 'auto' ? null : value;
    10361389  },
     
    10381391  setStyle: function(element, style) {
    10391392    element = $(element);
    1040     for (var name in style)
    1041       element.style[name.camelize()] = style[name];
     1393    for (var name in style) {
     1394      var value = style[name];
     1395      if(name == 'opacity') {
     1396        if (value == 1) {
     1397          value = (/Gecko/.test(navigator.userAgent) &&
     1398            !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ? 0.999999 : 1.0;
     1399          if(/MSIE/.test(navigator.userAgent) && !window.opera)
     1400            element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'');
     1401        } else if(value == '') {
     1402          if(/MSIE/.test(navigator.userAgent) && !window.opera)
     1403            element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'');
     1404        } else {
     1405          if(value < 0.00001) value = 0;
     1406          if(/MSIE/.test(navigator.userAgent) && !window.opera)
     1407            element.style.filter = element.getStyle('filter').replace(/alpha\([^\)]*\)/gi,'') +
     1408              'alpha(opacity='+value*100+')';
     1409        }
     1410      } else if(['float','cssFloat'].include(name)) name = (typeof element.style.styleFloat != 'undefined') ? 'styleFloat' : 'cssFloat';
     1411      element.style[name.camelize()] = value;
     1412    }
     1413    return element;
    10421414  },
    10431415
    10441416  getDimensions: function(element) {
    10451417    element = $(element);
    1046     if (Element.getStyle(element, 'display') != 'none')
     1418    var display = $(element).getStyle('display');
     1419    if (display != 'none' && display != null) // Safari bug
    10471420      return {width: element.offsetWidth, height: element.offsetHeight};
    10481421
     
    10521425    var originalVisibility = els.visibility;
    10531426    var originalPosition = els.position;
     1427    var originalDisplay = els.display;
    10541428    els.visibility = 'hidden';
    10551429    els.position = 'absolute';
    1056     els.display = '';
     1430    els.display = 'block';
    10571431    var originalWidth = element.clientWidth;
    10581432    var originalHeight = element.clientHeight;
    1059     els.display = 'none';
     1433    els.display = originalDisplay;
    10601434    els.position = originalPosition;
    10611435    els.visibility = originalVisibility;
     
    10761450      }
    10771451    }
     1452    return element;
    10781453  },
    10791454
     
    10881463        element.style.right = '';
    10891464    }
     1465    return element;
    10901466  },
    10911467
    10921468  makeClipping: function(element) {
    10931469    element = $(element);
    1094     if (element._overflow) return;
    1095     element._overflow = element.style.overflow;
     1470    if (element._overflow) return element;
     1471    element._overflow = element.style.overflow || 'auto';
    10961472    if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden')
    10971473      element.style.overflow = 'hidden';
     1474    return element;
    10981475  },
    10991476
    11001477  undoClipping: function(element) {
    11011478    element = $(element);
    1102     if (element._overflow) return;
    1103     element.style.overflow = element._overflow;
    1104     element._overflow = undefined;
    1105   }
    1106 }
     1479    if (!element._overflow) return element;
     1480    element.style.overflow = element._overflow == 'auto' ? '' : element._overflow;
     1481    element._overflow = null;
     1482    return element;
     1483  }
     1484};
     1485
     1486Object.extend(Element.Methods, {childOf: Element.Methods.descendantOf});
     1487
     1488Element._attributeTranslations = {};
     1489
     1490Element._attributeTranslations.names = {
     1491  colspan:   "colSpan",
     1492  rowspan:   "rowSpan",
     1493  valign:    "vAlign",
     1494  datetime:  "dateTime",
     1495  accesskey: "accessKey",
     1496  tabindex:  "tabIndex",
     1497  enctype:   "encType",
     1498  maxlength: "maxLength",
     1499  readonly:  "readOnly",
     1500  longdesc:  "longDesc"
     1501};
     1502
     1503Element._attributeTranslations.values = {
     1504  _getAttr: function(element, attribute) {
     1505    return element.getAttribute(attribute, 2);
     1506  },
     1507
     1508  _flag: function(element, attribute) {
     1509    return $(element).hasAttribute(attribute) ? attribute : null;
     1510  },
     1511
     1512  style: function(element) {
     1513    return element.style.cssText.toLowerCase();
     1514  },
     1515
     1516  title: function(element) {
     1517    var node = element.getAttributeNode('title');
     1518    return node.specified ? node.nodeValue : null;
     1519  }
     1520};
     1521
     1522Object.extend(Element._attributeTranslations.values, {
     1523  href: Element._attributeTranslations.values._getAttr,
     1524  src:  Element._attributeTranslations.values._getAttr,
     1525  disabled: Element._attributeTranslations.values._flag,
     1526  checked:  Element._attributeTranslations.values._flag,
     1527  readonly: Element._attributeTranslations.values._flag,
     1528  multiple: Element._attributeTranslations.values._flag
     1529});
     1530
     1531Element.Methods.Simulated = {
     1532  hasAttribute: function(element, attribute) {
     1533    var t = Element._attributeTranslations;
     1534    attribute = t.names[attribute] || attribute;
     1535    return $(element).getAttributeNode(attribute).specified;
     1536  }
     1537};
     1538
     1539// IE is missing .innerHTML support for TABLE-related elements
     1540if (document.all && !window.opera){
     1541  Element.Methods.update = function(element, html) {
     1542    element = $(element);
     1543    html = typeof html == 'undefined' ? '' : html.toString();
     1544    var tagName = element.tagName.toUpperCase();
     1545    if (['THEAD','TBODY','TR','TD'].include(tagName)) {
     1546      var div = document.createElement('div');
     1547      switch (tagName) {
     1548        case 'THEAD':
     1549        case 'TBODY':
     1550          div.innerHTML = '<table><tbody>' +  html.stripScripts() + '</tbody></table>';
     1551          depth = 2;
     1552          break;
     1553        case 'TR':
     1554          div.innerHTML = '<table><tbody><tr>' +  html.stripScripts() + '</tr></tbody></table>';
     1555          depth = 3;
     1556          break;
     1557        case 'TD':
     1558          div.innerHTML = '<table><tbody><tr><td>' +  html.stripScripts() + '</td></tr></tbody></table>';
     1559          depth = 4;
     1560      }
     1561      $A(element.childNodes).each(function(node){
     1562        element.removeChild(node)
     1563      });
     1564      depth.times(function(){ div = div.firstChild });
     1565
     1566      $A(div.childNodes).each(
     1567        function(node){ element.appendChild(node) });
     1568    } else {
     1569      element.innerHTML = html.stripScripts();
     1570    }
     1571    setTimeout(function() {html.evalScripts()}, 10);
     1572    return element;
     1573  }
     1574};
    11071575
    11081576Object.extend(Element, Element.Methods);
     
    11101578var _nativeExtensions = false;
    11111579
    1112 if(!HTMLElement && /Konqueror|Safari|KHTML/.test(navigator.userAgent)) {
    1113   var HTMLElement = {}
    1114   HTMLElement.prototype = document.createElement('div').__proto__;
    1115 }
     1580if(/Konqueror|Safari|KHTML/.test(navigator.userAgent))
     1581  ['', 'Form', 'Input', 'TextArea', 'Select'].each(function(tag) {
     1582    var className = 'HTML' + tag + 'Element';
     1583    if(window[className]) return;
     1584    var klass = window[className] = {};
     1585    klass.prototype = document.createElement(tag ? tag.toLowerCase() : 'div').__proto__;
     1586  });
    11161587
    11171588Element.addMethods = function(methods) {
    11181589  Object.extend(Element.Methods, methods || {});
    11191590
    1120   if(typeof HTMLElement != 'undefined') {
    1121     var methods = Element.Methods, cache = Element.extend.cache;
    1122     for (property in methods) {
     1591  function copy(methods, destination, onlyIfAbsent) {
     1592    onlyIfAbsent = onlyIfAbsent || false;
     1593    var cache = Element.extend.cache;
     1594    for (var property in methods) {
    11231595      var value = methods[property];
    1124       if (typeof value == 'function')
    1125         HTMLElement.prototype[property] = cache.findOrStore(value);
    1126     }
     1596      if (!onlyIfAbsent || !(property in destination))
     1597        destination[property] = cache.findOrStore(value);
     1598    }
     1599  }
     1600
     1601  if (typeof HTMLElement != 'undefined') {
     1602    copy(Element.Methods, HTMLElement.prototype);
     1603    copy(Element.Methods.Simulated, HTMLElement.prototype, true);
     1604    copy(Form.Methods, HTMLFormElement.prototype);
     1605    [HTMLInputElement, HTMLTextAreaElement, HTMLSelectElement].each(function(klass) {
     1606      copy(Form.Element.Methods, klass.prototype);
     1607    });
    11271608    _nativeExtensions = true;
    11281609  }
    11291610}
    1130 
    1131 Element.addMethods();
    11321611
    11331612var Toggle = new Object();
     
    11491628        this.element.insertAdjacentHTML(this.adjacency, this.content);
    11501629      } catch (e) {
    1151         var tagName = this.element.tagName.toLowerCase();
    1152         if (tagName == 'tbody' || tagName == 'tr') {
     1630        var tagName = this.element.tagName.toUpperCase();
     1631        if (['TBODY', 'TR'].include(tagName)) {
    11531632          this.insertContent(this.contentFromAnonymousTable());
    11541633        } else {
     
    12491728  add: function(classNameToAdd) {
    12501729    if (this.include(classNameToAdd)) return;
    1251     this.set(this.toArray().concat(classNameToAdd).join(' '));
     1730    this.set($A(this).concat(classNameToAdd).join(' '));
    12521731  },
    12531732
    12541733  remove: function(classNameToRemove) {
    12551734    if (!this.include(classNameToRemove)) return;
    1256     this.set(this.select(function(className) {
    1257       return className != classNameToRemove;
    1258     }).join(' '));
     1735    this.set($A(this).without(classNameToRemove).join(' '));
    12591736  },
    12601737
    12611738  toString: function() {
    1262     return this.toArray().join(' ');
    1263   }
    1264 }
     1739    return $A(this).join(' ');
     1740  }
     1741};
    12651742
    12661743Object.extend(Element.ClassNames.prototype, Enumerable);
     
    13091786      conditions.push('true');
    13101787    if (clause = params.id)
    1311       conditions.push('element.id == ' + clause.inspect());
     1788      conditions.push('element.readAttribute("id") == ' + clause.inspect());
    13121789    if (clause = params.tagName)
    13131790      conditions.push('element.tagName.toUpperCase() == ' + clause.inspect());
    13141791    if ((clause = params.classNames).length > 0)
    1315       for (var i = 0; i < clause.length; i++)
    1316         conditions.push('Element.hasClassName(element, ' + clause[i].inspect() + ')');
     1792      for (var i = 0, length = clause.length; i < length; i++)
     1793        conditions.push('element.hasClassName(' + clause[i].inspect() + ')');
    13171794    if (clause = params.attributes) {
    13181795      clause.each(function(attribute) {
    1319         var value = 'element.getAttribute(' + attribute.name.inspect() + ')';
     1796        var value = 'element.readAttribute(' + attribute.name.inspect() + ')';
    13201797        var splitValueBy = function(delimiter) {
    13211798          return value + ' && ' + value + '.split(' + delimiter.inspect() + ')';
     
    13301807          case '!=':      conditions.push(value + ' != ' + attribute.value.inspect()); break;
    13311808          case '':
    1332           case undefined: conditions.push(value + ' != null'); break;
     1809          case undefined: conditions.push('element.hasAttribute(' + attribute.name.inspect() + ')'); break;
    13331810          default:        throw 'Unknown operator ' + attribute.operator + ' in selector';
    13341811        }
     
    13411818  compileMatcher: function() {
    13421819    this.match = new Function('element', 'if (!element.tagName) return false; \
     1820      element = $(element); \
    13431821      return ' + this.buildMatchExpression());
    13441822  },
     
    13551833
    13561834    var results = [];
    1357     for (var i = 0; i < scope.length; i++)
     1835    for (var i = 0, length = scope.length; i < length; i++)
    13581836      if (this.match(element = scope[i]))
    13591837        results.push(Element.extend(element));
     
    13671845}
    13681846
     1847Object.extend(Selector, {
     1848  matchElements: function(elements, expression) {
     1849    var selector = new Selector(expression);
     1850    return elements.select(selector.match.bind(selector)).map(Element.extend);
     1851  },
     1852
     1853  findElement: function(elements, expression, index) {
     1854    if (typeof expression == 'number') index = expression, expression = false;
     1855    return Selector.matchElements(elements, expression || '*')[index || 0];
     1856  },
     1857
     1858  findChildElements: function(element, expressions) {
     1859    return expressions.map(function(expression) {
     1860      return expression.match(/[^\s"]+(?:"[^"]*"[^\s"]+)*/g).inject([null], function(results, expr) {
     1861        var selector = new Selector(expr);
     1862        return results.inject([], function(elements, result) {
     1863          return elements.concat(selector.findElements(result || element));
     1864        });
     1865      });
     1866    }).flatten();
     1867  }
     1868});
     1869
    13691870function $$() {
    1370   return $A(arguments).map(function(expression) {
    1371     return expression.strip().split(/\s+/).inject([null], function(results, expr) {
    1372       var selector = new Selector(expr);
    1373       return results.map(selector.findElements.bind(selector)).flatten();
    1374     });
    1375   }).flatten();
    1376 }
    1377 var Field = {
    1378   clear: function() {
    1379     for (var i = 0; i < arguments.length; i++)
    1380       $(arguments[i]).value = '';
    1381   },
    1382 
     1871  return Selector.findChildElements(document, $A(arguments));
     1872}
     1873var Form = {
     1874  reset: function(form) {
     1875    $(form).reset();
     1876    return form;
     1877  },
     1878
     1879  serializeElements: function(elements, getHash) {
     1880    var data = elements.inject({}, function(result, element) {
     1881      if (!element.disabled && element.name) {
     1882        var key = element.name, value = $(element).getValue();
     1883        if (value != undefined) {
     1884          if (result[key]) {
     1885            if (result[key].constructor != Array) result[key] = [result[key]];
     1886            result[key].push(value);
     1887          }
     1888          else result[key] = value;
     1889        }
     1890      }
     1891      return result;
     1892    });
     1893
     1894    return getHash ? data : Hash.toQueryString(data);
     1895  }
     1896};
     1897
     1898Form.Methods = {
     1899  serialize: function(form, getHash) {
     1900    return Form.serializeElements(Form.getElements(form), getHash);
     1901  },
     1902
     1903  getElements: function(form) {
     1904    return $A($(form).getElementsByTagName('*')).inject([],
     1905      function(elements, child) {
     1906        if (Form.Element.Serializers[child.tagName.toLowerCase()])
     1907          elements.push(Element.extend(child));
     1908        return elements;
     1909      }
     1910    );
     1911  },
     1912
     1913  getInputs: function(form, typeName, name) {
     1914    form = $(form);
     1915    var inputs = form.getElementsByTagName('input');
     1916
     1917    if (!typeName && !name) return $A(inputs).map(Element.extend);
     1918
     1919    for (var i = 0, matchingInputs = [], length = inputs.length; i < length; i++) {
     1920      var input = inputs[i];
     1921      if ((typeName && input.type != typeName) || (name && input.name != name))
     1922        continue;
     1923      matchingInputs.push(Element.extend(input));
     1924    }
     1925
     1926    return matchingInputs;
     1927  },
     1928
     1929  disable: function(form) {
     1930    form = $(form);
     1931    form.getElements().each(function(element) {
     1932      element.blur();
     1933      element.disabled = 'true';
     1934    });
     1935    return form;
     1936  },
     1937
     1938  enable: function(form) {
     1939    form = $(form);
     1940    form.getElements().each(function(element) {
     1941      element.disabled = '';
     1942    });
     1943    return form;
     1944  },
     1945
     1946  findFirstElement: function(form) {
     1947    return $(form).getElements().find(function(element) {
     1948      return element.type != 'hidden' && !element.disabled &&
     1949        ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
     1950    });
     1951  },
     1952
     1953  focusFirstElement: function(form) {
     1954    form = $(form);
     1955    form.findFirstElement().activate();
     1956    return form;
     1957  }
     1958}
     1959
     1960Object.extend(Form, Form.Methods);
     1961
     1962/*--------------------------------------------------------------------------*/
     1963
     1964Form.Element = {
    13831965  focus: function(element) {
    13841966    $(element).focus();
    1385   },
    1386 
    1387   present: function() {
    1388     for (var i = 0; i < arguments.length; i++)
    1389       if ($(arguments[i]).value == '') return false;
    1390     return true;
     1967    return element;
    13911968  },
    13921969
    13931970  select: function(element) {
    13941971    $(element).select();
     1972    return element;
     1973  }
     1974}
     1975
     1976Form.Element.Methods = {
     1977  serialize: function(element) {
     1978    element = $(element);
     1979    if (!element.disabled && element.name) {
     1980      var value = element.getValue();
     1981      if (value != undefined) {
     1982        var pair = {};
     1983        pair[element.name] = value;
     1984        return Hash.toQueryString(pair);
     1985      }
     1986    }
     1987    return '';
     1988  },
     1989
     1990  getValue: function(element) {
     1991    element = $(element);
     1992    var method = element.tagName.toLowerCase();
     1993    return Form.Element.Serializers[method](element);
     1994  },
     1995
     1996  clear: function(element) {
     1997    $(element).value = '';
     1998    return element;
     1999  },
     2000
     2001  present: function(element) {
     2002    return $(element).value != '';
    13952003  },
    13962004
     
    13982006    element = $(element);
    13992007    element.focus();
    1400     if (element.select)
     2008    if (element.select && ( element.tagName.toLowerCase() != 'input' ||
     2009      !['button', 'reset', 'submit'].include(element.type) ) )
    14012010      element.select();
    1402   }
    1403 }
     2011    return element;
     2012  },
     2013
     2014  disable: function(element) {
     2015    element = $(element);
     2016    element.disabled = true;
     2017    return element;
     2018  },
     2019
     2020  enable: function(element) {
     2021    element = $(element);
     2022    element.blur();
     2023    element.disabled = false;
     2024    return element;
     2025  }
     2026}
     2027
     2028Object.extend(Form.Element, Form.Element.Methods);
     2029var Field = Form.Element;
     2030var $F = Form.Element.getValue;
    14042031
    14052032/*--------------------------------------------------------------------------*/
    1406 
    1407 var Form = {
    1408   serialize: function(form) {
    1409     var elements = Form.getElements($(form));
    1410     var queryComponents = new Array();
    1411 
    1412     for (var i = 0; i < elements.length; i++) {
    1413       var queryComponent = Form.Element.serialize(elements[i]);
    1414       if (queryComponent)
    1415         queryComponents.push(queryComponent);
    1416     }
    1417 
    1418     return queryComponents.join('&');
    1419   },
    1420 
    1421   getElements: function(form) {
    1422     form = $(form);
    1423     var elements = new Array();
    1424 
    1425     for (var tagName in Form.Element.Serializers) {
    1426       var tagElements = form.getElementsByTagName(tagName);
    1427       for (var j = 0; j < tagElements.length; j++)
    1428         elements.push(tagElements[j]);
    1429     }
    1430     return elements;
    1431   },
    1432 
    1433   getInputs: function(form, typeName, name) {
    1434     form = $(form);
    1435     var inputs = form.getElementsByTagName('input');
    1436 
    1437     if (!typeName && !name)
    1438       return inputs;
    1439 
    1440     var matchingInputs = new Array();
    1441     for (var i = 0; i < inputs.length; i++) {
    1442       var input = inputs[i];
    1443       if ((typeName && input.type != typeName) ||
    1444           (name && input.name != name))
    1445         continue;
    1446       matchingInputs.push(input);
    1447     }
    1448 
    1449     return matchingInputs;
    1450   },
    1451 
    1452   disable: function(form) {
    1453     var elements = Form.getElements(form);
    1454     for (var i = 0; i < elements.length; i++) {
    1455       var element = elements[i];
    1456       element.blur();
    1457       element.disabled = 'true';
    1458     }
    1459   },
    1460 
    1461   enable: function(form) {
    1462     var elements = Form.getElements(form);
    1463     for (var i = 0; i < elements.length; i++) {
    1464       var element = elements[i];
    1465       element.disabled = '';
    1466     }
    1467   },
    1468 
    1469   findFirstElement: function(form) {
    1470     return Form.getElements(form).find(function(element) {
    1471       return element.type != 'hidden' && !element.disabled &&
    1472         ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
    1473     });
    1474   },
    1475 
    1476   focusFirstElement: function(form) {
    1477     Field.activate(Form.findFirstElement(form));
    1478   },
    1479 
    1480   reset: function(form) {
    1481     $(form).reset();
    1482   }
    1483 }
    1484 
    1485 Form.Element = {
    1486   serialize: function(element) {
    1487     element = $(element);
    1488     var method = element.tagName.toLowerCase();
    1489     var parameter = Form.Element.Serializers[method](element);
    1490 
    1491     if (parameter) {
    1492       var key = encodeURIComponent(parameter[0]);
    1493       if (key.length == 0) return;
    1494 
    1495       if (parameter[1].constructor != Array)
    1496         parameter[1] = [parameter[1]];
    1497 
    1498       return parameter[1].map(function(value) {
    1499         return key + '=' + encodeURIComponent(value);
    1500       }).join('&');
    1501     }
    1502   },
    1503 
    1504   getValue: function(element) {
    1505     element = $(element);
    1506     var method = element.tagName.toLowerCase();
    1507     var parameter = Form.Element.Serializers[method](element);
    1508 
    1509     if (parameter)
    1510       return parameter[1];
    1511   }
    1512 }
    15132033
    15142034Form.Element.Serializers = {
    15152035  input: function(element) {
    15162036    switch (element.type.toLowerCase()) {
    1517       case 'submit':
    1518       case 'hidden':
    1519       case 'password':
    1520       case 'text':
    1521         return Form.Element.Serializers.textarea(element);
    15222037      case 'checkbox':
    15232038      case 'radio':
    15242039        return Form.Element.Serializers.inputSelector(element);
    1525     }
    1526     return false;
     2040      default:
     2041        return Form.Element.Serializers.textarea(element);
     2042    }
    15272043  },
    15282044
    15292045  inputSelector: function(element) {
    1530     if (element.checked)
    1531       return [element.name, element.value];
     2046    return element.checked ? element.value : null;
    15322047  },
    15332048
    15342049  textarea: function(element) {
    1535     return [element.name, element.value];
     2050    return element.value;
    15362051  },
    15372052
    15382053  select: function(element) {
    1539     return Form.Element.Serializers[element.type == 'select-one' ?
     2054    return this[element.type == 'select-one' ?
    15402055      'selectOne' : 'selectMany'](element);
    15412056  },
    15422057
    15432058  selectOne: function(element) {
    1544     var value = '', opt, index = element.selectedIndex;
    1545     if (index >= 0) {
    1546       opt = element.options[index];
    1547       value = opt.value || opt.text;
    1548     }
    1549     return [element.name, value];
     2059    var index = element.selectedIndex;
     2060    return index >= 0 ? this.optionValue(element.options[index]) : null;
    15502061  },
    15512062
    15522063  selectMany: function(element) {
    1553     var value = [];
    1554     for (var i = 0; i < element.length; i++) {
     2064    var values, length = element.length;
     2065    if (!length) return null;
     2066
     2067    for (var i = 0, values = []; i < length; i++) {
    15552068      var opt = element.options[i];
    1556       if (opt.selected)
    1557         value.push(opt.value || opt.text);
    1558     }
    1559     return [element.name, value];
    1560   }
    1561 }
    1562 
    1563 /*--------------------------------------------------------------------------*/
    1564 
    1565 var $F = Form.Element.getValue;
     2069      if (opt.selected) values.push(this.optionValue(opt));
     2070    }
     2071    return values;
     2072  },
     2073
     2074  optionValue: function(opt) {
     2075    // extend element because hasAttribute may not be native
     2076    return Element.extend(opt).hasAttribute('value') ? opt.value : opt.text;
     2077  }
     2078}
    15662079
    15672080/*--------------------------------------------------------------------------*/
     
    15842097  onTimerEvent: function() {
    15852098    var value = this.getValue();
    1586     if (this.lastValue != value) {
     2099    var changed = ('string' == typeof this.lastValue && 'string' == typeof value
     2100      ? this.lastValue != value : String(this.lastValue) != String(value));
     2101    if (changed) {
    15872102      this.callback(this.element, value);
    15882103      this.lastValue = value;
     
    16292144
    16302145  registerFormCallbacks: function() {
    1631     var elements = Form.getElements(this.element);
    1632     for (var i = 0; i < elements.length; i++)
    1633       this.registerCallback(elements[i]);
     2146    Form.getElements(this.element).each(this.registerCallback.bind(this));
    16342147  },
    16352148
     
    16412154          Event.observe(element, 'click', this.onElementEvent.bind(this));
    16422155          break;
    1643         case 'password':
    1644         case 'text':
    1645         case 'textarea':
    1646         case 'select-one':
    1647         case 'select-multiple':
     2156        default:
    16482157          Event.observe(element, 'change', this.onElementEvent.bind(this));
    16492158          break;
     
    16802189  KEY_DOWN:     40,
    16812190  KEY_DELETE:   46,
     2191  KEY_HOME:     36,
     2192  KEY_END:      35,
     2193  KEY_PAGEUP:   33,
     2194  KEY_PAGEDOWN: 34,
    16822195
    16832196  element: function(event) {
     
    17352248  unloadCache: function() {
    17362249    if (!Event.observers) return;
    1737     for (var i = 0; i < Event.observers.length; i++) {
     2250    for (var i = 0, length = Event.observers.length; i < length; i++) {
    17382251      Event.stopObserving.apply(this, Event.observers[i]);
    17392252      Event.observers[i][0] = null;
     
    17432256
    17442257  observe: function(element, name, observer, useCapture) {
    1745     var element = $(element);
     2258    element = $(element);
    17462259    useCapture = useCapture || false;
    17472260
     
    17512264      name = 'keydown';
    17522265
    1753     this._observeAndCache(element, name, observer, useCapture);
     2266    Event._observeAndCache(element, name, observer, useCapture);
    17542267  },
    17552268
    17562269  stopObserving: function(element, name, observer, useCapture) {
    1757     var element = $(element);
     2270    element = $(element);
    17582271    useCapture = useCapture || false;
    17592272
     
    18222335      element = element.offsetParent;
    18232336      if (element) {
    1824         p = Element.getStyle(element, 'position');
     2337        if(element.tagName=='BODY') break;
     2338        var p = Element.getStyle(element, 'position');
    18252339        if (p == 'relative' || p == 'absolute') break;
    18262340      }
     
    18782392  },
    18792393
    1880   clone: function(source, target) {
    1881     source = $(source);
    1882     target = $(target);
    1883     target.style.position = 'absolute';
    1884     var offsets = this.cumulativeOffset(source);
    1885     target.style.top    = offsets[1] + 'px';
    1886     target.style.left   = offsets[0] + 'px';
    1887     target.style.width  = source.offsetWidth + 'px';
    1888     target.style.height = source.offsetHeight + 'px';
    1889   },
    1890 
    18912394  page: function(forElement) {
    18922395    var valueT = 0, valueL = 0;
     
    19052408    element = forElement;
    19062409    do {
    1907       valueT -= element.scrollTop  || 0;
    1908       valueL -= element.scrollLeft || 0;
     2410      if (!window.opera || element.tagName=='BODY') {
     2411        valueT -= element.scrollTop  || 0;
     2412        valueL -= element.scrollLeft || 0;
     2413      }
    19092414    } while (element = element.parentNode);
    19102415
     
    19672472
    19682473    element.style.position = 'absolute';
    1969     element.style.top    = top + 'px';;
    1970     element.style.left   = left + 'px';;
    1971     element.style.width  = width + 'px';;
    1972     element.style.height = height + 'px';;
     2474    element.style.top    = top + 'px';
     2475    element.style.left   = left + 'px';
     2476    element.style.width  = width + 'px';
     2477    element.style.height = height + 'px';
    19732478  },
    19742479
     
    20072512  }
    20082513}
     2514
     2515Element.addMethods();
  • tags/2.2/wp-includes/js/scriptaculous/scriptaculous.js

    r5468 r5480  
    1 // Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
     1// script.aculo.us scriptaculous.js v1.7.0, Fri Jan 19 19:16:36 CET 2007
     2
     3// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
    24//
    35// Permission is hereby granted, free of charge, to any person obtaining
     
    1921// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
    2022// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
     23//
     24// For details, see the script.aculo.us web site: http://script.aculo.us/
    2125
    2226var Scriptaculous = {
    23   Version: '1.6.1',
     27  Version: '1.7.0',
    2428  require: function(libraryName) {
    2529    // inserting via DOM fails in Safari 2.0, so brute force approach
  • tags/2.2/wp-includes/js/scriptaculous/slider.js

    r5468 r5480  
    1 // Copyright (c) 2005 Marty Haught, Thomas Fuchs
     1// script.aculo.us slider.js v1.7.0, Fri Jan 19 19:16:36 CET 2007
     2
     3// Copyright (c) 2005, 2006 Marty Haught, Thomas Fuchs
    24//
    3 // See http://script.aculo.us for more info
    4 //
    5 // Permission is hereby granted, free of charge, to any person obtaining
    6 // a copy of this software and associated documentation files (the
    7 // "Software"), to deal in the Software without restriction, including
    8 // without limitation the rights to use, copy, modify, merge, publish,
    9 // distribute, sublicense, and/or sell copies of the Software, and to
    10 // permit persons to whom the Software is furnished to do so, subject to
    11 // the following conditions:
    12 //
    13 // The above copyright notice and this permission notice shall be
    14 // included in all copies or substantial portions of the Software.
    15 //
    16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    17 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
    18 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
    19 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
    20 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
    21 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
    22 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
     5// script.aculo.us is freely distributable under the terms of an MIT-style license.
     6// For details, see the script.aculo.us web site: http://script.aculo.us/
    237
    248if(!Control) var Control = {};
     
    6549   
    6650    this.trackLength = this.maximumOffset() - this.minimumOffset();
    67     this.handleLength = this.isVertical() ? this.handles[0].offsetHeight : this.handles[0].offsetWidth;
     51
     52    this.handleLength = this.isVertical() ?
     53      (this.handles[0].offsetHeight != 0 ?
     54        this.handles[0].offsetHeight : this.handles[0].style.height.replace(/px$/,"")) :
     55      (this.handles[0].offsetWidth != 0 ? this.handles[0].offsetWidth :
     56        this.handles[0].style.width.replace(/px$/,""));
    6857
    6958    this.active   = false;
     
    138127  setValue: function(sliderValue, handleIdx){
    139128    if(!this.active) {
    140       this.activeHandle    = this.handles[handleIdx];
    141       this.activeHandleIdx = handleIdx;
     129      this.activeHandleIdx = handleIdx || 0;
     130      this.activeHandle    = this.handles[this.activeHandleIdx];
    142131      this.updateStyles();
    143132    }
     
    181170  },
    182171  maximumOffset: function(){
    183     return(this.isVertical() ?
    184       this.track.offsetHeight - this.alignY : this.track.offsetWidth - this.alignX);
     172    return(this.isVertical() ?
     173      (this.track.offsetHeight != 0 ? this.track.offsetHeight :
     174        this.track.style.height.replace(/px$/,"")) - this.alignY :
     175      (this.track.offsetWidth != 0 ? this.track.offsetWidth :
     176        this.track.style.width.replace(/px$/,"")) - this.alignY);
    185177  }, 
    186178  isVertical:  function(){
     
    218210        var handle = Event.element(event);
    219211        var pointer  = [Event.pointerX(event), Event.pointerY(event)];
    220         if(handle==this.track) {
     212        var track = handle;
     213        if(track==this.track) {
    221214          var offsets  = Position.cumulativeOffset(this.track);
    222215          this.event = event;
     
    231224          while((this.handles.indexOf(handle) == -1) && handle.parentNode)
    232225            handle = handle.parentNode;
    233        
    234           this.activeHandle    = handle;
    235           this.activeHandleIdx = this.handles.indexOf(this.activeHandle);
    236           this.updateStyles();
    237        
    238           var offsets  = Position.cumulativeOffset(this.activeHandle);
    239           this.offsetX = (pointer[0] - offsets[0]);
    240           this.offsetY = (pointer[1] - offsets[1]);
     226           
     227          if(this.handles.indexOf(handle)!=-1) {
     228            this.activeHandle    = handle;
     229            this.activeHandleIdx = this.handles.indexOf(this.activeHandle);
     230            this.updateStyles();
     231           
     232            var offsets  = Position.cumulativeOffset(this.activeHandle);
     233            this.offsetX = (pointer[0] - offsets[0]);
     234            this.offsetY = (pointer[1] - offsets[1]);
     235          }
    241236        }
    242237      }
  • tags/2.2/wp-includes/js/scriptaculous/unittest.js

    r5468 r5480  
    1 // Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
    2 //           (c) 2005 Jon Tirsen (http://www.tirsen.com)
    3 //           (c) 2005 Michael Schuerig (http://www.schuerig.de/michael/)
     1// script.aculo.us unittest.js v1.7.0, Fri Jan 19 19:16:36 CET 2007
     2
     3// Copyright (c) 2005, 2006 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
     4//           (c) 2005, 2006 Jon Tirsen (http://www.tirsen.com)
     5//           (c) 2005, 2006 Michael Schuerig (http://www.schuerig.de/michael/)
    46//
    5 // Permission is hereby granted, free of charge, to any person obtaining
    6 // a copy of this software and associated documentation files (the
    7 // "Software"), to deal in the Software without restriction, including
    8 // without limitation the rights to use, copy, modify, merge, publish,
    9 // distribute, sublicense, and/or sell copies of the Software, and to
    10 // permit persons to whom the Software is furnished to do so, subject to
    11 // the following conditions:
    12 //
    13 // The above copyright notice and this permission notice shall be
    14 // included in all copies or substantial portions of the Software.
    15 //
    16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
    17 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
    18 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
    19 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
    20 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
    21 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
    22 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
    23 
     7// script.aculo.us is freely distributable under the terms of an MIT-style license.
     8// For details, see the script.aculo.us web site: http://script.aculo.us/
    249
    2510// experimental, Firefox-only
     
    2813    pointerX: 0,
    2914    pointerY: 0,
    30     buttons: 0
     15    buttons:  0,
     16    ctrlKey:  false,
     17    altKey:   false,
     18    shiftKey: false,
     19    metaKey:  false
    3120  }, arguments[2] || {});
    3221  var oEvent = document.createEvent("MouseEvents");
    3322  oEvent.initMouseEvent(eventName, true, true, document.defaultView,
    3423    options.buttons, options.pointerX, options.pointerY, options.pointerX, options.pointerY,
    35     false, false, false, false, 0, $(element));
     24    options.ctrlKey, options.altKey, options.shiftKey, options.metaKey, 0, $(element));
    3625 
    3726  if(this.mark) Element.remove(this.mark);
     
    9988    this.statusCell = document.createElement('td');
    10089    this.nameCell = document.createElement('td');
     90    this.nameCell.className = "nameCell";
    10191    this.nameCell.appendChild(document.createTextNode(testName));
    10292    this.messageCell = document.createElement('td');
     
    111101    this.statusCell.innerHTML = status;
    112102    this.messageCell.innerHTML = this._toHTML(summary);
     103    this.addLinksToResults();
    113104  },
    114105  message: function(message) {
     
    132123  _toHTML: function(txt) {
    133124    return txt.escapeHTML().replace(/\n/g,"<br/>");
     125  },
     126  addLinksToResults: function(){
     127    $$("tr.failed .nameCell").each( function(td){ // todo: limit to children of this.log
     128      td.title = "Run only this test"
     129      Event.observe(td, 'click', function(){ window.location.search = "?tests=" + td.innerHTML;});
     130    });
     131    $$("tr.passed .nameCell").each( function(td){ // todo: limit to children of this.log
     132      td.title = "Run all tests"
     133      Event.observe(td, 'click', function(){ window.location.search = "";});
     134    });
    134135  }
    135136}
     
    142143    }, arguments[1] || {});
    143144    this.options.resultsURL = this.parseResultsURLQueryParameter();
     145    this.options.tests      = this.parseTestsQueryParameter();
    144146    if (this.options.testLog) {
    145147      this.options.testLog = $(this.options.testLog) || null;
     
    159161        for(var testcase in testcases) {
    160162          if(/^test/.test(testcase)) {
    161             this.tests.push(new Test.Unit.Testcase(testcase, testcases[testcase], testcases["setup"], testcases["teardown"]));
     163            this.tests.push(
     164               new Test.Unit.Testcase(
     165                 this.options.context ? ' -> ' + this.options.titles[testcase] : testcase,
     166                 testcases[testcase], testcases["setup"], testcases["teardown"]
     167               ));
    162168          }
    163169        }
     
    170176  parseResultsURLQueryParameter: function() {
    171177    return window.location.search.parseQuery()["resultsURL"];
     178  },
     179  parseTestsQueryParameter: function(){
     180    if (window.location.search.parseQuery()["tests"]){
     181        return window.location.search.parseQuery()["tests"].split(',');
     182    };
    172183  },
    173184  // Returns:
     
    230241    }
    231242    return (
     243      (this.options.context ? this.options.context + ': ': '') +
    232244      this.tests.length + " tests, " +
    233245      assertions + " assertions, " +
     
    284296    catch(e) { this.error(e); }
    285297  },
     298  assertInspect: function(expected, actual) {
     299    var message = arguments[2] || "assertInspect";
     300    try { (expected == actual.inspect()) ? this.pass() :
     301      this.fail(message + ': expected "' + Test.Unit.inspect(expected) +
     302        '", actual "' + Test.Unit.inspect(actual) + '"'); }
     303    catch(e) { this.error(e); }
     304  },
    286305  assertEnumEqual: function(expected, actual) {
    287306    var message = arguments[2] || "assertEnumEqual";
     
    298317    catch(e) { this.error(e); }
    299318  },
     319  assertIdentical: function(expected, actual) {
     320    var message = arguments[2] || "assertIdentical";
     321    try { (expected === actual) ? this.pass() :
     322      this.fail(message + ': expected "' + Test.Unit.inspect(expected) + 
     323        '", actual "' + Test.Unit.inspect(actual) + '"'); }
     324    catch(e) { this.error(e); }
     325  },
     326  assertNotIdentical: function(expected, actual) {
     327    var message = arguments[2] || "assertNotIdentical";
     328    try { !(expected === actual) ? this.pass() :
     329      this.fail(message + ': expected "' + Test.Unit.inspect(expected) + 
     330        '", actual "' + Test.Unit.inspect(actual) + '"'); }
     331    catch(e) { this.error(e); }
     332  },
    300333  assertNull: function(obj) {
    301334    var message = arguments[1] || 'assertNull'
     
    304337    catch(e) { this.error(e); }
    305338  },
     339  assertMatch: function(expected, actual) {
     340    var message = arguments[2] || 'assertMatch';
     341    var regex = new RegExp(expected);
     342    try { (regex.exec(actual)) ? this.pass() :
     343      this.fail(message + ' : regex: "' +  Test.Unit.inspect(expected) + ' did not match: ' + Test.Unit.inspect(actual) + '"'); }
     344    catch(e) { this.error(e); }
     345  },
    306346  assertHidden: function(element) {
    307347    var message = arguments[1] || 'assertHidden';
     
    311351    var message = arguments[1] || 'assertNotNull';
    312352    this.assert(object != null, message);
     353  },
     354  assertType: function(expected, actual) {
     355    var message = arguments[2] || 'assertType';
     356    try {
     357      (actual.constructor == expected) ? this.pass() :
     358      this.fail(message + ': expected "' + Test.Unit.inspect(expected) + 
     359        '", actual "' + (actual.constructor) + '"'); }
     360    catch(e) { this.error(e); }
     361  },
     362  assertNotOfType: function(expected, actual) {
     363    var message = arguments[2] || 'assertNotOfType';
     364    try {
     365      (actual.constructor != expected) ? this.pass() :
     366      this.fail(message + ': expected "' + Test.Unit.inspect(expected) + 
     367        '", actual "' + (actual.constructor) + '"'); }
     368    catch(e) { this.error(e); }
    313369  },
    314370  assertInstanceOf: function(expected, actual) {
     
    325381      this.fail(message + ": object was an instance of the not expected type"); }
    326382    catch(e) { this.error(e); }
     383  },
     384  assertRespondsTo: function(method, obj) {
     385    var message = arguments[2] || 'assertRespondsTo';
     386    try {
     387      (obj[method] && typeof obj[method] == 'function') ? this.pass() :
     388      this.fail(message + ": object doesn't respond to [" + method + "]"); }
     389    catch(e) { this.error(e); }
     390  },
     391  assertReturnsTrue: function(method, obj) {
     392    var message = arguments[2] || 'assertReturnsTrue';
     393    try {
     394      var m = obj[method];
     395      if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)];
     396      m() ? this.pass() :
     397      this.fail(message + ": method returned false"); }
     398    catch(e) { this.error(e); }
     399  },
     400  assertReturnsFalse: function(method, obj) {
     401    var message = arguments[2] || 'assertReturnsFalse';
     402    try {
     403      var m = obj[method];
     404      if(!m) m = obj['is'+method.charAt(0).toUpperCase()+method.slice(1)];
     405      !m() ? this.pass() :
     406      this.fail(message + ": method returned true"); }
     407    catch(e) { this.error(e); }
     408  },
     409  assertRaise: function(exceptionName, method) {
     410    var message = arguments[2] || 'assertRaise';
     411    try {
     412      method();
     413      this.fail(message + ": exception expected but none was raised"); }
     414    catch(e) {
     415      ((exceptionName == null) || (e.name==exceptionName)) ? this.pass() : this.error(e);
     416    }
     417  },
     418  assertElementsMatch: function() {
     419    var expressions = $A(arguments), elements = $A(expressions.shift());
     420    if (elements.length != expressions.length) {
     421      this.fail('assertElementsMatch: size mismatch: ' + elements.length + ' elements, ' + expressions.length + ' expressions');
     422      return false;
     423    }
     424    elements.zip(expressions).all(function(pair, index) {
     425      var element = $(pair.first()), expression = pair.last();
     426      if (element.match(expression)) return true;
     427      this.fail('assertElementsMatch: (in index ' + index + ') expected ' + expression.inspect() + ' but got ' + element.inspect());
     428    }.bind(this)) && this.pass();
     429  },
     430  assertElementMatches: function(element, expression) {
     431    this.assertElementsMatch([element], expression);
     432  },
     433  benchmark: function(operation, iterations) {
     434    var startAt = new Date();
     435    (iterations || 1).times(operation);
     436    var timeTaken = ((new Date())-startAt);
     437    this.info((arguments[2] || 'Operation') + ' finished ' +
     438       iterations + ' iterations in ' + (timeTaken/1000)+'s' );
     439    return timeTaken;
    327440  },
    328441  _isVisible: function(element) {
     
    356469    Test.Unit.Assertions.prototype.initialize.bind(this)();
    357470    this.name           = name;
    358     this.test           = test || function() {};
     471   
     472    if(typeof test == 'string') {
     473      test = test.gsub(/(\.should[^\(]+\()/,'#{0}this,');
     474      test = test.gsub(/(\.should[^\(]+)\(this,\)/,'#{1}(this)');
     475      this.test = function() {
     476        eval('with(this){'+test+'}');
     477      }
     478    } else {
     479      this.test = test || function() {};
     480    }
     481   
    359482    this.setup          = setup || function() {};
    360483    this.teardown       = teardown || function() {};
     
    382505  }
    383506});
     507
     508// *EXPERIMENTAL* BDD-style testing to please non-technical folk
     509// This draws many ideas from RSpec http://rspec.rubyforge.org/
     510
     511Test.setupBDDExtensionMethods = function(){
     512  var METHODMAP = {
     513    shouldEqual:     'assertEqual',
     514    shouldNotEqual:  'assertNotEqual',
     515    shouldEqualEnum: 'assertEnumEqual',
     516    shouldBeA:       'assertType',
     517    shouldNotBeA:    'assertNotOfType',
     518    shouldBeAn:      'assertType',
     519    shouldNotBeAn:   'assertNotOfType',
     520    shouldBeNull:    'assertNull',
     521    shouldNotBeNull: 'assertNotNull',
     522   
     523    shouldBe:        'assertReturnsTrue',
     524    shouldNotBe:     'assertReturnsFalse',
     525    shouldRespondTo: 'assertRespondsTo'
     526  };
     527  Test.BDDMethods = {};
     528  for(m in METHODMAP) {
     529    Test.BDDMethods[m] = eval(
     530      'function(){'+
     531      'var args = $A(arguments);'+
     532      'var scope = args.shift();'+
     533      'scope.'+METHODMAP[m]+'.apply(scope,(args || []).concat([this])); }');
     534  }
     535  [Array.prototype, String.prototype, Number.prototype].each(
     536    function(p){ Object.extend(p, Test.BDDMethods) }
     537  );
     538}
     539
     540Test.context = function(name, spec, log){
     541  Test.setupBDDExtensionMethods();
     542 
     543  var compiledSpec = {};
     544  var titles = {};
     545  for(specName in spec) {
     546    switch(specName){
     547      case "setup":
     548      case "teardown":
     549        compiledSpec[specName] = spec[specName];
     550        break;
     551      default:
     552        var testName = 'test'+specName.gsub(/\s+/,'-').camelize();
     553        var body = spec[specName].toString().split('\n').slice(1);
     554        if(/^\{/.test(body[0])) body = body.slice(1);
     555        body.pop();
     556        body = body.map(function(statement){
     557          return statement.strip()
     558        });
     559        compiledSpec[testName] = body.join('\n');
     560        titles[testName] = specName;
     561    }
     562  }
     563  new Test.Unit.Runner(compiledSpec, { titles: titles, testLog: log || 'testlog', context: name });
     564};
  • tags/2.2/wp-includes/js/scriptaculous/wp-scriptaculous.js

    r5468 r5480  
    1313
    1414var Scriptaculous = {
    15   Version: '1.6.1',
     15  Version: '1.7.0',
    1616  require: function(libraryName) {
    1717    // inserting via DOM fails in Safari 2.0, so brute force approach
  • tags/2.2/wp-includes/js/tinymce/plugins/autosave/editor_plugin.js

    r5468 r5480  
    11/**
    2  * $Id: editor_plugin_src.js 126 2006-10-22 16:19:55Z spocke $
     2 * $Id: editor_plugin_src.js 201 2007-02-12 15:56:56Z spocke $
    33 *
    44 * @author Moxiecode
    5  * @copyright Copyright © 2004-2006, Moxiecode Systems AB, All rights reserved.
     5 * @copyright Copyright © 2004-2007, Moxiecode Systems AB, All rights reserved.
    66 */
    77
     
    1515            author : 'Moxiecode Systems AB',
    1616            authorurl : 'http://tinymce.moxiecode.com',
    17             infourl : 'http://tinymce.moxiecode.com/tinymce/docs/plugin_autosave.html',
     17            infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/autosave',
    1818            version : tinyMCE.majorVersion + "." + tinyMCE.minorVersion
    1919        };
  • tags/2.2/wp-includes/js/tinymce/plugins/directionality/editor_plugin.js

    r5468 r5480  
    11/**
    2  * $Id: editor_plugin_src.js 126 2006-10-22 16:19:55Z spocke $
     2 * $Id: editor_plugin_src.js 201 2007-02-12 15:56:56Z spocke $
    33 *
    44 * @author Moxiecode
    5  * @copyright Copyright © 2004-2006, Moxiecode Systems AB, All rights reserved.
     5 * @copyright Copyright © 2004-2007, Moxiecode Systems AB, All rights reserved.
    66 */
    77
     
    1515            author : 'Moxiecode Systems AB',
    1616            authorurl : 'http://tinymce.moxiecode.com',
    17             infourl : 'http://tinymce.moxiecode.com/tinymce/docs/plugin_directionality.html',
     17            infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/directionality',
    1818            version : tinyMCE.majorVersion + "." + tinyMCE.minorVersion
    1919        };
  • tags/2.2/wp-includes/js/tinymce/plugins/inlinepopups/editor_plugin.js

    r5468 r5480  
    11/**
    2  * $Id: editor_plugin_src.js 126 2006-10-22 16:19:55Z spocke $
     2 * $Id: editor_plugin_src.js 201 2007-02-12 15:56:56Z spocke $
    33 *
    44 * Moxiecode DHTML Windows script.
    55 *
    66 * @author Moxiecode
    7  * @copyright Copyright © 2004-2006, Moxiecode Systems AB, All rights reserved.
     7 * @copyright Copyright © 2004-2007, Moxiecode Systems AB, All rights reserved.
    88 */
    99
     
    1616            author : 'Moxiecode Systems AB',
    1717            authorurl : 'http://tinymce.moxiecode.com',
    18             infourl : 'http://tinymce.moxiecode.com/tinymce/docs/plugin_inlinepopups.html',
     18            infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/inlinepopups',
    1919            version : tinyMCE.majorVersion + "." + tinyMCE.minorVersion
    2020        };
     
    2727
    2828TinyMCE_Engine.prototype.orgOpenWindow = TinyMCE_Engine.prototype.openWindow;
     29TinyMCE_Engine.prototype.orgCloseWindow = TinyMCE_Engine.prototype.closeWindow;
    2930
    3031TinyMCE_Engine.prototype.openWindow = function(template, args) {
     
    5354        height = 200;
    5455
     56    if (!(minWidth = parseInt(template['minWidth'])))
     57        minWidth = 100;
     58
     59    if (!(minHeight = parseInt(template['minHeight'])))
     60        minHeight = 100;
     61
    5562    resizable = (args && args['resizable']) ? args['resizable'] : "no";
    5663    scrollbars = (args && args['scrollbars']) ? args['scrollbars'] : "no";
     
    6774
    6875    var elm = document.getElementById(this.selectedInstance.editorId + '_parent');
    69     var pos = tinyMCE.getAbsPosition(elm);
     76
     77    if (tinyMCE.hasPlugin('fullscreen') && this.selectedInstance.getData('fullscreen').enabled)
     78        pos = { absLeft: 0, absTop: 0 };
     79    else
     80        pos = tinyMCE.getAbsPosition(elm);
    7081
    7182    // Center div in editor area
     
    7384    pos.absTop += Math.round((elm.firstChild.clientHeight / 2) - (height / 2));
    7485
    75     url += tinyMCE.settings['imp_version'] ? (url.indexOf('?')==-1?'?':'&') + 'ver=' + tinyMCE.settings['imp_version'] : '';
    76 
    77     mcWindows.open(url, mcWindows.idCounter++, "modal=yes,width=" + width+ ",height=" + height + ",resizable=" + resizable + ",scrollbars=" + scrollbars + ",statusbar=" + resizable + ",left=" + pos.absLeft + ",top=" + pos.absTop);
    78 };
    79 
    80 TinyMCE_Engine.prototype.orgCloseWindow = TinyMCE_Engine.prototype.closeWindow;
     86    url += tinyMCE.settings['imp_version'] ? (url.indexOf('?')==-1?'?':'&') + 'ver=' + tinyMCE.settings['imp_version'] : ''; // WordPress cache buster
     87
     88    mcWindows.open(url, mcWindows.idCounter++, "modal=yes,width=" + width+ ",height=" + height + ",resizable=" + resizable + ",scrollbars=" + scrollbars + ",statusbar=" + resizable + ",left=" + pos.absLeft + ",top=" + pos.absTop + ",minWidth=" + minWidth + ",minHeight=" + minHeight );
     89};
    8190
    8291TinyMCE_Engine.prototype.closeWindow = function(win) {
    83     if (mcWindows.selectedWindow != null)
    84         mcWindows.selectedWindow.close();
    85     else
     92    var gotit = false, n, w;
     93    for (n in mcWindows.windows) {
     94        w = mcWindows.windows[n];
     95        if (typeof(w) == 'function') continue;
     96        if (win.name == w.id + '_iframe') {
     97            w.close();
     98            gotit = true;
     99        }
     100    }
     101    if (!gotit)
    86102        this.orgCloseWindow(win);
     103
     104    tinyMCE.selectedInstance.getWin().focus();
    87105};
    88106
     
    112130    this.selectedWindow = null;
    113131    this.lastSelectedWindow = null;
    114     this.zindex = 100;
     132    this.zindex = 1001;
    115133    this.mouseDownScreenX = 0;
    116134    this.mouseDownScreenY = 0;
     
    132150    this.addEvent(document, "mouseup", mcWindows.eventDispatcher);
    133151
     152    this.addEvent(window, "resize", mcWindows.eventDispatcher);
     153    this.addEvent(document, "scroll", mcWindows.eventDispatcher);
     154
    134155    this.doc = document;
     156};
     157
     158TinyMCE_Windows.prototype.getBounds = function() {
     159    if (!this.bounds) {
     160        var vp = tinyMCE.getViewPort(window);
     161        var top, left, bottom, right, docEl = this.doc.documentElement;
     162
     163        top    = vp.top;
     164        left   = vp.left;
     165        bottom = vp.height + top - 2;
     166        right  = vp.width  + left - 22; // TODO this number is platform dependant
     167        // x1, y1, x2, y2
     168        this.bounds = [left, top, right, bottom];
     169    }
     170    return this.bounds;
     171};
     172
     173TinyMCE_Windows.prototype.clampBoxPosition = function(x, y, w, h, minW, minH) {
     174    var bounds = this.getBounds();
     175
     176    x = Math.max(bounds[0], Math.min(bounds[2], x + w) - w);
     177    y = Math.max(bounds[1], Math.min(bounds[3], y + h) - h);
     178
     179    return this.clampBoxSize(x, y, w, h, minW, minH);
     180};
     181
     182TinyMCE_Windows.prototype.clampBoxSize = function(x, y, w, h, minW, minH) {
     183    var bounds = this.getBounds();
     184
     185    return [
     186        x, y,
     187        Math.max(minW, Math.min(bounds[2], x + w) - x),
     188        Math.max(minH, Math.min(bounds[3], y + h) - y)
     189    ];
    135190};
    136191
     
    183238            mcWindows.selectedWindow.onFocus(e);
    184239            break;
     240        case "scroll":
     241        case "resize":
     242            if (mcWindows.clampUpdateTimeout)
     243                clearTimeout(mcWindows.clampUpdateTimeout);
     244            mcWindows.clampEventType = e.type;
     245            mcWindows.clampUpdateTimeout =
     246                setTimeout(function () {mcWindows.updateClamping()}, 100);
     247            break;
     248    }
     249};
     250
     251TinyMCE_Windows.prototype.updateClamping = function () {
     252    var clamp, oversize, etype = mcWindows.clampEventType;
     253
     254    this.bounds = null; // Recalc window bounds on resize/scroll
     255    this.clampUpdateTimeout = null;
     256
     257    for (var n in this.windows) {
     258        win = this.windows[n];
     259        if (typeof(win) == 'function' || ! win.winElement) continue;
     260
     261        clamp = mcWindows.clampBoxPosition(
     262            win.left, win.top,
     263            win.winElement.scrollWidth,
     264            win.winElement.scrollHeight,
     265            win.features.minWidth,
     266            win.features.minHeight
     267        );
     268        oversize = (
     269            clamp[2] != win.winElement.scrollWidth ||
     270            clamp[3] != win.winElement.scrollHeight
     271        ) ? true : false;
     272
     273        if (!oversize || win.features.resizable == "yes" || etype != "scroll")
     274            win.moveTo(clamp[0], clamp[1]);
     275        if (oversize && win.features.resizable == "yes")
     276            win.resizeTo(clamp[2], clamp[3]);
    185277    }
    186278};
     
    190282        obj.attachEvent("on" + name, handler);
    191283    else
    192         obj.addEventListener(name, handler, true);
     284        obj.addEventListener(name, handler, false);
    193285};
    194286
     
    214306    options['width'] = "300";
    215307    options['height'] = "300";
     308    options['minwidth'] = "100";
     309    options['minheight'] = "100";
    216310    options['resizable'] = "yes";
    217311    options['minimizable'] = "yes";
     
    237331    options['width'] = parseInt(options['width']);
    238332    options['height'] = parseInt(options['height']);
     333    options['minWidth'] = parseInt(options['minwidth']);
     334    options['minHeight'] = parseInt(options['minheight']);
    239335
    240336    return options;
     
    249345
    250346    features = this.parseFeatures(features);
     347
     348    // Clamp specified dimensions
     349    var clamp = mcWindows.clampBoxPosition(
     350        features['left'], features['top'],
     351        features['width'], features['height'],
     352        features['minWidth'], features['minHeight']
     353    );
     354
     355    features['left'] = clamp[0];
     356    features['top'] = clamp[1];
     357
     358    if (features['resizable'] == "yes") {
     359        features['width'] = clamp[2];
     360        features['height'] = clamp[3];
     361    }
    251362
    252363    // Create div
     
    282393    html += '<head>';
    283394    html += '<title>Wrapper iframe</title>';
     395    if (this.isMac) html += '<style type="text/css">.mceWindowTitle{float:none;margin:0;width:100%;text-align:center;}.mceWindowClose{float:none;position:absolute;left:0px;top:0px;}</style>';
    284396    html += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">';
    285397    html += '<link href="' + this.getParam("css_file") + '" rel="stylesheet" type="text/css" />';
    286     if ( this.isMac ) html += '<style type="text/css">.mceWindowTitle{float:none;margin:0;text-align:center;}.mceWindowClose{float:none;position:absolute;left:0px;top:0px;}</style>';
    287398    html += '</head>';
    288399    html += '<body onload="parent.mcWindows.onLoad(\'' + name + '\');">';
     
    294405    html += '    <div class="mceWindowHeadTools">';
    295406    html += '      <a href="javascript:parent.mcWindows.windows[\'' + name + '\'].close();" target="_self" onmousedown="return false;" class="mceWindowClose"><img border="0" src="' + imgPath + '/window_close.gif" /></a>';
    296 //  html += '      <a href="javascript:mcWindows.windows[\'' + name + '\'].maximize();" target="_self" onmousedown="return false;" class="mceWindowMaximize"></a>';
    297 //  html += '      <a href="javascript:mcWindows.windows[\'' + name + '\'].minimize();" target="_self" onmousedown="return false;" class="mceWindowMinimize"></a>';
     407    if (features['resizable'] == "yes" && features['maximizable'] == "yes")
     408        html += '      <a href="javascript:parent.mcWindows.windows[\'' + name + '\'].maximize();" target="_self" onmousedown="return false;" class="mceWindowMaximize"><img border="0" src="' + imgPath + '/window_maximize.gif" /></a>';
     409    // html += '      <a href="javascript:mcWindows.windows[\'' + name + '\'].minimize();" target="_self" onmousedown="return false;" class="mceWindowMinimize"></a>';
    298410    html += '    </div>';
    299411    html += '</div><div id="' + id + '_body" class="mceWindowBody" style="width: ' + width + 'px; height: ' + height + 'px;">';
     
    324436// Blocks the document events by placing a image over the whole document
    325437TinyMCE_Windows.prototype.setDocumentLock = function(state) {
     438    var elm = document.getElementById('mcWindowEventBlocker');
     439
    326440    if (state) {
    327         var elm = document.getElementById('mcWindowEventBlocker');
    328441        if (elm == null) {
    329442            elm = document.createElement("div");
     
    349462        elm.style.zIndex = mcWindows.zindex-1;
    350463        elm.style.display = "block";
    351     } else {
    352         var elm = document.getElementById('mcWindowEventBlocker');
    353 
     464    } else if (elm != null) {
    354465        if (mcWindows.windows.length == 0)
    355466            elm.parentNode.removeChild(elm);
     
    445556    div.setAttribute("height", (height));
    446557    div.style.position = "absolute";
     558
    447559    div.style.left = left + "px";
    448560    div.style.top = top + "px";
     
    471583    iframe.setAttribute("width", iframeWidth);
    472584    iframe.setAttribute("height", iframeHeight);
    473 //  iframe.setAttribute("src", "../jscripts/tiny_mce/blank.htm");
     585    // iframe.setAttribute("src", "../jscripts/tiny_mce/blank.htm");
    474586    // iframe.setAttribute("allowtransparency", "false");
    475587    iframe.setAttribute("scrolling", "no");
     
    520632
    521633TinyMCE_Window.prototype.maximize = function() {
    522    
     634    if (this.restoreSize) {
     635        this.moveTo(this.restoreSize[0], this.restoreSize[1]);
     636        this.resizeTo(this.restoreSize[2], this.restoreSize[3]);
     637        this.updateClamping();
     638        this.restoreSize = null;
     639    } else {
     640        var bounds = mcWindows.getBounds();
     641        this.restoreSize = [
     642            this.left, this.top,
     643            this.winElement.scrollWidth,
     644            this.winElement.scrollHeight
     645        ];
     646        this.moveTo(bounds[0], bounds[1]);
     647        this.resizeTo(
     648            bounds[2] - bounds[0],
     649            bounds[3] - bounds[1]
     650        );
     651    }
    523652};
    524653
     
    550679    mcWindows.windows = mcWindowsNew;
    551680
    552 //  alert(mcWindows.doc.getElementById(this.id + "_iframe"));
     681    // alert(mcWindows.doc.getElementById(this.id + "_iframe"));
    553682
    554683    var e = mcWindows.doc.getElementById(this.id + "_iframe");
     
    559688
    560689    mcWindows.setDocumentLock(false);
    561 
    562     tinyMCE.selectedInstance.getWin().focus();
    563690};
    564691
    565692TinyMCE_Window.prototype.onMouseMove = function(e) {
    566     var scrollX = 0;//this.doc.body.scrollLeft;
    567     var scrollY = 0;//this.doc.body.scrollTop;
    568 
     693    var clamp;
    569694    // Calculate real X, Y
    570695    var dx = e.screenX - mcWindows.mouseDownScreenX;
     
    573698    switch (mcWindows.action) {
    574699        case "resize":
    575             width = mcWindows.mouseDownWidth + (e.screenX - mcWindows.mouseDownScreenX);
    576             height = mcWindows.mouseDownHeight + (e.screenY - mcWindows.mouseDownScreenY);
    577 
    578             width = width < 100 ? 100 : width;
    579             height = height < 100 ? 100 : height;
    580 
    581             this.wrapperIFrameElement.style.width = width+2;
    582             this.wrapperIFrameElement.style.height = height+2;
    583             this.wrapperIFrameElement.width = width+2;
    584             this.wrapperIFrameElement.height = height+2;
    585             this.winElement.style.width = width;
    586             this.winElement.style.height = height;
    587 
    588             height = height - this.deltaHeight;
    589 
    590             this.containerElement.style.width = width;
    591 
    592             this.iframeElement.style.width = width;
    593             this.iframeElement.style.height = height;
    594             this.bodyElement.style.width = width;
    595             this.bodyElement.style.height = height;
    596             this.headElement.style.width = width;
    597             //this.statusElement.style.width = width;
     700            clamp = mcWindows.clampBoxSize(
     701                this.left, this.top,
     702                mcWindows.mouseDownWidth + (e.screenX - mcWindows.mouseDownScreenX),
     703                mcWindows.mouseDownHeight + (e.screenY - mcWindows.mouseDownScreenY),
     704                this.features.minWidth, this.features.minHeight
     705            );
     706
     707            this.resizeTo(clamp[2], clamp[3]);
    598708
    599709            mcWindows.cancelEvent(e);
     
    603713            this.left = mcWindows.mouseDownLayerX + (e.screenX - mcWindows.mouseDownScreenX);
    604714            this.top = mcWindows.mouseDownLayerY + (e.screenY - mcWindows.mouseDownScreenY);
    605             this.winElement.style.left = this.left + "px";
    606             this.winElement.style.top = this.top + "px";
     715            this.updateClamping();
    607716
    608717            mcWindows.cancelEvent(e);
    609718            break;
    610719    }
     720};
     721
     722TinyMCE_Window.prototype.moveTo = function (x, y) {
     723    this.left = x;
     724    this.top = y;
     725
     726    this.winElement.style.left = this.left + "px";
     727    this.winElement.style.top = this.top + "px";
     728};
     729
     730TinyMCE_Window.prototype.resizeTo = function (width, height) {
     731    this.wrapperIFrameElement.style.width = (width+2) + 'px';
     732    this.wrapperIFrameElement.style.height = (height+2) + 'px';
     733    this.wrapperIFrameElement.width = width+2;
     734    this.wrapperIFrameElement.height = height+2;
     735    this.winElement.style.width = width + 'px';
     736    this.winElement.style.height = height + 'px';
     737
     738    height = height - this.deltaHeight;
     739
     740    this.containerElement.style.width = width + 'px';
     741    this.iframeElement.style.width = width + 'px';
     742    this.iframeElement.style.height = height + 'px';
     743    this.bodyElement.style.width = width + 'px';
     744    this.bodyElement.style.height = height + 'px';
     745    this.headElement.style.width = width + 'px';
     746    //this.statusElement.style.width = width + 'px';
     747};
     748
     749TinyMCE_Window.prototype.updateClamping = function () {
     750    var clamp, oversize;
     751
     752    clamp = mcWindows.clampBoxPosition(
     753        this.left, this.top,
     754        this.winElement.scrollWidth,
     755        this.winElement.scrollHeight,
     756        this.features.minWidth, this.features.minHeight
     757    );
     758    oversize = (
     759        clamp[2] != this.winElement.scrollWidth ||
     760        clamp[3] != this.winElement.scrollHeight
     761    ) ? true : false;
     762
     763    this.moveTo(clamp[0], clamp[1]);
     764    if (this.features.resizable == "yes" && oversize)
     765        this.resizeTo(clamp[2], clamp[3]);
    611766};
    612767
     
    637792TinyMCE_Window.prototype.onMouseDown = function(e) {
    638793    var elm = mcWindows.isMSIE ? this.wrapperFrame.event.srcElement : e.target;
    639 
    640     var scrollX = 0;//this.doc.body.scrollLeft;
    641     var scrollY = 0;//this.doc.body.scrollTop;
    642794
    643795    mcWindows.mouseDownScreenX = e.screenX;
  • tags/2.2/wp-includes/js/tinymce/plugins/paste/editor_plugin.js

    r5468 r5480  
    11/**
    2  * $Id: editor_plugin_src.js 126 2006-10-22 16:19:55Z spocke $
     2 * $Id: editor_plugin_src.js 201 2007-02-12 15:56:56Z spocke $
    33 *
    44 * @author Moxiecode
    5  * @copyright Copyright © 2004-2006, Moxiecode Systems AB, All rights reserved.
     5 * @copyright Copyright © 2004-2007, Moxiecode Systems AB, All rights reserved.
    66 */
    77
     
    1515            author : 'Moxiecode Systems AB',
    1616            authorurl : 'http://tinymce.moxiecode.com',
    17             infourl : 'http://tinymce.moxiecode.com/tinymce/docs/plugin_paste.html',
     17            infourl : 'http://wiki.moxiecode.com/index.php/TinyMCE:Plugins/paste',
    1818            version : tinyMCE.majorVersion + "." + tinyMCE.minorVersion
    1919        };
     
    2323        if (tinyMCE.isMSIE && tinyMCE.getParam("paste_auto_cleanup_on_paste", false))
    2424            tinyMCE.addEvent(inst.getBody(), "paste", TinyMCE_PastePlugin._handlePasteEvent);
     25    },
     26
     27    handleEvent : function(e) {
     28        // Force paste dialog if non IE browser
     29        if (!tinyMCE.isRealIE && tinyMCE.getParam("paste_auto_cleanup_on_paste", false) && e.ctrlKey && e.keyCode == 86 && e.type == "keydown") {
     30            window.setTimeout('tinyMCE.selectedInstance.execCommand("mcePasteText",true)', 1);
     31            return tinyMCE.cancelEvent(e);
     32        }
     33
     34        return true;
    2535    },
    2636
  • tags/2.2/wp-includes/js/tinymce/plugins/spellchecker/classes/TinyGoogleSpell.class.php

    r5468 r5480  
    11<?php
    2 /* * 
     2/* *
    33 * Tiny Spelling Interface for TinyMCE Spell Checking.
    44 *
    55 * Copyright © 2006 Moxiecode Systems AB
    66 */
    7 
    8 require_once("HttpClient.class.php");
    97
    108class TinyGoogleSpell {
     
    2321
    2422        for ($i=0; $i<count($matches); $i++)
    25             $words[] = substr($wordstr, $matches[$i][1], $matches[$i][2]);
     23            $words[] = $this->unhtmlentities(mb_substr($wordstr, $matches[$i][1], $matches[$i][2], "UTF-8"));
    2624
    2725        return $words;
     26    }
     27
     28    function unhtmlentities($string) {
     29        $string = preg_replace('~&#x([0-9a-f]+);~ei', 'chr(hexdec("\\1"))', $string);
     30        $string = preg_replace('~&#([0-9]+);~e', 'chr(\\1)', $string);
     31
     32        $trans_tbl = get_html_translation_table(HTML_ENTITIES);
     33        $trans_tbl = array_flip($trans_tbl);
     34
     35        return strtr($string, $trans_tbl);
    2836    }
    2937
     
    3543
    3644        if (count($matches) > 0)
    37             $sug = explode("\t", $matches[0][4]);
     45            $sug = explode("\t", utf8_encode($this->unhtmlentities($matches[0][4])));
    3846
    3947        return $sug;
    4048    }
    4149
     50    function _xmlChars($string) {
     51       $trans = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES);
     52   
     53       foreach ($trans as $k => $v)
     54            $trans[$k] = "&#".ord($k).";";
     55
     56       return strtr($string, $trans);
     57    }
     58
    4259    function _getMatches($word_list) {
    43         $xml = "";
    44 
    45         // Setup HTTP Client
    46         $client = new HttpClient('www.google.com');
    47         $client->setUserAgent('Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR');
    48         $client->setHandleRedirects(false);
    49         $client->setDebug(false);
     60        $server = "www.google.com";
     61        $port = 443;
     62        $path = "/tbproxy/spell?lang=" . $this->lang . "&hl=en";
     63        $host = "www.google.com";
     64        $url = "https://" . $server;
    5065
    5166        // Setup XML request
    52         $xml .= '<?xml version="1.0" encoding="utf-8" ?>';
    53         $xml .= '<spellrequest textalreadyclipped="0" ignoredups="0" ignoredigits="1" ignoreallcaps="1">';
    54         $xml .= '<text>' . htmlentities($word_list) . '</text></spellrequest>';
     67        $xml = '<?xml version="1.0" encoding="utf-8" ?><spellrequest textalreadyclipped="0" ignoredups="0" ignoredigits="1" ignoreallcaps="1"><text>' . $word_list . '</text></spellrequest>';
    5568
    56         // Execute HTTP Post to Google
    57         if (!$client->post('/tbproxy/spell?lang=' . $this->lang, $xml)) {
    58             $this->errorMsg[] = 'An error occurred: ' . $client->getError();
    59             return array();
     69        $header  = "POST ".$path." HTTP/1.0 \r\n";
     70        $header .= "MIME-Version: 1.0 \r\n";
     71        $header .= "Content-type: application/PTI26 \r\n";
     72        $header .= "Content-length: ".strlen($xml)." \r\n";
     73        $header .= "Content-transfer-encoding: text \r\n";
     74        $header .= "Request-number: 1 \r\n";
     75        $header .= "Document-type: Request \r\n";
     76        $header .= "Interface-Version: Test 1.4 \r\n";
     77        $header .= "Connection: close \r\n\r\n";
     78        $header .= $xml;
     79        //$this->_debugData($xml);
     80
     81        // Use curl if it exists
     82        if (function_exists('curl_init')) {
     83            // Use curl
     84            $ch = curl_init();
     85            curl_setopt($ch, CURLOPT_URL,$url);
     86            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
     87            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $header);
     88            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
     89            $xml = curl_exec($ch);
     90            curl_close($ch);
     91        } else {
     92            // Use raw sockets
     93            $fp = fsockopen("ssl://" . $server, $port, $errno, $errstr, 30);
     94            if ($fp) {
     95                // Send request
     96                fwrite($fp, $header);
     97
     98                // Read response
     99                $xml = "";
     100                while (!feof($fp))
     101                    $xml .= fgets($fp, 128);
     102
     103                fclose($fp);
     104            } else
     105                echo "Could not open SSL connection to google.";
    60106        }
    61107
     108        //$this->_debugData($xml);
     109
    62110        // Grab and parse content
    63         $xml = $client->getContent();
    64111        preg_match_all('/<c o="([^"]*)" l="([^"]*)" s="([^"]*)">([^<]*)<\/c>/', $xml, $matches, PREG_SET_ORDER);
    65112
    66113        return $matches;
     114    }
     115
     116    function _debugData($data) {
     117        $fh = @fopen("debug.log", 'a+');
     118        @fwrite($fh, $data);
     119        @fclose($fh);
    67120    }
    68121}
  • tags/2.2/wp-includes/js/tinymce/plugins/spellchecker/classes/TinyPspellShell.class.php

    r5468 r5480  
    66 *
    77 */
     8
    89
    910class TinyPspellShell {
     
    2829
    2930        $this->tmpfile = tempnam($config['tinypspellshell.tmp'], "tinyspell");
    30         $this->cmd = "cat ". $this->tmpfile ." | " . $config['tinypspellshell.aspell'] . " -a --lang=". $this->lang;
     31
     32        if(preg_match("#win#i",php_uname()))
     33            $this->cmd = $config['tinypspellshell.aspell'] . " -a --lang=". $this->lang." --encoding=utf-8 -H < $this->tmpfile 2>&1";
     34        else
     35            $this->cmd = "cat ". $this->tmpfile ." | " . $config['tinypspellshell.aspell'] . " -a --encoding=utf-8 -H --lang=". $this->lang;
    3136    }
    3237
     
    3742            foreach($wordArray as $key => $value)
    3843                fwrite($fh, "^" . $value . "\n");
    39 
    4044            fclose($fh);
    4145        } else {
     
    4549
    4650        $data = shell_exec($this->cmd);
    47         @unlink($this->tmpfile);
     51        @unlink($this->tmpfile);
     52       
    4853        $returnData = array();
    4954        $dataArr = preg_split("/\n/", $data, -1, PREG_SPLIT_NO_EMPTY);
     
    6772    // Returns array with suggestions or false if failed.
    6873    function getSuggestion($word) {
     74        if (function_exists("mb_convert_encoding"))
     75            $word = mb_convert_encoding($word, "ISO-8859-1", mb_detect_encoding($word, "UTF-8"));
     76        else
     77            $word = utf8_encode($word);
     78
    6979        if ($fh = fopen($this->tmpfile, "w")) {
    7080            fwrite($fh, "!\n");
     
    7282            fclose($fh);
    7383        } else
    74             wp_die("Error opening tmp file.");
     84            die("Error opening tmp file.");
    7585
    7686        $data = shell_exec($this->cmd);
    77         @unlink($this->tmpfile);
     87
     88        @unlink($this->tmpfile);
     89
    7890        $returnData = array();
    7991        $dataArr = preg_split("/\n/", $data, -1, PREG_SPLIT_NO_EMPTY);
     
    95107        return $returnData;
    96108    }
     109
     110    function _debugData($data) {
     111        $fh = @fopen("debug.log", 'a+');
     112        @fwrite($fh, $data);
     113        @fclose($fh);
     114    }
     115
    97116}
    98117
  • tags/2.2/wp-includes/js/tinymce/plugins/spellchecker/config.php

    r5468 r5480  
    22    $spellCheckerConfig = array();
    33
     4    // Spellchecker class use
     5    // require_once("classes/TinyPspellShell.class.php"); // Command line pspell
     6    require_once("classes/TinyGoogleSpell.class.php"); // Google web service
     7    // require_once("classes/TinyPspell.class.php"); // Internal PHP version
     8
    49    // General settings
    510    $spellCheckerConfig['enabled'] = true;
    6 
    7     // Pspell shell specific settings
    8     $spellCheckerConfig['tinypspellshell.aspell'] = '/usr/bin/aspell';
    9     $spellCheckerConfig['tinypspellshell.tmp'] = '/tmp/tinyspell/0';
    1011
    1112    // Default settings
     
    1819    $spellCheckerConfig['default.encoding'] = "";
    1920
    20     // Spellchecker class use
    21     if ( function_exists('pspell_new') )
    22         require_once("classes/TinyPspell.class.php"); // Internal PHP version
    23 
    24     elseif ( file_exists($spellCheckerConfig['tinypspellshell.aspell']) )
    25         require_once("classes/TinyPspellShell.class.php"); // Command line pspell
    26 
    27     else
    28         require_once("classes/TinyGoogleSpell.class.php"); // Google web service
     21    // Pspell shell specific settings
     22    $spellCheckerConfig['tinypspellshell.aspell'] = '/usr/bin/aspell';
     23    $spellCheckerConfig['tinypspellshell.tmp'] = '/tmp';
    2924?>
  • tags/2.2/wp-includes/js/tinymce/plugins/spellchecker/css/content.css

    r5468 r5480  
    11.mceItemHiddenSpellWord {
    22    background: url('../images/wline.gif') repeat-x bottom left;
    3     bo2rder-bottom: 1px dashed red;
    43    cursor: default;
    54}
  • tags/2.2/wp-includes/js/tinymce/plugins/spellchecker/css/spellchecker.css

    r5468 r5480  
    3232    font-weight: bold;
    3333    font-size: 11px;
     34    background-color: #FFF;
    3435}
  • tags/2.2/wp-includes/js/tinymce/plugins/spellchecker/editor_plugin.js

    r5468 r5480  
    1 /**
    2  * $RCSfile: editor_plugin_src.js,v $
    3  * $Revision: 1.4 $
    4  * $Date: 2006/03/24 17:24:50 $
    5  *
    6  * @author Moxiecode
    7  * @copyright Copyright © 2004-2006, Moxiecode Systems AB, All rights reserved.
    8  */
    9 
    10 tinyMCE.importPluginLanguagePack('spellchecker', 'en,sv,nn,nb');
    11 
    12 // Plucin static class
    13 var TinyMCE_SpellCheckerPlugin = {
    14     _contextMenu : new TinyMCE_Menu(),
    15     _menu : new TinyMCE_Menu(),
    16     _counter : 0,
    17 
    18     getInfo : function() {
    19         return {
    20             longname : 'Spellchecker',
    21             author : 'Moxiecode Systems AB',
    22             authorurl : 'http://tinymce.moxiecode.com',
    23             infourl : 'http://tinymce.moxiecode.com/tinymce/docs/plugin_spellchecker.html',
    24             version : tinyMCE.majorVersion + "." + tinyMCE.minorVersion
    25         };
    26     },
    27 
    28     handleEvent : function(e) {
    29         var elm = tinyMCE.isMSIE ? e.srcElement : e.target;
    30         var inst = tinyMCE.selectedInstance, args = '';
    31         var self = TinyMCE_SpellCheckerPlugin;
    32         var cm = self._contextMenu;
    33         var p, p2, x, y, sx, sy, h, elm;
    34 
    35         // Handle click on word
    36         if ((e.type == "click" || e.type == "contextmenu") && elm) {
    37             do {
    38                 if (tinyMCE.getAttrib(elm, 'class') == "mceItemHiddenSpellWord") {
    39                     inst.spellCheckerElm = elm;
    40 
    41                     // Setup arguments
    42                     args += 'id=' + inst.editorId + "|" + (++self._counter);
    43                     args += '&cmd=suggest&check=' + escape(elm.innerHTML);
    44                     args += '&lang=' + escape(inst.spellCheckerLang);
    45 
    46                     elm = inst.spellCheckerElm;
    47                     p = tinyMCE.getAbsPosition(inst.iframeElement);
    48                     p2 = tinyMCE.getAbsPosition(elm);
    49                     h = parseInt(elm.offsetHeight);
    50                     sx = inst.getBody().scrollLeft;
    51                     sy = inst.getBody().scrollTop;
    52                     x = p.absLeft + p2.absLeft - sx;
    53                     y = p.absTop + p2.absTop - sy + h;
    54 
    55                     cm.clear();
    56                     cm.addTitle(tinyMCE.getLang('lang_spellchecker_wait', '', true));
    57                     cm.show();
    58                     cm.moveTo(x, y);
    59 
    60                     inst.selection.selectNode(elm, false, false);
    61 
    62                     self._sendAjax(self.baseURL + "/tinyspell.php", self._ajaxResponse, 'post', args);
    63 
    64                     tinyMCE.cancelEvent(e);
    65                     return false;
    66                 }
    67             } while ((elm = elm.parentNode));
    68         }
    69 
    70         return true;
    71     },
    72 
    73     initInstance : function(inst) {
    74         var self = TinyMCE_SpellCheckerPlugin, m = self._menu, cm = self._contextMenu, e;
    75 
    76         tinyMCE.importCSS(inst.getDoc(), tinyMCE.baseURL + "/plugins/spellchecker/css/content.css");
    77 
    78         if (!tinyMCE.hasMenu('spellcheckercontextmenu')) {
    79             tinyMCE.importCSS(document, tinyMCE.baseURL + "/plugins/spellchecker/css/spellchecker.css");
    80 
    81             cm.init({drop_menu : false});
    82             tinyMCE.addMenu('spellcheckercontextmenu', cm);
    83         }
    84 
    85         if (!tinyMCE.hasMenu('spellcheckermenu')) {
    86             m.init({});
    87             tinyMCE.addMenu('spellcheckermenu', m);
    88         }
    89 
    90         inst.spellCheckerLang = 'en';
    91         self._buildSettingsMenu(inst, null);
    92 
    93         e = self._getBlockBoxLayer(inst).create('div', 'mceBlockBox', document.getElementById(inst.editorId + '_parent'));
    94         self._getMsgBoxLayer(inst).create('div', 'mceMsgBox', document.getElementById(inst.editorId + '_parent'));
    95     },
    96 
    97     _getMsgBoxLayer : function(inst) {
    98         if (!inst.spellCheckerMsgBoxL)
    99             inst.spellCheckerMsgBoxL = new TinyMCE_Layer(inst.editorId + '_spellcheckerMsgBox', false);
    100 
    101         return inst.spellCheckerMsgBoxL;
    102     },
    103 
    104     _getBlockBoxLayer : function(inst) {
    105         if (!inst.spellCheckerBoxL)
    106             inst.spellCheckerBoxL = new TinyMCE_Layer(inst.editorId + '_spellcheckerBlockBox', false);
    107 
    108         return inst.spellCheckerBoxL;
    109     },
    110 
    111     _buildSettingsMenu : function(inst, lang) {
    112         var i, ar = tinyMCE.getParam('spellchecker_languages', '+English=en').split(','), p;
    113         var self = TinyMCE_SpellCheckerPlugin, m = self._menu, c;
    114 
    115         m.clear();
    116         m.addTitle(tinyMCE.getLang('lang_spellchecker_langs', '', true));
    117 
    118         for (i=0; i<ar.length; i++) {
    119             if (ar[i] != '') {
    120                 p = ar[i].split('=');
    121                 c = 'mceMenuCheckItem';
    122 
    123                 if (p[0].charAt(0) == '+') {
    124                     p[0] = p[0].substring(1);
    125 
    126                     if (lang == null) {
    127                         c = 'mceMenuSelectedItem';
    128                         inst.spellCheckerLang = p[1];
    129                     }
    130                 }
    131 
    132                 if (lang == p[1])
    133                     c = 'mceMenuSelectedItem';
    134 
    135                 m.add({text : p[0], js : "tinyMCE.execInstanceCommand('" + inst.editorId + "','mceSpellCheckerSetLang',false,'" + p[1] + "');", class_name : c});
    136             }
    137         }
    138     },
    139 
    140     setupContent : function(editor_id, body, doc) {
    141         TinyMCE_SpellCheckerPlugin._removeWords(doc);
    142     },
    143 
    144     getControlHTML : function(cn) {
    145         switch (cn) {
    146             case "spellchecker":
    147                 return TinyMCE_SpellCheckerPlugin._getMenuButtonHTML(cn, 'lang_spellchecker_desc', '{$pluginurl}/images/spellchecker.gif', 'lang_spellchecker_desc', 'mceSpellCheckerMenu', 'mceSpellCheck');
    148         }
    149 
    150         return "";
    151     },
    152 
    153     /**
    154      * Returns the HTML code for a normal button control.
    155      *
    156      * @param {string} id Button control id, this will be the suffix for the element id, the prefix is the editor id.
    157      * @param {string} lang Language variable key name to insert as the title/alt of the button image.
    158      * @param {string} img Image URL to insert, {$themeurl} and {$pluginurl} will be replaced.
    159      * @param {string} mlang Language variable key name to insert as the title/alt of the menu button image.
    160      * @param {string} mid Menu by id to display when the menu button is pressed.
    161      * @param {string} cmd Command to execute when the user clicks the button.
    162      * @param {string} ui Optional user interface boolean for command.
    163      * @param {string} val Optional value for command.
    164      * @return HTML code for a normal button based in input information.
    165      * @type string
    166      */
    167     _getMenuButtonHTML : function(id, lang, img, mlang, mid, cmd, ui, val) {
    168         var h = '', m, x;
    169 
    170         cmd = 'tinyMCE.hideMenus();tinyMCE.execInstanceCommand(\'{$editor_id}\',\'' + cmd + '\'';
    171 
    172         if (typeof(ui) != "undefined" && ui != null)
    173             cmd += ',' + ui;
    174 
    175         if (typeof(val) != "undefined" && val != null)
    176             cmd += ",'" + val + "'";
    177 
    178         cmd += ');';
    179 
    180         // Use tilemaps when enabled and found and never in MSIE since it loads the tile each time from cache if cahce is disabled
    181         if (tinyMCE.getParam('button_tile_map') && (!tinyMCE.isMSIE || tinyMCE.isOpera) && (m = tinyMCE.buttonMap[id]) != null && (tinyMCE.getParam("language") == "en" || img.indexOf('$lang') == -1)) {
    182             // Tiled button
    183             x = 0 - (m * 20) == 0 ? '0' : 0 - (m * 20);
    184             h += '<a id="{$editor_id}_' + id + '" href="javascript:' + cmd + '" onclick="' + cmd + 'return false;" onmousedown="return false;" class="mceTiledButton mceButtonNormal" target="_self">';
    185             h += '<img src="{$themeurl}/images/spacer.gif" style="background-position: ' + x + 'px 0" title="{$' + lang + '}" />';
    186             h += '<img src="{$themeurl}/images/button_menu.gif" title="{$' + lang + '}" class="mceMenuButton" onclick="' + mcmd + 'return false;" />';
    187             h += '</a>';
    188         } else {
    189             if (tinyMCE.isMSIE && !tinyMCE.isOpera)
    190                 h += '<span id="{$editor_id}_' + id + '" class="mceMenuButton" onmouseover="tinyMCE.plugins.spellchecker._menuButtonEvent(\'over\',this);" onmouseout="tinyMCE.plugins.spellchecker._menuButtonEvent(\'out\',this);">';
    191             else
    192                 h += '<span id="{$editor_id}_' + id + '" class="mceMenuButton">';
    193 
    194             h += '<a href="javascript:' + cmd + '" onclick="' + cmd + 'return false;" onmousedown="return false;" class="mceMenuButtonNormal" target="_self">';
    195             h += '<img src="' + img + '" title="{$' + lang + '}" /></a>';
    196             h += '<a href="#" onclick="tinyMCE.plugins.spellchecker._toggleMenu(\'{$editor_id}\',\'' + mid + '\');return false;" onmousedown="return false;"><img src="{$themeurl}/images/button_menu.gif" title="{$' + lang + '}" class="mceMenuButton" />';
    197             h += '</a></span>';
    198         }
    199 
    200         return h;
    201     },
    202 
    203     _menuButtonEvent : function(e, o) {
    204         if (o.className == 'mceMenuButtonFocus')
    205             return;
    206 
    207         if (e == 'over')
    208             o.className = o.className + ' mceMenuHover';
    209         else
    210             o.className = o.className.replace(/\s.*$/, '');
    211     },
    212 
    213     _toggleMenu : function(editor_id, id) {
    214         var self = TinyMCE_SpellCheckerPlugin;
    215         var e = document.getElementById(editor_id + '_spellchecker');
    216         var inst = tinyMCE.getInstanceById(editor_id);
    217 
    218         if (self._menu.isVisible()) {
    219             tinyMCE.hideMenus();
    220             return;
    221         }
    222 
    223         tinyMCE.lastMenuBtnClass = e.className.replace(/\s.*$/, '');
    224         tinyMCE.switchClass(editor_id + '_spellchecker', 'mceMenuButtonFocus');
    225 
    226         self._menu.moveRelativeTo(e, 'bl');
    227         self._menu.moveBy(tinyMCE.isMSIE && !tinyMCE.isOpera ? 0 : 1, -1);
    228 
    229         if (tinyMCE.isOpera)
    230             self._menu.moveBy(0, -2);
    231 
    232         self._onMenuEvent(inst, self._menu, 'show');
    233 
    234         self._menu.show();
    235 
    236         tinyMCE.lastSelectedMenuBtn = editor_id + '_spellchecker';
    237     },
    238 
    239     _onMenuEvent : function(inst, m, n) {
    240         TinyMCE_SpellCheckerPlugin._buildSettingsMenu(inst, inst.spellCheckerLang);
    241     },
    242 
    243     execCommand : function(editor_id, element, command, user_interface, value) {
    244         var inst = tinyMCE.getInstanceById(editor_id), self = TinyMCE_SpellCheckerPlugin, args = '', co, bb, mb, nl, i, e;
    245 
    246         // Handle commands
    247         switch (command) {
    248             case "mceSpellCheck":
    249                 if (!inst.spellcheckerOn) {
    250                     inst.spellCheckerBookmark = inst.selection.getBookmark();
    251 
    252                     // Setup arguments
    253                     args += 'id=' + inst.editorId + "|" + (++self._counter);
    254                     args += '&cmd=spell&check=' + escape(self._getWordList(inst.getBody())).replace(/%20/g, '+');
    255                     args += '&lang=' + escape(inst.spellCheckerLang);
    256 
    257                     co = document.getElementById(inst.editorId + '_parent').firstChild;
    258                     bb = self._getBlockBoxLayer(inst);
    259                     bb.moveRelativeTo(co, 'tl');
    260                     bb.resizeTo(co.offsetWidth, co.offsetHeight);
    261                     bb.show();
    262 
    263                     // Setup message box
    264                     mb = self._getMsgBoxLayer(inst);
    265                     e = mb.getElement();
    266                     e.innerHTML = '<span>' + tinyMCE.getLang('lang_spellchecker_swait', '', true) + '</span>';
    267                     mb.show();
    268                     mb.moveRelativeTo(co, 'cc');
    269 
    270                     if (tinyMCE.isMSIE && !tinyMCE.isOpera) {
    271                         nl = co.getElementsByTagName('select');
    272                         for (i=0; i<nl.length; i++)
    273                             nl[i].disabled = true;
    274                     }
    275 
    276                     inst.spellcheckerOn = true;
    277                     tinyMCE.switchClass(editor_id + '_spellchecker', 'mceMenuButtonSelected');
    278 
    279                     self._sendAjax(self.baseURL + "/tinyspell.php", self._ajaxResponse, 'post', args);
    280                 } else {
    281                     self._removeWords(inst.getDoc());
    282                     inst.spellcheckerOn = false;
    283                     tinyMCE.switchClass(editor_id + '_spellchecker', 'mceMenuButton');
    284                 }
    285 
    286                 return true;
    287 
    288             case "mceSpellCheckReplace":
    289                 if (inst.spellCheckerElm)
    290                     tinyMCE.setOuterHTML(inst.spellCheckerElm, value);
    291 
    292                 self._checkDone(inst);
    293                 self._contextMenu.hide();
    294                 self._menu.hide();
    295 
    296                 return true;
    297 
    298             case "mceSpellCheckIgnore":
    299                 if (inst.spellCheckerElm)
    300                     self._removeWord(inst.spellCheckerElm);
    301 
    302                 self._checkDone(inst);
    303                 self._contextMenu.hide();
    304                 self._menu.hide();
    305                 return true;
    306 
    307             case "mceSpellCheckIgnoreAll":
    308                 if (inst.spellCheckerElm)
    309                     self._removeWords(inst.getDoc(), inst.spellCheckerElm.innerHTML);
    310 
    311                 self._checkDone(inst);
    312                 self._contextMenu.hide();
    313                 self._menu.hide();
    314                 return true;
    315 
    316             case "mceSpellCheckerSetLang":
    317                 tinyMCE.hideMenus();
    318                 inst.spellCheckerLang = value;
    319                 self._removeWords(inst.getDoc());
    320                 inst.spellcheckerOn = false;
    321                 tinyMCE.switchClass(editor_id + '_spellchecker', 'mceMenuButton');
    322                 return true;
    323         }
    324 
    325         // Pass to next handler in chain
    326         return false;
    327     },
    328 
    329     cleanup : function(type, content, inst) {
    330         switch (type) {
    331             case "get_from_editor_dom":
    332                 TinyMCE_SpellCheckerPlugin._removeWords(content);
    333                 inst.spellcheckerOn = false;
    334                 break;
    335         }
    336 
    337         return content;
    338     },
    339 
    340     // Private plugin specific methods
    341 
    342     _displayUI : function(inst) {
    343         var self = TinyMCE_SpellCheckerPlugin;
    344         var bb = self._getBlockBoxLayer(inst);
    345         var mb = self._getMsgBoxLayer(inst);
    346         var nl, i;
    347         var co = document.getElementById(inst.editorId + '_parent').firstChild;
    348 
    349         if (tinyMCE.isMSIE && !tinyMCE.isOpera) {
    350             nl = co.getElementsByTagName('select');
    351             for (i=0; i<nl.length; i++)
    352                 nl[i].disabled = false;
    353         }
    354 
    355         bb.hide();
    356         mb.hide();
    357     },
    358 
    359     _ajaxResponse : function(xml) {
    360         var el = xml ? xml.documentElement : null;
    361         var inst = tinyMCE.selectedInstance, self = TinyMCE_SpellCheckerPlugin;
    362         var cmd = el ? el.getAttribute("cmd") : null, err, id = el ? el.getAttribute("id") : null;
    363 
    364         if (id)
    365             inst = tinyMCE.getInstanceById(id.substring(0, id.indexOf('|')));
    366 
    367         self._displayUI(inst);
    368 
    369         // Ignore suggestions for other ajax responses
    370         if (cmd == "suggest" && id != inst.editorId + "|" + self._counter)
    371             return;
    372 
    373         if (!el) {
    374             inst.spellcheckerOn = false;
    375             tinyMCE.switchClass(inst.editorId + '_spellchecker', 'mceMenuButton');
    376             alert("Could not execute AJAX call, server didn't return valid a XML.");
    377             return;
    378         }
    379 
    380         err = el.getAttribute("error");
    381 
    382         if (err == "true") {
    383             inst.spellcheckerOn = false;
    384             tinyMCE.switchClass(inst.editorId + '_spellchecker', 'mceMenuButton');
    385             alert(el.getAttribute("msg"));
    386             return;
    387         }
    388 
    389         switch (cmd) {
    390             case "spell":
    391                 if (xml.documentElement.firstChild) {
    392                     self._markWords(inst.getDoc(), inst.getBody(), el.firstChild.nodeValue.split(' '));
    393                     inst.selection.moveToBookmark(inst.spellCheckerBookmark);
    394                 } else
    395                     alert(tinyMCE.getLang('lang_spellchecker_no_mpell', '', true));
    396 
    397                 self._checkDone(inst);
    398 
    399                 break;
    400 
    401             case "suggest":
    402                 self._buildMenu(el.firstChild ? el.firstChild.nodeValue.split(' ') : null, 10);
    403                 self._contextMenu.show();
    404                 break;
    405         }
    406     },
    407 
    408     _getWordSeparators : function() {
    409         var i, re = '', ch = tinyMCE.getParam('spellchecker_word_separator_chars', '\\s!"#$%&()*+,-./:;<=>?@[\]^_{|}§©«®±¶·¸»¼½¾¿×÷¤\u201d\u201c');
    410 
    411         for (i=0; i<ch.length; i++)
    412             re += '\\' + ch.charAt(i);
    413 
    414         return re;
    415     },
    416 
    417     _getWordList : function(n) {
    418         var i, x, s, nv = '', nl = tinyMCE.getNodeTree(n, new Array(), 3), wl = new Array();
    419         var re = TinyMCE_SpellCheckerPlugin._getWordSeparators();
    420 
    421         for (i=0; i<nl.length; i++)
    422             nv += nl[i].nodeValue + " ";
    423 
    424         nv = nv.replace(new RegExp('([0-9]|[' + re + '])', 'g'), ' ');
    425         nv = tinyMCE.trim(nv.replace(/(\s+)/g, ' '));
    426 
    427         nl = nv.split(/\s+/);
    428         for (i=0; i<nl.length; i++) {
    429             s = false;
    430             for (x=0; x<wl.length; x++) {
    431                 if (wl[x] == nl[i]) {
    432                     s = true;
    433                     break;
    434                 }
    435             }
    436 
    437             if (!s)
    438                 wl[wl.length] = nl[i];
    439         }
    440 
    441         return wl.join(' ');
    442     },
    443 
    444     _removeWords : function(doc, word) {
    445         var i, c, nl = doc.getElementsByTagName("span");
    446         var self = TinyMCE_SpellCheckerPlugin;
    447         var inst = tinyMCE.selectedInstance, b = inst ? inst.selection.getBookmark() : null;
    448 
    449         word = typeof(word) == 'undefined' ? null : word;
    450 
    451         for (i=nl.length-1; i>=0; i--) {
    452             c = tinyMCE.getAttrib(nl[i], 'class');
    453 
    454             if ((c == 'mceItemHiddenSpellWord' || c == 'mceItemHidden') && (word == null || nl[i].innerHTML == word))
    455                 self._removeWord(nl[i]);
    456         }
    457 
    458         if (b)
    459             inst.selection.moveToBookmark(b);
    460     },
    461 
    462     _checkDone : function(inst) {
    463         var i, w = 0, nl = inst.getDoc().getElementsByTagName("span")
    464         var self = TinyMCE_SpellCheckerPlugin;
    465 
    466         for (i=nl.length-1; i>=0; i--) {
    467             c = tinyMCE.getAttrib(nl[i], 'class');
    468 
    469             if (c == 'mceItemHiddenSpellWord')
    470                 w++;
    471         }
    472 
    473         if (w == 0) {
    474             self._removeWords(inst.getDoc());
    475             inst.spellcheckerOn = false;
    476             tinyMCE.switchClass(inst.editorId + '_spellchecker', 'mceMenuButton');
    477         }
    478     },
    479 
    480     _removeWord : function(e) {
    481         tinyMCE.setOuterHTML(e, e.innerHTML);
    482     },
    483 
    484     _markWords : function(doc, n, wl) {
    485         var i, nv, nn, nl = tinyMCE.getNodeTree(n, new Array(), 3);
    486         var r1, r2, r3, r4, r5, w = '';
    487         var re = TinyMCE_SpellCheckerPlugin._getWordSeparators();
    488 
    489         for (i=0; i<wl.length; i++)
    490             w += wl[i] + ((i == wl.length-1) ? '' : '|');
    491 
    492         r1 = new RegExp('([' + re + '])(' + w + ')([' + re + '])', 'g');
    493         r2 = new RegExp('^(' + w + ')', 'g');
    494         r3 = new RegExp('(' + w + ')([' + re + ']?)$', 'g');
    495         r4 = new RegExp('^(' + w + ')([' + re + ']?)$', 'g');
    496         r5 = new RegExp('(' + w + ')([' + re + '])', 'g');
    497 
    498         for (i=0; i<nl.length; i++) {
    499             nv = nl[i].nodeValue;
    500             if (r1.test(nv) || r2.test(nv) || r3.test(nv) || r4.test(nv)) {
    501                 nv = tinyMCE.xmlEncode(nv);
    502                 nv = nv.replace(r5, '<span class="mceItemHiddenSpellWord">$1</span>$2');
    503                 nv = nv.replace(r3, '<span class="mceItemHiddenSpellWord">$1</span>$2');
    504 
    505                 nn = doc.createElement('span');
    506                 nn.className = "mceItemHidden";
    507                 nn.innerHTML = nv;
    508 
    509                 // Remove old text node
    510                 nl[i].parentNode.replaceChild(nn, nl[i]);
    511             }
    512         }
    513     },
    514 
    515     _buildMenu : function(sg, max) {
    516         var i, self = TinyMCE_SpellCheckerPlugin, cm = self._contextMenu;
    517 
    518         cm.clear();
    519 
    520         if (sg != null) {
    521             cm.addTitle(tinyMCE.getLang('lang_spellchecker_sug', '', true));
    522 
    523             for (i=0; i<sg.length && i<max; i++)
    524                 cm.addItem(sg[i], 'tinyMCE.execCommand("mceSpellCheckReplace",false,"' + sg[i] + '");');
    525 
    526             cm.addSeparator();
    527             cm.addItem(tinyMCE.getLang('lang_spellchecker_ignore_word', '', true), 'tinyMCE.execCommand(\'mceSpellCheckIgnore\');');
    528             cm.addItem(tinyMCE.getLang('lang_spellchecker_ignore_words', '', true), 'tinyMCE.execCommand(\'mceSpellCheckIgnoreAll\');');
    529         } else
    530             cm.addTitle(tinyMCE.getLang('lang_spellchecker_no_sug', '', true));
    531 
    532         cm.update();
    533     },
    534 
    535     _getAjaxHTTP : function() {
    536         try {
    537             return new ActiveXObject('Msxml2.XMLHTTP')
    538         } catch (e) {
    539             try {
    540                 return new ActiveXObject('Microsoft.XMLHTTP')
    541             } catch (e) {
    542                 return new XMLHttpRequest();
    543             }
    544         }
    545     },
    546 
    547     /**
    548      * Perform AJAX call.
    549      *
    550      * @param {string} u URL of AJAX service.
    551      * @param {function} f Function to call when response arrives.
    552      * @param {string} m Request method post or get.
    553      * @param {Array} a Array with arguments to send.
    554      */
    555     _sendAjax : function(u, f, m, a) {
    556         var x = TinyMCE_SpellCheckerPlugin._getAjaxHTTP();
    557 
    558         x.open(m, u, true);
    559 
    560         x.onreadystatechange = function() {
    561             if (x.readyState == 4)
    562                 f(x.responseXML);
    563         };
    564 
    565         if (m == 'post')
    566             x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    567 
    568         x.send(a);
    569     }
    570 };
    571 
    572 // Register plugin
    573 tinyMCE.addPlugin('spellchecker', TinyMCE_SpellCheckerPlugin);
     1tinyMCE.importPluginLanguagePack('spellchecker','en,fr,sv,nn,nb');var TinyMCE_SpellCheckerPlugin={_contextMenu:new TinyMCE_Menu(),_menu:new TinyMCE_Menu(),_counter:0,_ajaxPage:'/tinyspell.php',getInfo:function(){return{longname:'Spellchecker PHP',author:'Moxiecode Systems AB',authorurl:'http://tinymce.moxiecode.com',infourl:'http://tinymce.moxiecode.com/tinymce/docs/plugin_spellchecker.html',version:"1.0.3"};},handleEvent:function(e){var elm=tinyMCE.isMSIE?e.srcElement:e.target;var inst=tinyMCE.selectedInstance,args='';var self=TinyMCE_SpellCheckerPlugin;var cm=self._contextMenu;var p,p2,x,y,sx,sy,h,elm;if((e.type=="click"||e.type=="contextmenu")&&elm){do{if(tinyMCE.getAttrib(elm,'class')=="mceItemHiddenSpellWord"){inst.spellCheckerElm=elm;args+='id='+inst.editorId+"|"+(++self._counter);args+='&cmd=suggest&check='+encodeURIComponent(elm.innerHTML);args+='&lang='+escape(inst.spellCheckerLang);elm=inst.spellCheckerElm;p=tinyMCE.getAbsPosition(inst.iframeElement);p2=tinyMCE.getAbsPosition(elm);h=parseInt(elm.offsetHeight);sx=inst.getBody().scrollLeft;sy=inst.getBody().scrollTop;x=p.absLeft+p2.absLeft-sx;y=p.absTop+p2.absTop-sy+h;cm.clear();cm.addTitle(tinyMCE.getLang('lang_spellchecker_wait','',true));cm.show();cm.moveTo(x,y);inst.selection.selectNode(elm,false,false);self._sendAjax(self.baseURL+self._ajaxPage,self._ajaxResponse,'post',args);tinyMCE.cancelEvent(e);return false;}}while((elm=elm.parentNode));}return true;},initInstance:function(inst){var self=TinyMCE_SpellCheckerPlugin,m=self._menu,cm=self._contextMenu,e;tinyMCE.importCSS(inst.getDoc(),tinyMCE.baseURL+"/plugins/spellchecker/css/content.css");if(!tinyMCE.hasMenu('spellcheckercontextmenu')){tinyMCE.importCSS(document,tinyMCE.baseURL+"/plugins/spellchecker/css/spellchecker.css");cm.init({drop_menu:false});tinyMCE.addMenu('spellcheckercontextmenu',cm);}if(!tinyMCE.hasMenu('spellcheckermenu')){m.init({});tinyMCE.addMenu('spellcheckermenu',m);}inst.spellCheckerLang='en';self._buildSettingsMenu(inst,null);e=self._getBlockBoxLayer(inst).create('div','mceBlockBox',document.getElementById(inst.editorId+'_parent'));self._getMsgBoxLayer(inst).create('div','mceMsgBox',document.getElementById(inst.editorId+'_parent'));},_getMsgBoxLayer:function(inst){if(!inst.spellCheckerMsgBoxL)inst.spellCheckerMsgBoxL=new TinyMCE_Layer(inst.editorId+'_spellcheckerMsgBox',false);return inst.spellCheckerMsgBoxL;},_getBlockBoxLayer:function(inst){if(!inst.spellCheckerBoxL)inst.spellCheckerBoxL=new TinyMCE_Layer(inst.editorId+'_spellcheckerBlockBox',false);return inst.spellCheckerBoxL;},_buildSettingsMenu:function(inst,lang){var i,ar=tinyMCE.getParam('spellchecker_languages','+English=en').split(','),p;var self=TinyMCE_SpellCheckerPlugin,m=self._menu,c;m.clear();m.addTitle(tinyMCE.getLang('lang_spellchecker_langs','',true));for(i=0;i<ar.length;i++){if(ar[i]!=''){p=ar[i].split('=');c='mceMenuCheckItem';if(p[0].charAt(0)=='+'){p[0]=p[0].substring(1);if(lang==null){c='mceMenuSelectedItem';inst.spellCheckerLang=p[1];}}if(lang==p[1])c='mceMenuSelectedItem';m.add({text:p[0],js:"tinyMCE.execInstanceCommand('"+inst.editorId+"','mceSpellCheckerSetLang',false,'"+p[1]+"');",class_name:c});}}},setupContent:function(editor_id,body,doc){TinyMCE_SpellCheckerPlugin._removeWords(doc,null,true);},getControlHTML:function(cn){switch(cn){case"spellchecker":return TinyMCE_SpellCheckerPlugin._getMenuButtonHTML(cn,'lang_spellchecker_desc','{$pluginurl}/images/spellchecker.gif','lang_spellchecker_desc','mceSpellCheckerMenu','mceSpellCheck');}return"";},_getMenuButtonHTML:function(id,lang,img,mlang,mid,cmd,ui,val){var h='',m,x;cmd='tinyMCE.hideMenus();tinyMCE.execInstanceCommand(\'{$editor_id}\',\''+cmd+'\'';if(typeof(ui)!="undefined"&&ui!=null)cmd+=','+ui;if(typeof(val)!="undefined"&&val!=null)cmd+=",'"+val+"'";cmd+=');';if(tinyMCE.getParam('button_tile_map')&&(!tinyMCE.isMSIE||tinyMCE.isOpera)&&(m=tinyMCE.buttonMap[id])!=null&&(tinyMCE.getParam("language")=="en"||img.indexOf('$lang')==-1)){x=0-(m*20)==0?'0':0-(m*20);h+='<a id="{$editor_id}_'+id+'" href="javascript:'+cmd+'" onclick="'+cmd+'return false;" onmousedown="return false;" class="mceTiledButton mceButtonNormal" target="_self">';h+='<img src="{$themeurl}/images/spacer.gif" style="background-position: '+x+'px 0" title="{$'+lang+'}" />';h+='<img src="{$themeurl}/images/button_menu.gif" title="{$'+lang+'}" class="mceMenuButton" onclick="'+mcmd+'return false;" />';h+='</a>';}else{if(tinyMCE.isMSIE&&!tinyMCE.isOpera)h+='<span id="{$editor_id}_'+id+'" class="mceMenuButton" onmouseover="tinyMCE.plugins.spellchecker._menuButtonEvent(\'over\',this);" onmouseout="tinyMCE.plugins.spellchecker._menuButtonEvent(\'out\',this);">';else h+='<span id="{$editor_id}_'+id+'" class="mceMenuButton">';h+='<a href="javascript:'+cmd+'" onclick="'+cmd+'return false;" onmousedown="return false;" class="mceMenuButtonNormal" target="_self">';h+='<img src="'+img+'" title="{$'+lang+'}" /></a>';h+='<a href="#" onclick="tinyMCE.plugins.spellchecker._toggleMenu(\'{$editor_id}\',\''+mid+'\');return false;" onmousedown="return false;"><img src="{$themeurl}/images/button_menu.gif" title="{$'+lang+'}" class="mceMenuButton" />';h+='</a></span>';}return h;},_menuButtonEvent:function(e,o){var t=this;window.setTimeout(function(){t._menuButtonEvent2(e,o);},1);},_menuButtonEvent2:function(e,o){if(o.className=='mceMenuButtonFocus')return;if(e=='over')o.className=o.className+' mceMenuHover';else o.className=o.className.replace(/\s.*$/,'');},_toggleMenu:function(editor_id,id){var self=TinyMCE_SpellCheckerPlugin;var e=document.getElementById(editor_id+'_spellchecker');var inst=tinyMCE.getInstanceById(editor_id);if(self._menu.isVisible()){tinyMCE.hideMenus();return;}tinyMCE.lastMenuBtnClass=e.className.replace(/\s.*$/,'');tinyMCE.switchClass(editor_id+'_spellchecker','mceMenuButtonFocus');self._menu.moveRelativeTo(e,'bl');self._menu.moveBy(tinyMCE.isMSIE&&!tinyMCE.isOpera?0:1,-1);if(tinyMCE.isOpera)self._menu.moveBy(0,-2);self._onMenuEvent(inst,self._menu,'show');self._menu.show();tinyMCE.lastSelectedMenuBtn=editor_id+'_spellchecker';},_onMenuEvent:function(inst,m,n){TinyMCE_SpellCheckerPlugin._buildSettingsMenu(inst,inst.spellCheckerLang);},execCommand:function(editor_id,element,command,user_interface,value){var inst=tinyMCE.getInstanceById(editor_id),self=TinyMCE_SpellCheckerPlugin,args='',co,bb,mb,nl,i,e,mbs;switch(command){case"mceSpellCheck":if(!inst.spellcheckerOn){inst.spellCheckerBookmark=inst.selection.getBookmark();if(tinyMCE.isRealIE)tinyMCE.setInnerHTML(inst.getBody(),inst.getBody().innerHTML);args+='id='+inst.editorId+"|"+(++self._counter);args+='&cmd=spell&check='+encodeURIComponent(self._getWordList(inst.getBody())).replace(/\'/g,'%27');args+='&lang='+escape(inst.spellCheckerLang);co=document.getElementById(inst.editorId+'_parent').firstChild;bb=self._getBlockBoxLayer(inst);bb.moveRelativeTo(co,'tl');bb.resizeTo(co.offsetWidth,co.offsetHeight);bb.show();mb=self._getMsgBoxLayer(inst);e=mb.getElement();if(e.childNodes[0])e.removeChild(e.childNodes[0]);mbs=document.createElement("span");mbs.innerHTML='<span>'+tinyMCE.getLang('lang_spellchecker_swait','',true)+'</span>';e.appendChild(mbs);mb.show();mb.moveRelativeTo(co,'cc');if(tinyMCE.isMSIE&&!tinyMCE.isOpera){nl=co.getElementsByTagName('select');for(i=0;i<nl.length;i++)nl[i].disabled=true;}inst.spellcheckerOn=true;tinyMCE.switchClass(editor_id+'_spellchecker','mceMenuButtonSelected');self._sendAjax(self.baseURL+self._ajaxPage,self._ajaxResponse,'post',args);}else{self._removeWords(inst.getDoc());inst.spellcheckerOn=false;tinyMCE.switchClass(editor_id+'_spellchecker','mceMenuButton');}return true;case"mceSpellCheckReplace":if(inst.spellCheckerElm)tinyMCE.setOuterHTML(inst.spellCheckerElm,value);self._checkDone(inst);self._contextMenu.hide();self._menu.hide();return true;case"mceSpellCheckIgnore":if(inst.spellCheckerElm)self._removeWord(inst.spellCheckerElm);self._checkDone(inst);self._contextMenu.hide();self._menu.hide();return true;case"mceSpellCheckIgnoreAll":if(inst.spellCheckerElm)self._removeWords(inst.getDoc(),inst.spellCheckerElm.innerHTML);self._checkDone(inst);self._contextMenu.hide();self._menu.hide();return true;case"mceSpellCheckerSetLang":tinyMCE.hideMenus();inst.spellCheckerLang=value;self._removeWords(inst.getDoc());inst.spellcheckerOn=false;tinyMCE.switchClass(editor_id+'_spellchecker','mceMenuButton');return true;}return false;},cleanup:function(type,content,inst){switch(type){case"get_from_editor_dom":TinyMCE_SpellCheckerPlugin._removeWords(content,null,true);inst.spellcheckerOn=false;break;}return content;},_displayUI:function(inst){var self=TinyMCE_SpellCheckerPlugin;var bb=self._getBlockBoxLayer(inst);var mb=self._getMsgBoxLayer(inst);var nl,i;var co=document.getElementById(inst.editorId+'_parent').firstChild;if(tinyMCE.isMSIE&&!tinyMCE.isOpera){nl=co.getElementsByTagName('select');for(i=0;i<nl.length;i++)nl[i].disabled=false;}bb.hide();mb.hide();},_ajaxResponse:function(xml){var el=xml?xml.documentElement:null;var inst=tinyMCE.selectedInstance,self=TinyMCE_SpellCheckerPlugin;var cmd=el?el.getAttribute("cmd"):null,err,id=el?el.getAttribute("id"):null;if(id)inst=tinyMCE.getInstanceById(id.substring(0,id.indexOf('|')));self._displayUI(inst);if(cmd=="suggest"&&id!=inst.editorId+"|"+self._counter)return;if(!el){inst.spellcheckerOn=false;tinyMCE.switchClass(inst.editorId+'_spellchecker','mceMenuButton');alert("Could not execute AJAX call, server didn't return valid a XML.");return;}err=el.getAttribute("error");if(err=="true"){inst.spellcheckerOn=false;tinyMCE.switchClass(inst.editorId+'_spellchecker','mceMenuButton');alert(el.getAttribute("msg"));return;}switch(cmd){case"spell":if(xml.documentElement.firstChild){self._markWords(inst.getDoc(),inst.getBody(),decodeURIComponent(el.firstChild.nodeValue).split('+'));inst.selection.moveToBookmark(inst.spellCheckerBookmark);if(tinyMCE.getParam('spellchecker_report_misspellings',false))alert(tinyMCE.getLang('lang_spellchecker_mpell_found','',true,{words:self._countWords(inst)}));}else alert(tinyMCE.getLang('lang_spellchecker_no_mpell','',true));self._checkDone(inst);inst.useCSS=false;break;case"suggest":self._buildMenu(el.firstChild?decodeURIComponent(el.firstChild.nodeValue).split('+'):null,10);self._contextMenu.show();break;}},_getWordSeparators:function(){var i,re='',ch=tinyMCE.getParam('spellchecker_word_separator_chars','\\s!"#$%&()*+,-./:;<=>?@[\]^_{|}\u201d\u201c');for(i=0;i<ch.length;i++)re+='\\'+ch.charAt(i);return re;},_getWordList:function(n){var i,x,s,nv='',nl=tinyMCE.getNodeTree(n,new Array(),3),wl=new Array();var re=TinyMCE_SpellCheckerPlugin._getWordSeparators();for(i=0;i<nl.length;i++){if(!new RegExp('/SCRIPT|STYLE/').test(nl[i].parentNode.nodeName))nv+=nl[i].nodeValue+" ";}nv=nv.replace(new RegExp('([0-9]|['+re+'])','g'),' ');nv=tinyMCE.trim(nv.replace(/(\s+)/g,' '));nl=nv.split(/\s+/);for(i=0;i<nl.length;i++){s=false;for(x=0;x<wl.length;x++){if(wl[x]==nl[i]){s=true;break;}}if(!s&&nl[i].length>0)wl[wl.length]=nl[i];}return wl.join(' ');},_removeWords:function(doc,word,cleanup){var i,c,nl=doc.getElementsByTagName("span");var self=TinyMCE_SpellCheckerPlugin;var inst=tinyMCE.selectedInstance,b=inst?inst.selection.getBookmark():null;word=typeof(word)=='undefined'?null:word;for(i=nl.length-1;i>=0;i--){c=tinyMCE.getAttrib(nl[i],'class');if((c=='mceItemHiddenSpellWord'||c=='mceItemHidden')&&(word==null||nl[i].innerHTML==word))self._removeWord(nl[i]);}if(b&&!cleanup)inst.selection.moveToBookmark(b);},_checkDone:function(inst){var self=TinyMCE_SpellCheckerPlugin;var w=self._countWords(inst);if(w==0){self._removeWords(inst.getDoc());inst.spellcheckerOn=false;tinyMCE.switchClass(inst.editorId+'_spellchecker','mceMenuButton');}},_countWords:function(inst){var i,w=0,nl=inst.getDoc().getElementsByTagName("span"),c;var self=TinyMCE_SpellCheckerPlugin;for(i=nl.length-1;i>=0;i--){c=tinyMCE.getAttrib(nl[i],'class');if(c=='mceItemHiddenSpellWord')w++;}return w;},_removeWord:function(e){if(e!=null)tinyMCE.setOuterHTML(e,e.innerHTML);},_markWords:function(doc,n,wl){var i,nv,nn,nl=tinyMCE.getNodeTree(n,new Array(),3);var r1,r2,r3,r4,r5,w='';var re=TinyMCE_SpellCheckerPlugin._getWordSeparators();for(i=0;i<wl.length;i++){if(wl[i].length>0)w+=wl[i]+((i==wl.length-1)?'':'|');}for(i=0;i<nl.length;i++){nv=nl[i].nodeValue;r1=new RegExp('(['+re+'])('+w+')(['+re+'])','g');r2=new RegExp('^('+w+')','g');r3=new RegExp('('+w+')(['+re+']?)$','g');r4=new RegExp('^('+w+')(['+re+']?)$','g');r5=new RegExp('('+w+')(['+re+'])','g');if(r1.test(nv)||r2.test(nv)||r3.test(nv)||r4.test(nv)){nv=tinyMCE.xmlEncode(nv);nv=nv.replace(r5,'<span class="mceItemHiddenSpellWord">$1</span>$2');nv=nv.replace(r3,'<span class="mceItemHiddenSpellWord">$1</span>$2');nn=doc.createElement('span');nn.className="mceItemHidden";nn.innerHTML=nv;nl[i].parentNode.replaceChild(nn,nl[i]);}}},_buildMenu:function(sg,max){var i,self=TinyMCE_SpellCheckerPlugin,cm=self._contextMenu;cm.clear();if(sg!=null){cm.addTitle(tinyMCE.getLang('lang_spellchecker_sug','',true));for(i=0;i<sg.length&&i<max;i++)cm.addItem(sg[i],'tinyMCE.execCommand("mceSpellCheckReplace",false,"'+sg[i]+'");');cm.addSeparator();}else cm.addTitle(tinyMCE.getLang('lang_spellchecker_no_sug','',true));cm.addItem(tinyMCE.getLang('lang_spellchecker_ignore_word','',true),'tinyMCE.execCommand(\'mceSpellCheckIgnore\');');cm.addItem(tinyMCE.getLang('lang_spellchecker_ignore_words','',true),'tinyMCE.execCommand(\'mceSpellCheckIgnoreAll\');');cm.update();},_getAjaxHTTP:function(){try{return new ActiveXObject('Msxml2.XMLHTTP')}catch(e){try{return new ActiveXObject('Microsoft.XMLHTTP')}catch(e){return new XMLHttpRequest();}}},_sendAjax:function(u,f,m,a){var x=TinyMCE_SpellCheckerPlugin._getAjaxHTTP();x.open(m,u,true);x.onreadystatechange=function(){if(x.readyState==4)f(x.responseXML);};if(m=='post')x.setRequestHeader('Content-type','application/x-www-form-urlencoded');x.send(a);}};tinyMCE.addPlugin('spellchecker',TinyMCE_SpellCheckerPlugin);
  • tags/2.2/wp-includes/js/tinymce/plugins/spellchecker/langs/en.js

    r5468 r5480  
    1111    sug : 'Suggestions',
    1212    no_sug : 'No suggestions',
    13     no_mpell : 'No misspellings found.'
     13    no_mpell : 'No misspellings found.',
     14    mpell_found : 'Found {$words} misspellings.'
    1415});
  • tags/2.2/wp-includes/js/tinymce/plugins/spellchecker/tinyspell.php

    r5468 r5480  
    88 * @copyright Copyright © 2004-2006, Moxiecode Systems AB, All rights reserved.
    99 */
     10
     11    // Ignore the Notice errors for now.
     12    error_reporting(E_ALL ^ E_NOTICE);
    1013
    1114    require_once("config.php");
     
    3134    // Get input parameters.
    3235
    33     $check = $_POST['check'];
    34     $cmd = sanitize($_POST['cmd']);
    35     $lang = sanitize($_POST['lang'], "strict");
    36     $mode = sanitize($_POST['mode'], "strict");
    37     $spelling = sanitize($_POST['spelling'], "strict");
    38     $jargon = sanitize($_POST['jargon'], "strict");
    39     $encoding = sanitize($_POST['encoding'], "strict");
    40     $sg = sanitize($_POST['sg'], "bool");
     36    $check = urldecode($_REQUEST['check']);
     37    $cmd = sanitize($_REQUEST['cmd']);
     38    $lang = sanitize($_REQUEST['lang'], "strict");
     39    $mode = sanitize($_REQUEST['mode'], "strict");
     40    $spelling = sanitize($_REQUEST['spelling'], "strict");
     41    $jargon = sanitize($_REQUEST['jargon'], "strict");
     42    $encoding = sanitize($_REQUEST['encoding'], "strict");
     43    $sg = sanitize($_REQUEST['sg'], "bool");
    4144    $words = array();
    4245
     
    9194                $result = $tinyspell->checkWords($words);
    9295            break;
     96   
    9397            case "suggest":
    9498                $result = $tinyspell->getSuggestion($check);
    9599            break;
     100
    96101            default:
    97102                // Just use this for now.
     
    110115        case "xml":
    111116            header('Content-type: text/xml; charset=utf-8');
    112             echo '<?xml version="1.0" encoding="utf-8" ?>';
    113             echo "\n";
     117            $body  = '<?xml version="1.0" encoding="utf-8" ?>';
     118            $body .= "\n";
     119           
    114120            if (count($result) == 0)
    115                 echo '<res id="' . $id . '" cmd="'. $cmd .'" />';
     121                $body .= '<res id="' . $id . '" cmd="'. $cmd .'" />';
    116122            else
    117                 echo '<res id="' . $id . '" cmd="'. $cmd .'">'. utf8_encode(implode(" ", $result)) .'</res>';
     123                $body .= '<res id="' . $id . '" cmd="'. $cmd .'">'. urlencode(implode(" ", $result)) .'</res>';
    118124
     125            echo $body;
    119126        break;
    120127        case "xmlerror";
    121128            header('Content-type: text/xml; charset=utf-8');
    122             echo '<?xml version="1.0" encoding="utf-8" ?>';
    123             echo "\n";
    124             echo '<res id="' . $id . '" cmd="'. $cmd .'" error="true" msg="'. implode(" ", $tinyspell->errorMsg) .'" />';
     129            $body  = '<?xml version="1.0" encoding="utf-8" ?>';
     130            $body .= "\n";
     131            $body .= '<res id="' . $id . '" cmd="'. $cmd .'" error="true" msg="'. implode(" ", $tinyspell->errorMsg) .'" />';
     132            echo $body;
    125133        break;
    126134        case "html":
     
    131139        break;
    132140    }
    133 ?>
     141
     142?>
  • tags/2.2/wp-includes/js/tinymce/plugins/wordpress/editor_plugin.js

    r5468 r5480  
    516516
    517517        // Tweak the widths
    518         ta.parentNode.style.paddingRight = '2px';
     518        ta.parentNode.style.paddingRight = '12px';
    519519
    520520        if ( tinyMCE.isMSIE && !tinyMCE.isOpera ) {
  • tags/2.2/wp-includes/js/tinymce/plugins/wordpress/langs/en.js

    r5468 r5480  
    3030numlist_desc : 'Ordered list (' + metaKey + '+o)',
    3131outdent_desc : 'Outdent (' + metaKey + '+w)',
    32 indent_desc : 'Indent List/Blockquote (' + metaKey + '+q)'
     32indent_desc : 'Indent list/blockquote (' + metaKey + '+q)'
    3333});
  • tags/2.2/wp-includes/js/tinymce/plugins/wordpress/wordpress.css

    r5468 r5480  
    4949    overflow: hidden;
    5050    padding-left: 12px;
    51     background-image: url('../images/anchor_symbol.gif');
    5251    background-position: bottom;
    5352    background-repeat: no-repeat;
  • tags/2.2/wp-includes/js/tinymce/themes/advanced/about.htm

    r5468 r5480  
    2222                <p>TinyMCE is a platform independent web based Javascript HTML WYSIWYG editor control released as Open Source under <a href="../../license.txt" target="_blank">LGPL</a>
    2323                by Moxiecode Systems AB. It has the ability to convert HTML TEXTAREA fields or other HTML elements to editor instances.</p>
    24                 <p>Copyright &copy; 2003-2006, <a href="http://www.moxiecode.com" target="_blank">Moxiecode Systems AB</a>, All rights reserved.</p>
     24                <p>Copyright &copy; 2003-2007, <a href="http://www.moxiecode.com" target="_blank">Moxiecode Systems AB</a>, All rights reserved.</p>
    2525                <p>For more information about this software visit the <a href="http://tinymce.moxiecode.com" target="_blank">TinyMCE website</a>.</p>
    2626
  • tags/2.2/wp-includes/js/tinymce/themes/advanced/css/editor_ui.css

    r5468 r5480  
    11/* This file contains the CSS data for the editor UI of TinyMCE instances */
    22
    3 .mceToolbarTop a, .mceToolbarTop a:visited, .mceToolbarTop a:hover, .mceToolbarBottom a, .mceToolbarBottom a:visited, .mceToolbarBottom a:hover {border: 0;  margin: 0;  padding: 0; background: transparent;}
     3.mceToolbarTop a, .mceToolbarTop a:visited, .mceToolbarTop a:hover, .mceToolbarBottom a, .mceToolbarBottom a:visited, .mceToolbarBottom a:hover {border: 0; margin: 0; padding: 0; background: transparent;}
    44.mceSeparatorLine {border: 0; padding: 0; margin-left: 4px; margin-right: 2px;}
    55.mceSelectList {font-family: 'MS Sans Serif', sans-serif, Verdana, Arial; font-size: 7pt !important; font-weight: normal; margin-top: 3px; padding: 0; display: inline; vertical-align: top; background-color: #F0F0EE;}
    66.mceLabel, .mceLabelDisabled {font-family: 'MS Sans Serif', sans-serif, Verdana, Arial; font-size: 9pt;}
    77.mceLabel {color: #000000;}
    8 .mceLabelDisabled {cursor: text;  color: #999999;}
    9 .mceEditor {background: #F0F0EE;  border: 1px solid #cccccc;  padding: 0; margin: 0;}
    10 .mceEditorArea { font-family: 'MS Sans Serif', sans-serif, Verdana, Arial;  background: #FFFFFF;  padding: 0;  margin: 0; }
    11 .mceToolbarTop, .mceToolbarBottom {background: #F0F0EE;  line-height: 1px; font-size: 1px;}
     8.mceLabelDisabled {cursor: text; color: #999999;}
     9.mceEditor {background: #F0F0EE; border: 1px solid #cccccc; padding: 0; margin: 0;}
     10.mceEditorArea { font-family: 'MS Sans Serif', sans-serif, Verdana, Arial; background: #FFFFFF; padding: 0; margin: 0; }
     11.mceToolbarTop, .mceToolbarBottom {background: #F0F0EE; line-height: 1px; font-size: 1px;}
    1212.mceToolbarTop {border-bottom: 1px solid #cccccc; padding-bottom: 1px;}
    1313.mceToolbarBottom {border-top: 1px solid #cccccc;}
    14 .mceToolbarContainer {position: relative;  left: 0;  top: 0;  display: block;}
     14.mceToolbarContainer {display: block; position: relative; left: 0; top: 0; width: 100%;}
    1515.mceStatusbarTop, .mceStatusbarBottom, .mceStatusbar {height: 20px;}
    16 .mceStatusbarTop .mceStatusbarPathText, .mceStatusbarBottom .mceStatusbarPathText, .mceStatusbar .mceStatusbarPathText {font-family: 'MS Sans Serif', sans-serif, Verdana, Arial;  font-size: 9pt;  padding: 2px;  line-height: 16px; overflow: visible;}
     16.mceStatusbarTop .mceStatusbarPathText, .mceStatusbarBottom .mceStatusbarPathText, .mceStatusbar .mceStatusbarPathText {font-family: 'MS Sans Serif', sans-serif, Verdana, Arial; font-size: 9pt; padding: 2px; line-height: 16px; overflow: visible;}
    1717.mceStatusbarTop {border-bottom: 1px solid #cccccc;}
    1818.mceStatusbarBottom {border-top: 1px solid #cccccc;}
    1919.mceStatusbar {border-bottom: 1px solid #cccccc;}
    20 .mcePathItem, .mcePathItem:link, .mcePathItem:visited, .mcePathItem:hover {text-decoration: none;  font-family: 'MS Sans Serif', sans-serif, Verdana, Arial;  font-size: 9pt; color: #000000;}
     20.mcePathItem, .mcePathItem:link, .mcePathItem:visited, .mcePathItem:hover {text-decoration: none; font-family: 'MS Sans Serif', sans-serif, Verdana, Arial; font-size: 9pt; color: #000000;}
    2121.mcePathItem:hover {text-decoration: underline;}
    2222.mceStatusbarPathText {float: left;}
    23 .mceStatusbarResize {float: right;  background-image: url('../images/statusbar_resize.gif');  background-repeat: no-repeat;  width: 11px;  height: 20px; cursor: se-resize;}
    24 .mceResizeBox {width: 10px;  height: 10px;  display: none;  border: 1px dotted gray;  margin: 0; padding: 0;}
     23.mceStatusbarResize {float: right; background-image: url('../images/statusbar_resize.gif'); background-repeat: no-repeat; width: 11px; height: 20px; cursor: se-resize;}
     24.mceResizeBox {width: 10px; height: 10px; display: none; border: 1px dotted gray; margin: 0; padding: 0;}
    2525.mceEditorIframe {border: 0;}
    2626
    2727/* Button CSS rules */
    2828
    29 a.mceButtonDisabled img, a.mceButtonNormal img, a.mceButtonSelected img {width: 20px;  height: 20px;  cursor: default;  margin-top: 1px; margin-left: 1px;}
     29a.mceButtonDisabled img, a.mceButtonNormal img, a.mceButtonSelected img {width: 20px; height: 20px; cursor: default; margin-top: 1px; margin-left: 1px;}
    3030a.mceButtonDisabled img {border: 0 !important;}
    3131a.mceButtonNormal img, a.mceButtonSelected img {border: 1px solid #F0F0EE !important;}
    32 a.mceButtonSelected img {border: 1px solid #6779AA !important;  background-color: #D4D5D8;}
    33 a.mceButtonNormal img:hover, a.mceButtonSelected img:hover {border: 1px solid #0A246A !important;  cursor: default; background-color: #B6BDD2;}
    34 a.mceButtonDisabled img {-moz-opacity:0.3;  opacity: 0.3;  border: 1px solid #F0F0EE !important; cursor: default;}
    35 a.mceTiledButton img {background-image: url('../images/buttons.gif');  background-repeat: no-repeat;}
     32a.mceButtonSelected img {border: 1px solid #6779AA !important; background-color: #D4D5D8;}
     33a.mceButtonNormal img:hover, a.mceButtonSelected img:hover {border: 1px solid #0A246A !important; cursor: default; background-color: #B6BDD2;}
     34a.mceButtonDisabled img {-moz-opacity:0.3; opacity: 0.3; border: 1px solid #F0F0EE !important; cursor: default;}
     35a.mceTiledButton img {background-image: url('../images/buttons.gif'); background-repeat: no-repeat;}
    3636
    3737/* Menu button CSS rules */
    3838
    39 span.mceMenuButton img, span.mceMenuButtonSelected img {border: 1px solid #F0F0EE;  margin-left: 1px;}
    40 span.mceMenuButtonSelected img {border: 1px solid #6779AA;  background-color: #B6BDD2;}
    41 span.mceMenuButtonSelected img.mceMenuButton {border: 1px solid #F0F0EE;  background-color: transparent;}
    42 span.mceMenuButton img.mceMenuButton, span.mceMenuButtonSelected img.mceMenuButton {border-left: 0;  margin-left: 0;}
    43 span.mceMenuButton:hover img, span.mceMenuButtonSelected:hover img {border: 1px solid #0A246A;  background-color: #B6BDD2;}
     39span.mceMenuButton img, span.mceMenuButtonSelected img {border: 1px solid #F0F0EE; margin-left: 1px;}
     40span.mceMenuButtonSelected img {border: 1px solid #6779AA; background-color: #B6BDD2;}
     41span.mceMenuButtonSelected img.mceMenuButton {border: 1px solid #F0F0EE; background-color: transparent;}
     42span.mceMenuButton img.mceMenuButton, span.mceMenuButtonSelected img.mceMenuButton {border-left: 0; margin-left: 0;}
     43span.mceMenuButton:hover img, span.mceMenuButtonSelected:hover img {border: 1px solid #0A246A; background-color: #B6BDD2;}
    4444span.mceMenuButton:hover img.mceMenuButton, span.mceMenuButtonSelected:hover img.mceMenuButton {border-left: 0;}
    45 span.mceMenuButtonFocus img {border: 1px solid gray;  border-right: 0;  margin-left: 1px; background-color: #F5F4F2;}
    46 span.mceMenuButtonFocus img.mceMenuButton {border: 1px solid gray;  border-left: 1px solid #F5F4F2; margin-left: 0;}
    47 span.mceMenuHover img {border: 1px solid #0A246A;  background-color: #B6BDD2;}
    48 span.mceMenuButtonSelected.mceMenuHover img.mceMenuButton {border: 1px solid #0A246A;  background-color: #B6BDD2; border-left: 0;}
     45span.mceMenuButtonFocus img {border: 1px solid gray; border-right: 0; margin-left: 1px; background-color: #F5F4F2;}
     46span.mceMenuButtonFocus img.mceMenuButton {border: 1px solid gray; border-left: 1px solid #F5F4F2; margin-left: 0;}
     47span.mceMenuHover img {border: 1px solid #0A246A; background-color: #B6BDD2;}
     48span.mceMenuButtonSelected.mceMenuHover img.mceMenuButton {border: 1px solid #0A246A; background-color: #B6BDD2; border-left: 0;}
    4949
    5050/* Menu */
    5151
    52 .mceMenu {position: absolute;  left: 0;  top: 0;  display: none;  z-index: 100;  background-color: white;  border: 1px solid gray; font-weight: normal;}
    53 .mceMenu a, .mceMenuTitle, .mceMenuDisabled {display: block;  width: 100%;  text-decoration: none;  background-color: white;  font-family: Tahoma, Verdana, Arial, Helvetica;  font-size: 11px;  line-height: 20px; color: black;}
    54 .mceMenu a:hover {background-color: #B6BDD2;  color: black; text-decoration: none !important;}
    55 .mceMenu span {padding-left: 10px;  padding-right: 10px;  display: block; line-height: 20px;}
    56 .mceMenuSeparator {border-bottom: 1px solid gray;  background-color: gray; height: 1px;}
     52.mceMenu {position: absolute; left: 0; top: 0; display: none; z-index: 1000; background-color: white; border: 1px solid gray; font-weight: normal;}
     53.mceMenu a, .mceMenuTitle, .mceMenuDisabled {display: block; width: 100%; text-decoration: none; background-color: white; font-family: Tahoma, Verdana, Arial, Helvetica; font-size: 11px; line-height: 20px; color: black;}
     54.mceMenu a:hover {background-color: #B6BDD2; color: black; text-decoration: none !important;}
     55.mceMenu span {padding-left: 10px; padding-right: 10px; display: block; line-height: 20px;}
     56.mceMenuSeparator {border-bottom: 1px solid gray; background-color: gray; height: 1px;}
    5757.mceMenuTitle span {padding-left: 5px;}
    58 .mceMenuTitle {background-color: #DDDDDD;  font-weight: bold;}
     58.mceMenuTitle {background-color: #DDDDDD; font-weight: bold;}
    5959.mceMenuDisabled {color: gray;}
    60 span.mceMenuSelectedItem {background-image: url('../images/menu_check.gif');  background-repeat: no-repeat;  background-position: 5px 8px; padding-left: 20px;}
     60span.mceMenuSelectedItem {background-image: url('../images/menu_check.gif'); background-repeat: no-repeat; background-position: 5px 8px; padding-left: 20px;}
    6161span.mceMenuCheckItem {padding-left: 20px;}
    62 span.mceMenuLine {display: block;  position: absolute;  left: 0;  top: -1px;  background-color: #F5F4F2;  width: 30px;  height: 1px;  overflow: hidden;  padding-left: 0; padding-right: 0;}
    63 .mceColors table, .mceColors td {margin: 0;  padding: 2px;}
    64 a.mceMoreColors {width: 130px;  margin: 0;  padding: 0;  margin-left: 3px;  margin-bottom: 3px;  text-align: center;  border: 1px solid white;}
    65 .mceColorPreview {position: absolute;  left: 0;  top: 0;  margin-left: 3px;  margin-top: 15px;  width: 16px;  height: 4px; background-color: red;}
     62span.mceMenuLine {display: block; position: absolute; left: 0; top: -1px; background-color: #F5F4F2; width: 30px; height: 1px; overflow: hidden; padding-left: 0; padding-right: 0;}
     63.mceColors table, .mceColors td {margin: 0; padding: 2px;}
     64a.mceMoreColors {width: auto; padding: 0; margin: 0 3px 3px 3px; text-align: center; border: 1px solid white; text-decoration: none !important;}
     65.mceColorPreview {position: absolute; overflow:hidden; left: 0; top: 0; margin-left: 3px; margin-top: 15px; width: 16px; height: 4px; background-color: red;}
    6666a.mceMoreColors:hover {border: 1px solid #0A246A;}
    67 .mceColors td a {width: 9px;  height: 9px;  overflow: hidden; border: 1px solid #808080;}
     67.mceColors td a {width: 9px; height: 9px; overflow: hidden; border: 1px solid #808080;}
    6868
    6969/* MSIE 6 specific rules */
    7070
    71 * html a.mceButtonNormal img, * html a.mceButtonSelected img, * html a.mceButtonDisabled img {border: 0 !important;  margin-top: 2px; margin-bottom: 1px;}
    72 * html a.mceButtonDisabled img {filter:progid:DXImageTransform.Microsoft.Alpha(opacity=30);  border: 0 !important;}
     71* html a.mceButtonNormal img, * html a.mceButtonSelected img, * html a.mceButtonDisabled img {border: 0 !important; margin-top: 2px; margin-bottom: 1px;}
     72* html a.mceButtonDisabled img {filter:progid:DXImageTransform.Microsoft.Alpha(opacity=30); border: 0 !important;}
    7373* html a.mceButtonDisabled {border: 1px solid #F0F0EE !important;}
    74 * html a.mceButtonNormal, * html a.mceButtonSelected {border: 1px solid #F0F0EE !important;  cursor: default;}
    75 * html a.mceButtonSelected {border: 1px solid #6779AA !important;  background-color: #D4D5D8;}
    76 * html a.mceButtonNormal:hover, * html a.mceButtonSelected:hover {border: 1px solid #0A246A !important;  background-color: #B6BDD2; cursor: default;}
     74* html a.mceButtonNormal, * html a.mceButtonSelected {border: 1px solid #F0F0EE !important; cursor: default;}
     75* html a.mceButtonSelected {border: 1px solid #6779AA !important; background-color: #D4D5D8;}
     76* html a.mceButtonNormal:hover, * html a.mceButtonSelected:hover {border: 1px solid #0A246A !important; background-color: #B6BDD2; cursor: default;}
    7777* html .mceSelectList {margin-top: 2px;}
    78 * html span.mceMenuButton, * html span.mceMenuButtonFocus {position: relative;  left: 0; top: 0;}
    79 * html span.mceMenuButton img, * html span.mceMenuButtonSelected img, * html span.mceMenuButtonFocus img {position: relative;  top: 1px;}
    80 * html a.mceMoreColors {width: 132px;}
    81 * html .mceColors td a {width: 10px;  height: 10px;}
    82 * html .mceColorPreview {margin-left: 2px;  margin-top: 14px;}
     78* html span.mceMenuButton, * html span.mceMenuButtonFocus {position: relative; left: 0; top: 0;}
     79* html span.mceMenuButton img, * html span.mceMenuButtonSelected img, * html span.mceMenuButtonFocus img {position: relative; top: 1px;}
     80* html a.mceMoreColors {width: auto;}
     81* html .mceColors td a {width: 10px; height: 10px;}
     82* html .mceColorPreview {margin-left: 2px; margin-top: 14px;}
    8383
    8484/* MSIE 7 specific rules */
    8585
    86 *:first-child+html a.mceButtonNormal img, *:first-child+html a.mceButtonSelected img, *:first-child+html a.mceButtonDisabled img {border: 0 !important;  margin-top: 2px; margin-bottom: 1px;}
    87 *:first-child+html a.mceButtonDisabled img {filter:progid:DXImageTransform.Microsoft.Alpha(opacity=30);  border: 0 !important;}
     86*:first-child+html a.mceButtonNormal img, *:first-child+html a.mceButtonSelected img, *:first-child+html a.mceButtonDisabled img {border: 0 !important; margin-top: 2px; margin-bottom: 1px;}
     87*:first-child+html a.mceButtonDisabled img {filter:progid:DXImageTransform.Microsoft.Alpha(opacity=30); border: 0 !important;}
    8888*:first-child+html a.mceButtonDisabled {border: 1px solid #F0F0EE !important;}
    89 *:first-child+html a.mceButtonNormal, *:first-child+html a.mceButtonSelected {border: 1px solid #F0F0EE !important;  cursor: default;}
    90 *:first-child+html a.mceButtonSelected {border: 1px solid #6779AA !important;  background-color: #D4D5D8;}
    91 *:first-child+html a.mceButtonNormal:hover, *:first-child+html a.mceButtonSelected:hover {border: 1px solid #0A246A !important;  background-color: #B6BDD2; cursor: default;}
     89*:first-child+html a.mceButtonNormal, *:first-child+html a.mceButtonSelected {border: 1px solid #F0F0EE !important; cursor: default;}
     90*:first-child+html a.mceButtonSelected {border: 1px solid #6779AA !important; background-color: #D4D5D8;}
     91*:first-child+html a.mceButtonNormal:hover, *:first-child+html a.mceButtonSelected:hover {border: 1px solid #0A246A !important; background-color: #B6BDD2; cursor: default;}
    9292*:first-child+html .mceSelectList {margin-top: 2px;}
    93 *:first-child+html span.mceMenuButton, *:first-child+html span.mceMenuButtonFocus {position: relative;  left: 0; top: 0;}
    94 *:first-child+html span.mceMenuButton img, *:first-child+html span.mceMenuButtonSelected img, *:first-child+html span.mceMenuButtonFocus img {position: relative;  top: 1px;}
    95 *:first-child+html a.mceMoreColors {width: 132px;}
    96 *:first-child+html .mceColors td a {width: 10px;  height: 10px;}
    97 *:first-child+html .mceColorPreview {margin: 0; padding-left: 4px;  margin-top: 14px; width: 14px;}
     93*:first-child+html span.mceMenuButton, *:first-child+html span.mceMenuButtonFocus {position: relative; left: 0; top: 0;}
     94*:first-child+html span.mceMenuButton img, *:first-child+html span.mceMenuButtonSelected img, *:first-child+html span.mceMenuButtonFocus img {position: relative; top: 1px;}
     95*:first-child+html a.mceMoreColors {width: 137px;}
     96*:first-child+html .mceColors td a {width: 10px; height: 10px;}
     97*:first-child+html .mceColorPreview {margin: 0; padding-left: 4px; margin-top: 14px; width: 14px;}
  • tags/2.2/wp-includes/js/tinymce/themes/advanced/editor_template.js

    r5468 r5480  
    11/**
    2  * $Id: editor_template_src.js 129 2006-10-23 09:45:17Z spocke $
     2 * $Id: editor_template_src.js 218 2007-02-13 11:08:01Z spocke $
    33 *
    44 * @author Moxiecode
    5  * @copyright Copyright © 2004-2006, Moxiecode Systems AB, All rights reserved.
     5 * @copyright Copyright © 2004-2007, Moxiecode Systems AB, All rights reserved.
    66 */
    77
     
    4444        ['sup', 'sup.gif', 'lang_theme_sup_desc', 'superscript'],
    4545        ['forecolor', 'forecolor.gif', 'lang_theme_forecolor_desc', 'forecolor', true],
     46        ['forecolorpicker', 'forecolor.gif', 'lang_theme_forecolor_desc', 'forecolorpicker', true],
    4647        ['backcolor', 'backcolor.gif', 'lang_theme_backcolor_desc', 'HiliteColor', true],
     48        ['backcolorpicker', 'backcolor.gif', 'lang_theme_backcolor_desc', 'backcolorpicker', true],
    4749        ['charmap', 'charmap.gif', 'lang_theme_charmap_desc', 'mceCharMap'],
    4850        ['visualaid', 'visualaid.gif', 'lang_theme_visualaid_desc', 'mceToggleVisualAid'],
     
    357359                return false;
    358360
     361            case "forecolorpicker":
     362                this._pickColor(editor_id, 'forecolor');
     363                return true;
     364
    359365            case "forecolorMenu":
    360366                TinyMCE_AdvancedTheme._hideMenus(editor_id);
     
    421427                ml.show();
    422428            return true;
     429   
     430            case "backcolorpicker":
     431                this._pickColor(editor_id, 'HiliteColor');
     432                return true;
    423433
    424434            case "mceColorPicker":
    425435                if (user_interface) {
    426                     var template = new Array();
    427                     var inputColor = value['document'].getElementById(value['element_id']).value;
     436                    var template = [];
     437   
     438                    if (!value['callback'] && !value['color'])
     439                        value['color'] = value['document'].getElementById(value['element_id']).value;
    428440
    429441                    template['file'] = 'color_picker.htm';
    430                     template['width'] = 220;
    431                     template['height'] = 190;
     442                    template['width'] = 380;
     443                    template['height'] = 250;
    432444                    template['close_previous'] = "no";
    433445
     
    439451
    440452                    tinyMCE.lastColorPickerValue = value;
    441                     tinyMCE.openWindow(template, {editor_id : editor_id, mce_store_selection : value['store_selection'], inline : "yes", command : "mceColorPicker", input_color : inputColor});
     453                    tinyMCE.openWindow(template, {editor_id : editor_id, mce_store_selection : value['store_selection'], inline : "yes", command : "mceColorPicker", input_color : value['color']});
    442454                } else {
    443                     var savedVal = tinyMCE.lastColorPickerValue;
    444                     var elm = savedVal['document'].getElementById(savedVal['element_id']);
     455                    var savedVal = tinyMCE.lastColorPickerValue, elm;
     456
     457                    if (savedVal['callback']) {
     458                        savedVal['callback'](value);
     459                        return true;
     460                    }
     461
     462                    elm = savedVal['document'].getElementById(savedVal['element_id']);
    445463                    elm.value = value;
    446464
     
    600618                template['html'] = '<table class="mceEditor" border="0" cellpadding="0" cellspacing="0" width="{$width}" height="{$height}" style="width:{$width_style};height:{$height_style}"><tbody>';
    601619
    602                 if (toolbarLocation == "top") {
    603                     template['html'] += '<tr><td class="mceToolbarTop" align="' + toolbarAlign + '" height="1" nowrap="nowrap"><span id="' + editorId + '_toolbar" class="mceToolbarContainer">' + toolbarHTML + '</span></td></tr>';
    604                 }
     620                if (toolbarLocation == "top")
     621                    template['html'] += '<tr><td dir="ltr" class="mceToolbarTop" align="' + toolbarAlign + '" height="1" nowrap="nowrap"><span id="' + editorId + '_toolbar" class="mceToolbarContainer">' + toolbarHTML + '</span></td></tr>';
    605622
    606623                if (statusbarLocation == "top") {
     
    611628                template['html'] += '<tr><td align="center"><span id="{$editor_id}"></span></td></tr>';
    612629
    613                 if (toolbarLocation == "bottom") {
    614                     template['html'] += '<tr><td class="mceToolbarBottom" align="' + toolbarAlign + '" height="1"><span id="' + editorId + '_toolbar" class="mceToolbarContainer">' + toolbarHTML + '</span></td></tr>';
    615                 }
     630                if (toolbarLocation == "bottom")
     631                    template['html'] += '<tr><td dir="ltr" class="mceToolbarBottom" align="' + toolbarAlign + '" height="1"><span id="' + editorId + '_toolbar" class="mceToolbarContainer">' + toolbarHTML + '</span></td></tr>';
    616632
    617633                // External toolbar changes
     
    714730
    715731        template['html'] = tinyMCE.replaceVar(template['html'], 'style_select_options', styleSelectHTML);
    716         template['delta_width'] = 0;
    717         template['delta_height'] = deltaHeight;
     732
     733        // Set to default values
     734        if (!template['delta_width'])
     735            template['delta_width'] = 0;
     736
     737        if (!template['delta_height'])
     738            template['delta_height'] = deltaHeight;
    718739
    719740        return template;
     
    733754    },
    734755
     756    removeInstance : function(inst) {
     757        new TinyMCE_Layer(inst.editorId + '_fcMenu').remove();
     758        new TinyMCE_Layer(inst.editorId + '_bcMenu').remove();
     759    },
     760
     761    hideInstance : function(inst) {
     762        TinyMCE_AdvancedTheme._hideMenus(inst.editorId);
     763    },
     764
    735765    _handleMenuEvent : function(e) {
    736766        var te = tinyMCE.isMSIE ? window.event.srcElement : e.target;
     
    781811
    782812            return false;
    783         };
    784 
    785         function getAttrib(elm, name) {
    786             return elm.getAttribute(name) ? elm.getAttribute(name) : "";
    787813        };
    788814
     
    840866                    if (st != "") {
    841867                        st = tinyMCE.serializeStyle(tinyMCE.parseStyle(st));
    842                         nodeData += "style: " + st + " ";
     868                        nodeData += "style: " + tinyMCE.xmlEncode(st) + " ";
    843869                    }
    844870                }
     
    850876                    var face = tinyMCE.getAttrib(path[i], "face");
    851877                    if (face != "")
    852                         nodeData += "font: " + face + " ";
     878                        nodeData += "font: " + tinyMCE.xmlEncode(face) + " ";
    853879
    854880                    var size = tinyMCE.getAttrib(path[i], "size");
    855881                    if (size != "")
    856                         nodeData += "size: " + size + " ";
     882                        nodeData += "size: " + tinyMCE.xmlEncode(size) + " ";
    857883
    858884                    var color = tinyMCE.getAttrib(path[i], "color");
    859885                    if (color != "")
    860                         nodeData += "color: " + color + " ";
    861                 }
    862 
    863                 if (getAttrib(path[i], 'id') != "") {
     886                        nodeData += "color: " + tinyMCE.xmlEncode(color) + " ";
     887                }
     888
     889                if (tinyMCE.getAttrib(path[i], 'id') != "") {
    864890                    nodeData += "id: " + path[i].getAttribute('id') + " ";
    865891                }
     
    869895                    nodeData += "class: " + className + " ";
    870896
    871                 if (getAttrib(path[i], 'src') != "") {
     897                if (tinyMCE.getAttrib(path[i], 'src') != "") {
    872898                    var src = tinyMCE.getAttrib(path[i], "mce_src");
    873899
     
    875901                         src = tinyMCE.getAttrib(path[i], "src");
    876902
    877                     nodeData += "src: " + src + " ";
    878                 }
    879 
    880                 if (path[i].nodeName == 'A' && getAttrib(path[i], 'href') != "") {
     903                    nodeData += "src: " + tinyMCE.xmlEncode(src) + " ";
     904                }
     905
     906                if (path[i].nodeName == 'A' && tinyMCE.getAttrib(path[i], 'href') != "") {
    881907                    var href = tinyMCE.getAttrib(path[i], "mce_href");
    882908
     
    884910                         href = tinyMCE.getAttrib(path[i], "href");
    885911
    886                     nodeData += "href: " + href + " ";
     912                    nodeData += "href: " + tinyMCE.xmlEncode(href) + " ";
    887913                }
    888914
     
    895921                if (nodeName == "a" && (anchor = tinyMCE.getAttrib(path[i], "name")) != "") {
    896922                    nodeName = "a";
    897                     nodeName += "#" + anchor;
     923                    nodeName += "#" + tinyMCE.xmlEncode(anchor);
    898924                    nodeData = "";
    899925                }
    900926
    901                 if (getAttrib(path[i], 'name').indexOf("mce_") != 0) {
     927                if (tinyMCE.getAttrib(path[i], 'name').indexOf("mce_") != 0) {
    902928                    var className = tinyMCE.getVisualAidClass(tinyMCE.getAttrib(path[i], "class"), false);
    903929                    if (className != "" && className.indexOf('mceItem') == -1) {
     
    11251151
    11261152                case "IMG":
    1127                 if (getAttrib(node, 'name').indexOf('mce_') != 0 && tinyMCE.getAttrib(node, 'class').indexOf('mceItem') == -1) {
     1153                if (tinyMCE.getAttrib(node, 'name').indexOf('mce_') != 0 && tinyMCE.getAttrib(node, 'class').indexOf('mceItem') == -1) {
    11281154                    tinyMCE.switchClass(editor_id + '_image', 'mceButtonSelected');
    11291155                }
     
    12181244            tableElm.style.width = w + "px";
    12191245
     1246        if ( !tinyMCE.isMSIE || tinyMCE.isMSIE7 || tinyMCE.isOpera ) // WordPress: do this later to avoid creeping toolbar bug in MSIE6
    12201247        tableElm.style.height = h + "px";
    12211248
     
    12261253        ih = ih < 1 ? 30 : ih;
    12271254
     1255/* WordPress found that this led to a shrinking editor with every resize. (Gray background creeps in 1px at a time.)
    12281256        if (tinyMCE.isGecko) {
    12291257            iw -= 2;
    12301258            ih -= 2;
    12311259        }
     1260*/
    12321261
    12331262        if (set_w)
     
    12461275            }
    12471276        }
     1277
     1278        tableElm.style.height = h + "px"; // WordPress: see above
    12481279
    12491280        // Remove pesky table controls
     
    13721403
    13731404        h += '</tr></table>';
    1374         /*
    1375         h += '<a href="" class="mceMoreColors">More colors</a>';
    1376         */
     1405
     1406        if (tinyMCE.getParam("theme_advanced_more_colors", true))
     1407            h += '<a href="#" onclick="TinyMCE_AdvancedTheme._pickColor(\'' + id + '\',\'' + cm + '\');" class="mceMoreColors">' + tinyMCE.getLang('lang_more_colors') + '</a>';
    13771408
    13781409        return h;
     1410    },
     1411
     1412    _pickColor : function(id, cm) {
     1413        var inputColor, inst = tinyMCE.selectedInstance;
     1414
     1415        if (cm == 'forecolor' && inst)
     1416            inputColor = inst.foreColor;
     1417
     1418        if ((cm == 'backcolor' || cm == 'HiliteColor') && inst)
     1419            inputColor = inst.backColor;
     1420
     1421        tinyMCE.execCommand('mceColorPicker', true, {color : inputColor, callback : function(c) {
     1422            tinyMCE.execInstanceCommand(id, cm, false, c);
     1423        }});
    13791424    },
    13801425
  • tags/2.2/wp-includes/js/tinymce/themes/advanced/jscripts/color_picker.js

    r5468 r5480  
    1 function init() {
    2     if (tinyMCE.isMSIE)
    3         tinyMCEPopup.resizeToInnerSize();
    4 }
    5 
    6 function selectColor() {
    7     var color = document.getElementById("selectedColorBox").value;
    8 
    9     tinyMCEPopup.execCommand(tinyMCE.getWindowArg('command'), false, color);
    10     tinyMCEPopup.close();
    11 }
    12 
    13 function showColor(color) {
    14     document.getElementById("selectedColor").style.backgroundColor = color;
    15     document.getElementById("selectedColorBox").value = color;
    16 }
     1var detail = 50, strhex = "0123456789abcdef", i, isMouseDown = false, isMouseOver = false;
    172
    183var colors = new Array(
     
    4631);
    4732
     33var named = {
     34    '#F0F8FF':'AliceBlue','#FAEBD7':'AntiqueWhite','#00FFFF':'Aqua','#7FFFD4':'Aquamarine','#F0FFFF':'Azure','#F5F5DC':'Beige',
     35    '#FFE4C4':'Bisque','#000000':'Black','#FFEBCD':'BlanchedAlmond','#0000FF':'Blue','#8A2BE2':'BlueViolet','#A52A2A':'Brown',
     36    '#DEB887':'BurlyWood','#5F9EA0':'CadetBlue','#7FFF00':'Chartreuse','#D2691E':'Chocolate','#FF7F50':'Coral','#6495ED':'CornflowerBlue',
     37    '#FFF8DC':'Cornsilk','#DC143C':'Crimson','#00FFFF':'Cyan','#00008B':'DarkBlue','#008B8B':'DarkCyan','#B8860B':'DarkGoldenRod',
     38    '#A9A9A9':'DarkGray','#A9A9A9':'DarkGrey','#006400':'DarkGreen','#BDB76B':'DarkKhaki','#8B008B':'DarkMagenta','#556B2F':'DarkOliveGreen',
     39    '#FF8C00':'Darkorange','#9932CC':'DarkOrchid','#8B0000':'DarkRed','#E9967A':'DarkSalmon','#8FBC8F':'DarkSeaGreen','#483D8B':'DarkSlateBlue',
     40    '#2F4F4F':'DarkSlateGray','#2F4F4F':'DarkSlateGrey','#00CED1':'DarkTurquoise','#9400D3':'DarkViolet','#FF1493':'DeepPink','#00BFFF':'DeepSkyBlue',
     41    '#696969':'DimGray','#696969':'DimGrey','#1E90FF':'DodgerBlue','#B22222':'FireBrick','#FFFAF0':'FloralWhite','#228B22':'ForestGreen',
     42    '#FF00FF':'Fuchsia','#DCDCDC':'Gainsboro','#F8F8FF':'GhostWhite','#FFD700':'Gold','#DAA520':'GoldenRod','#808080':'Gray','#808080':'Grey',
     43    '#008000':'Green','#ADFF2F':'GreenYellow','#F0FFF0':'HoneyDew','#FF69B4':'HotPink','#CD5C5C':'IndianRed','#4B0082':'Indigo','#FFFFF0':'Ivory',
     44    '#F0E68C':'Khaki','#E6E6FA':'Lavender','#FFF0F5':'LavenderBlush','#7CFC00':'LawnGreen','#FFFACD':'LemonChiffon','#ADD8E6':'LightBlue',
     45    '#F08080':'LightCoral','#E0FFFF':'LightCyan','#FAFAD2':'LightGoldenRodYellow','#D3D3D3':'LightGray','#D3D3D3':'LightGrey','#90EE90':'LightGreen',
     46    '#FFB6C1':'LightPink','#FFA07A':'LightSalmon','#20B2AA':'LightSeaGreen','#87CEFA':'LightSkyBlue','#778899':'LightSlateGray','#778899':'LightSlateGrey',
     47    '#B0C4DE':'LightSteelBlue','#FFFFE0':'LightYellow','#00FF00':'Lime','#32CD32':'LimeGreen','#FAF0E6':'Linen','#FF00FF':'Magenta','#800000':'Maroon',
     48    '#66CDAA':'MediumAquaMarine','#0000CD':'MediumBlue','#BA55D3':'MediumOrchid','#9370D8':'MediumPurple','#3CB371':'MediumSeaGreen','#7B68EE':'MediumSlateBlue',
     49    '#00FA9A':'MediumSpringGreen','#48D1CC':'MediumTurquoise','#C71585':'MediumVioletRed','#191970':'MidnightBlue','#F5FFFA':'MintCream','#FFE4E1':'MistyRose','#FFE4B5':'Moccasin',
     50    '#FFDEAD':'NavajoWhite','#000080':'Navy','#FDF5E6':'OldLace','#808000':'Olive','#6B8E23':'OliveDrab','#FFA500':'Orange','#FF4500':'OrangeRed','#DA70D6':'Orchid',
     51    '#EEE8AA':'PaleGoldenRod','#98FB98':'PaleGreen','#AFEEEE':'PaleTurquoise','#D87093':'PaleVioletRed','#FFEFD5':'PapayaWhip','#FFDAB9':'PeachPuff',
     52    '#CD853F':'Peru','#FFC0CB':'Pink','#DDA0DD':'Plum','#B0E0E6':'PowderBlue','#800080':'Purple','#FF0000':'Red','#BC8F8F':'RosyBrown','#4169E1':'RoyalBlue',
     53    '#8B4513':'SaddleBrown','#FA8072':'Salmon','#F4A460':'SandyBrown','#2E8B57':'SeaGreen','#FFF5EE':'SeaShell','#A0522D':'Sienna','#C0C0C0':'Silver',
     54    '#87CEEB':'SkyBlue','#6A5ACD':'SlateBlue','#708090':'SlateGray','#708090':'SlateGrey','#FFFAFA':'Snow','#00FF7F':'SpringGreen',
     55    '#4682B4':'SteelBlue','#D2B48C':'Tan','#008080':'Teal','#D8BFD8':'Thistle','#FF6347':'Tomato','#40E0D0':'Turquoise','#EE82EE':'Violet',
     56    '#F5DEB3':'Wheat','#FFFFFF':'White','#F5F5F5':'WhiteSmoke','#FFFF00':'Yellow','#9ACD32':'YellowGreen'
     57};
     58
     59function init() {
     60    var inputColor = convertRGBToHex(tinyMCE.getWindowArg('input_color'));
     61
     62    if (tinyMCE.isMSIE)
     63        tinyMCEPopup.resizeToInnerSize();
     64
     65    generatePicker();
     66
     67    if (inputColor) {
     68        changeFinalColor(inputColor);
     69
     70        col = convertHexToRGB(inputColor);
     71
     72        if (col)
     73            updateLight(col.r, col.g, col.b);
     74    }
     75}
     76
     77function insertAction() {
     78    var color = document.getElementById("color").value;
     79
     80    tinyMCEPopup.execCommand(tinyMCE.getWindowArg('command'), false, color);
     81    tinyMCEPopup.close();
     82}
     83
     84function showColor(color, name) {
     85    if (name)
     86        document.getElementById("colorname").innerHTML = name;
     87
     88    document.getElementById("preview").style.backgroundColor = color;
     89    document.getElementById("color").value = color;
     90}
     91
    4892function convertRGBToHex(col) {
    4993    var re = new RegExp("rgb\\s*\\(\\s*([0-9]+).*,\\s*([0-9]+).*,\\s*([0-9]+).*\\)", "gi");
     94
     95    if (!col)
     96        return col;
    5097
    5198    var rgb = col.replace(re, "$1,$2,$3").split(',');
     
    73120        b = parseInt(col.substring(4, 6), 16);
    74121
    75         return "rgb(" + r + "," + g + "," + b + ")";
    76     }
    77 
    78     return col;
    79 }
    80 
    81 function renderColorMap() {
    82     var html = "";
    83     var inputColor = convertRGBToHex(tinyMCE.getWindowArg('input_color'));
    84 
    85     html += '<table border="0" cellspacing="1" cellpadding="0">'
     122        return {r : r, g : g, b : b};
     123    }
     124
     125    return null;
     126}
     127
     128function generatePicker() {
     129    var el = document.getElementById('light'), h = '', i;
     130
     131    for (i = 0; i < detail; i++){
     132        h += '<div id="gs'+i+'" style="background-color:#000000; width:15px; height:3px; border-style:none; border-width:0px;"'
     133        + ' onclick="changeFinalColor(this.style.backgroundColor)"'
     134        + ' onmousedown="isMouseDown = true; return false;"'
     135        + ' onmouseup="isMouseDown = false;"'
     136        + ' onmousemove="if (isMouseDown && isMouseOver) changeFinalColor(this.style.backgroundColor); return false;"'
     137        + ' onmouseover="isMouseOver = true;"'
     138        + ' onmouseout="isMouseOver = false;"'
     139        + '></div>';
     140    }
     141
     142    el.innerHTML = h;
     143}
     144
     145function generateWebColors() {
     146    var el = document.getElementById('webcolors'), h = '', i;
     147
     148    if (el.className == 'generated')
     149        return;
     150
     151    h += '<table border="0" cellspacing="1" cellpadding="0">'
    86152        + '<tr>';
    87     for (var i=0; i<colors.length; i++) {
    88         html += '<td bgcolor="' + colors[i] + '">'
     153
     154    for (i=0; i<colors.length; i++) {
     155        h += '<td bgcolor="' + colors[i] + '">'
    89156            + '<a href="javascript:selectColor();" onfocus="showColor(\'' + colors[i] +  '\');" onmouseover="showColor(\'' + colors[i] +  '\');">'
    90157            + '<img border="0" src="images/spacer.gif" width="10" height="10" title="' + colors[i] +  '" alt="' + colors[i] +  '" /></a></td>';
    91158        if ((i+1) % 18 == 0)
    92             html += '</tr><tr>';
    93     }
    94     html += '<tr><td colspan="18">'
    95         + '<table width="100%" border="0" cellspacing="0" cellpadding="0">'
    96         + '<tr><td>'
    97         + '<img id="selectedColor" style="background-color:' + tinyMCE.getWindowArg('input_color') + '" border="0" src="images/spacer.gif" width="80" height="16" />'
    98         + '</td><td align="right">'
    99         + '<input id="selectedColorBox" name="selectedColorBox" type="text" size="7" maxlength="7" style="width:65px" value="' + inputColor + '" />'
    100         + '</td></tr>'
    101         + '</table>'
    102         + '<div style="float: left"><input type="button" id="insert" name="insert" value="{$lang_theme_colorpicker_apply}" style="margin-top:3px" onclick="selectColor();"></div>'
    103         + '<div style="float: right"><input type="button" name="cancel" value="{$lang_cancel}" style="margin-top:3px" onclick="tinyMCEPopup.close();" id="cancel" /></div>'
    104         + '</td></tr>'
    105         + '</table>';
    106 
    107     document.write(html);
    108 }
     159            h += '</tr><tr>';
     160    }
     161
     162    h += '</table>';
     163
     164    el.innerHTML = h;
     165    el.className = 'generated';
     166}
     167
     168function generateNamedColors() {
     169    var el = document.getElementById('namedcolors'), h = '', n, v, i = 0;
     170
     171    if (el.className == 'generated')
     172        return;
     173
     174    for (n in named) {
     175        v = named[n];
     176        h += '<a href="javascript:selectColor();" onmouseover="showColor(\'' + n +  '\',\'' + v + '\');" style="background-color: ' + n + '"><!-- IE --></a>'
     177    }
     178
     179    el.innerHTML = h;
     180    el.className = 'generated';
     181}
     182
     183function selectColor() {
     184    var color = document.getElementById("color").value;
     185
     186    if(window.opener)
     187        window.opener.tinyMCE.execInstanceCommand(tinyMCE.getWindowArg('editor_id'),tinyMCE.getWindowArg('command'),false,color);
     188
     189    window.close();
     190}
     191
     192function dechex(n) {
     193    return strhex.charAt(Math.floor(n / 16)) + strhex.charAt(n % 16);
     194}
     195
     196function computeColor(e) {
     197    var x, y, partWidth, partDetail, imHeight, r, g, b, coef, i, finalCoef, finalR, finalG, finalB;
     198
     199    x = e.offsetX ? e.offsetX : (e.target ? e.clientX - e.target.x : 0);
     200    y = e.offsetY ? e.offsetY : (e.target ? e.clientY - e.target.y : 0);
     201
     202    partWidth = document.getElementById('colorpicker').width / 6;
     203    partDetail = detail / 2;
     204    imHeight = document.getElementById('colorpicker').height;
     205
     206    r = (x >= 0)*(x < partWidth)*255 + (x >= partWidth)*(x < 2*partWidth)*(2*255 - x * 255 / partWidth) + (x >= 4*partWidth)*(x < 5*partWidth)*(-4*255 + x * 255 / partWidth) + (x >= 5*partWidth)*(x < 6*partWidth)*255;
     207    g = (x >= 0)*(x < partWidth)*(x * 255 / partWidth) + (x >= partWidth)*(x < 3*partWidth)*255 + (x >= 3*partWidth)*(x < 4*partWidth)*(4*255 - x * 255 / partWidth);
     208    b = (x >= 2*partWidth)*(x < 3*partWidth)*(-2*255 + x * 255 / partWidth) + (x >= 3*partWidth)*(x < 5*partWidth)*255 + (x >= 5*partWidth)*(x < 6*partWidth)*(6*255 - x * 255 / partWidth);
     209
     210    coef = (imHeight - y) / imHeight;
     211    r = 128 + (r - 128) * coef;
     212    g = 128 + (g - 128) * coef;
     213    b = 128 + (b - 128) * coef;
     214
     215    changeFinalColor('#' + dechex(r) + dechex(g) + dechex(b));
     216    updateLight(r, g, b);
     217}
     218
     219function updateLight(r, g, b) {
     220    var i, partDetail = detail / 2, finalCoef, finalR, finalG, finalB, color;
     221
     222    for (i=0; i<detail; i++) {
     223        if ((i>=0) && (i<partDetail)) {
     224            finalCoef = i / partDetail;
     225            finalR = dechex(255 - (255 - r) * finalCoef);
     226            finalG = dechex(255 - (255 - g) * finalCoef);
     227            finalB = dechex(255 - (255 - b) * finalCoef);
     228        } else {
     229            finalCoef = 2 - i / partDetail;
     230            finalR = dechex(r * finalCoef);
     231            finalG = dechex(g * finalCoef);
     232            finalB = dechex(b * finalCoef);
     233        }
     234
     235        color = finalR + finalG + finalB;
     236
     237        document.getElementById('gs' + i).style.backgroundColor = '#'+color;
     238    }
     239}
     240
     241function changeFinalColor(color) {
     242    if (color.indexOf('#') == -1)
     243        color = convertRGBToHex(color);
     244
     245    document.getElementById('preview').style.backgroundColor = color;
     246    document.getElementById('color').value = color;
     247}
     248
     249window.focus();
  • tags/2.2/wp-includes/js/tinymce/themes/advanced/jscripts/link.js

    r5468 r5480  
    2828    document.forms[0].href.value = tinyMCE.getWindowArg('href') || 'http://';
    2929    document.forms[0].href.select();
     30    document.forms[0].href.focus();
    3031    document.forms[0].linktitle.value = tinyMCE.getWindowArg('title');
    3132    document.forms[0].insert.value = tinyMCE.getLang('lang_' + tinyMCE.getWindowArg('action'), 'Insert', true);
     
    5859    var style_class = document.forms[0].styleSelect ? document.forms[0].styleSelect.value : "";
    5960    var dummy;
    60 
    61     // Make anchors absolute
     61   
     62    // WordPress: Make anchors absolute;
    6263    if (href.charAt(0) == '#')
    6364        href = tinyMCE.settings['document_base_url'] + href;
  • tags/2.2/wp-includes/js/tinymce/themes/advanced/jscripts/source_editor.js

    r5468 r5480  
    2626    s.wrap = val;
    2727
    28     if (tinyMCE.isGecko) {
     28    if (tinyMCE.isGecko || tinyMCE.isOpera) {
    2929        var v = s.value;
    3030        var n = s.cloneNode(false);
     
    4848
    4949    if (!tinyMCE.isMSIE) {
    50          wHeight = self.innerHeight-80;
    51          wWidth = self.innerWidth-16;
     50         wHeight = self.innerHeight - 60;
     51         wWidth = self.innerWidth - 16;
    5252    } else {
    53          wHeight = document.body.clientHeight - 80;
     53         wHeight = document.body.clientHeight - 60;
    5454         wWidth = document.body.clientWidth - 16;
    5555    }
     
    5858    el.style.width  = Math.abs(wWidth) + 'px';
    5959}
    60 
  • tags/2.2/wp-includes/js/tinymce/themes/advanced/langs/en.js

    r5468 r5480  
    7979close : 'Close',
    8080toolbar_focus : 'Jump to tool buttons - Alt+Q, Jump to editor - Alt-Z, Jump to element path - Alt-X',
    81 invalid_data : 'Error: Invalid values entered, these are marked in red.'
     81invalid_data : 'Error: Invalid values entered, these are marked in red.',
     82more_colors : 'More colors',
     83color_picker_tab : 'Picker',
     84color_picker : 'Color picker',
     85web_colors_tab : 'Web safe',
     86web_colors : 'Web safe colors',
     87named_colors_tab : 'Named',
     88named_colors : 'Named colors',
     89color : 'Color:',
     90color_name : 'Name:'
    8291});
  • tags/2.2/wp-includes/js/tinymce/tiny_mce.js

    r5468 r5480  
    66
    77    this.majorVersion = "2";
    8     this.minorVersion = "0.8";
    9     this.releaseDate = "2006-10-23";
     8    this.minorVersion = "1.0";
     9    this.releaseDate = "2007-02-13";
    1010
    1111    this.instances = new Array();
     
    187187        this._def("convert_on_click", false);
    188188        this._def("content_css", '');
    189         this._def("fix_list_elements", false);
     189        this._def("fix_list_elements", true);
    190190        this._def("fix_table_elements", false);
    191191        this._def("strict_loading_mode", document.contentType == 'application/xhtml+xml');
     
    193193        this._def("display_tab_class", '');
    194194        this._def("gecko_spellcheck", false);
     195        this._def("hide_selects_on_submit", true);
    195196
    196197        // Force strict loading mode to false on non Gecko browsers
     
    241242        this.blockRegExp = new RegExp("^(" + this.blockElms + ")$", "i");
    242243        this.posKeyCodes = new Array(13,45,36,35,33,34,37,38,39,40);
    243         this.uniqueURL = 'javascript:TINYMCE_UNIQUEURL();'; // Make unique URL non real URL
     244        this.uniqueURL = 'javascript:void(091039730);'; // Make unique URL non real URL
    244245        this.uniqueTag = '<div id="mceTMPElement" style="display: none">TMP</div>';
    245         this.callbacks = new Array('onInit', 'getInfo', 'getEditorTemplate', 'setupContent', 'onChange', 'onPageLoad', 'handleNodeChange', 'initInstance', 'execCommand', 'getControlHTML', 'handleEvent', 'cleanup');
     246        this.callbacks = new Array('onInit', 'getInfo', 'getEditorTemplate', 'setupContent', 'onChange', 'onPageLoad', 'handleNodeChange', 'initInstance', 'execCommand', 'getControlHTML', 'handleEvent', 'cleanup', 'removeInstance');
    246247
    247248        // Theme url
     
    339340            }
    340341        }
     342
     343        // Setup XML encoding regexps
     344        this.xmlEncodeAposRe = new RegExp('[<>&"\']', 'g');
     345        this.xmlEncodeRe = new RegExp('[<>&"]', 'g');
     346//      this.xmlEncodeEnts = {'&':'&amp;','"':'&quot;',"'":'&#39;','<':'&lt;','>':'&gt;'};
    341347    },
    342348
     
    571577        tinyMCE.undoIndex = n.length;
    572578
     579        // Dispatch remove instance call
     580        tinyMCE.dispatchCallback(ti, 'remove_instance_callback', 'removeInstance', ti);
     581
    573582        return ti;
    574583    },
     
    730739            case "mceRemoveEditor":
    731740                tinyMCE.removeMCEControl(value);
     741                return;
     742
     743            case "mceToggleEditor":
     744                var inst = tinyMCE.getInstanceById(value), pe, te;
     745
     746                if (inst) {
     747                    pe = document.getElementById(inst.editorId + '_parent');
     748                    te = inst.oldTargetElement;
     749
     750                    if (typeof(inst.enabled) == 'undefined')
     751                        inst.enabled = true;
     752
     753                    inst.enabled = !inst.enabled;
     754
     755                    if (!inst.enabled) {
     756                        pe.style.display = 'none';
     757                        te.value = inst.getHTML();
     758                        te.style.display = inst.oldTargetDisplay;
     759                        tinyMCE.dispatchCallback(inst, 'hide_instance_callback', 'hideInstance', inst);
     760                    } else {
     761                        pe.style.display = 'block';
     762                        te.style.display = 'none';
     763                        inst.setHTML(te.value);
     764                        inst.useCSS = false;
     765                        tinyMCE.dispatchCallback(inst, 'show_instance_callback', 'showInstance', inst);
     766                    }
     767                } else
     768                    tinyMCE.addMCEControl(tinyMCE._getElementById(value), value);
     769
    732770                return;
    733771
     
    837875        }
    838876
     877        tinyMCE.selectedInstance = inst;
    839878        inst.switchSettings();
    840879
     
    952991        //inst.getDoc().designMode = inst.getDoc().designMode;
    953992
    954         // Setup element references
    955         var parentElm = inst.targetDoc.getElementById(inst.editorId + '_parent');
    956         inst.formElement = tinyMCE.isGecko ? parentElm.previousSibling : parentElm.nextSibling;
    957 
    958993        tinyMCE.handleVisualAid(inst.getBody(), true, tinyMCE.settings['visual'], inst);
    959994        tinyMCE.dispatchCallback(inst, 'setupcontent_callback', 'setupContent', editor_id, inst.getBody(), inst.getDoc());
     
    10161051    storeAwayURLs : function(s) {
    10171052        // Remove all mce_src, mce_href and replace them with new ones
    1018     //  s = s.replace(new RegExp('mce_src\\s*=\\s*\"[^ >\"]*\"', 'gi'), '');
    1019     //  s = s.replace(new RegExp('mce_href\\s*=\\s*\"[^ >\"]*\"', 'gi'), '');
     1053        // s = s.replace(new RegExp('mce_src\\s*=\\s*\"[^ >\"]*\"', 'gi'), '');
     1054        // s = s.replace(new RegExp('mce_href\\s*=\\s*\"[^ >\"]*\"', 'gi'), '');
    10201055
    10211056        if (!s.match(/(mce_src|mce_href)/gi, s)) {
     
    10391074    },
    10401075
     1076    removeTinyMCEFormElements : function(form_obj) {
     1077        var i, elementId;
     1078
     1079        // Skip form element removal
     1080        if (!tinyMCE.getParam('hide_selects_on_submit'))
     1081            return;
     1082
     1083        // Check if form is valid
     1084        if (typeof(form_obj) == "undefined" || form_obj == null)
     1085            return;
     1086
     1087        // If not a form, find the form
     1088        if (form_obj.nodeName != "FORM") {
     1089            if (form_obj.form)
     1090                form_obj = form_obj.form;
     1091            else
     1092                form_obj = tinyMCE.getParentElement(form_obj, "form");
     1093        }
     1094
     1095        // Still nothing
     1096        if (form_obj == null)
     1097            return;
     1098
     1099        // Disable all UI form elements that TinyMCE created
     1100        for (i=0; i<form_obj.elements.length; i++) {
     1101            elementId = form_obj.elements[i].name ? form_obj.elements[i].name : form_obj.elements[i].id;
     1102
     1103            if (elementId.indexOf('mce_editor_') == 0)
     1104                form_obj.elements[i].disabled = true;
     1105        }
     1106    },
     1107
    10411108    handleEvent : function(e) {
    10421109        var inst = tinyMCE.selectedInstance;
     
    10871154
    10881155            case "submit":
     1156                tinyMCE.removeTinyMCEFormElements(tinyMCE.isMSIE ? window.event.srcElement : e.target);
    10891157                tinyMCE.triggerSave();
    10901158                tinyMCE.isNotDirty = true;
     
    14031471        } else {
    14041472            if (tinyMCE.isRealIE)
    1405                 h += '<span id="{$editor_id}_' + id + '" class="mceMenuButton" onmouseover="tinyMCE._menuButtonEvent(\'over\',this);tinyMCE.lastHover = this;" onmouseout="tinyMCE._menuButtonEvent(\'out\',this);">';
     1473                h += '<span id="{$editor_id}_' + id + '" dir="ltr" class="mceMenuButton" onmouseover="tinyMCE._menuButtonEvent(\'over\',this);tinyMCE.lastHover = this;" onmouseout="tinyMCE._menuButtonEvent(\'out\',this);">';
    14061474            else
    1407                 h += '<span id="{$editor_id}_' + id + '" class="mceMenuButton">';
     1475                h += '<span id="{$editor_id}_' + id + '" dir="ltr" class="mceMenuButton">';
    14081476
    14091477            h += '<a href="javascript:' + cmd + '" onclick="' + cmd + 'return false;" onmousedown="return false;" class="mceMenuButtonNormal" target="_self">';
     
    14341502
    14351503    submitPatch : function() {
     1504        tinyMCE.removeTinyMCEFormElements(this);
    14361505        tinyMCE.triggerSave();
    14371506        tinyMCE.isNotDirty = true;
     
    16501719
    16511720    triggerNodeChange : function(focus, setup_content) {
     1721        var elm, inst, editorId, undoIndex = -1, undoLevels = -1, doc, anySelection = false, st;
     1722
    16521723        if (tinyMCE.selectedInstance) {
    1653             var inst = tinyMCE.selectedInstance;
    1654             var editorId = inst.editorId;
    1655             var elm = (typeof(setup_content) != "undefined" && setup_content) ? tinyMCE.selectedElement : inst.getFocusElement();
    1656             var undoIndex = -1, doc;
    1657             var undoLevels = -1;
    1658             var anySelection = false;
    1659             var selectedText = inst.selection.getSelectedText();
     1724            inst = tinyMCE.selectedInstance;
     1725            elm = (typeof(setup_content) != "undefined" && setup_content) ? tinyMCE.selectedElement : inst.getFocusElement();
     1726
     1727/*          if (elm == inst.lastTriggerEl)
     1728                return;
     1729
     1730            inst.lastTriggerEl = elm;*/
     1731
     1732            editorId = inst.editorId;
     1733            st = inst.selection.getSelectedText();
    16601734
    16611735            if (tinyMCE.settings.auto_resize)
     
    16681742
    16691743            if (tinyMCE.selectedElement)
    1670                 anySelection = (tinyMCE.selectedElement.nodeName.toLowerCase() == "img") || (selectedText && selectedText.length > 0);
     1744                anySelection = (tinyMCE.selectedElement.nodeName.toLowerCase() == "img") || (st && st.length > 0);
    16711745
    16721746            if (tinyMCE.settings['custom_undo_redo']) {
     
    17541828    openWindow : function(template, args) {
    17551829        var html, width, height, x, y, resizable, scrollbars, url;
     1830
     1831        args = !args ? {} : args;
    17561832
    17571833        args['mce_template_file'] = template['file'];
     
    21302206
    21312207    getCSSClasses : function(editor_id, doc) {
    2132         var output = new Array();
     2208        var inst = tinyMCE.getInstanceById(editor_id);
    21332209
    21342210        // Is cached, use that
    2135         if (typeof(tinyMCE.cssClasses) != "undefined")
    2136             return tinyMCE.cssClasses;
     2211        if (inst && inst.cssClasses.length > 0)
     2212            return inst.cssClasses;
    21372213
    21382214        if (typeof(editor_id) == "undefined" && typeof(doc) == "undefined") {
     
    21922268                                    var addClass = true;
    21932269
    2194                                     for (var p=0; p<output.length && addClass; p++) {
    2195                                         if (output[p] == cssClass)
     2270                                    for (var p=0; p<inst.cssClasses.length && addClass; p++) {
     2271                                        if (inst.cssClasses[p] == cssClass)
    21962272                                            addClass = false;
    21972273                                    }
    21982274
    21992275                                    if (addClass)
    2200                                         output[output.length] = cssClass;
     2276                                        inst.cssClasses[inst.cssClasses.length] = cssClass;
    22012277                                }
    22022278                            }
     
    22072283        }
    22082284
    2209         // Cache em
    2210         if (output.length > 0)
    2211             tinyMCE.cssClasses = output;
    2212 
    2213         return output;
     2285        return inst.cssClasses;
    22142286    },
    22152287
     
    22392311
    22402312    getControlHTML : function(c) {
    2241         var i, l, n, o, v;
     2313        var i, l, n, o, v, rtl = tinyMCE.getLang('lang_dir') == 'rtl';
    22422314
    22432315        l = tinyMCE.plugins;
     
    22452317            o = l[n];
    22462318
    2247             if (o.getControlHTML && (v = o.getControlHTML(c)) != '')
     2319            if (o.getControlHTML && (v = o.getControlHTML(c)) != '') {
     2320                if (rtl)
     2321                    return '<span dir="rtl">' + tinyMCE.replaceVar(v, "pluginurl", o.baseURL) + '</span>';
     2322
    22482323                return tinyMCE.replaceVar(v, "pluginurl", o.baseURL);
     2324            }
    22492325        }
    22502326
    22512327        o = tinyMCE.themes[tinyMCE.settings['theme']];
    2252         if (o.getControlHTML && (v = o.getControlHTML(c)) != '')
     2328        if (o.getControlHTML && (v = o.getControlHTML(c)) != '') {
     2329            if (rtl)
     2330                return '<span dir="rtl">' + v + '</span>';
     2331
    22532332            return v;
     2333        }
    22542334
    22552335        return '';
     
    22572337
    22582338    evalFunc : function(f, idx, a, o) {
    2259         var s = '(', i;
    2260 
    2261         for (i=idx; i<a.length; i++) {
    2262             s += 'a[' + i + ']';
    2263 
    2264             if (i < a.length-1)
    2265                 s += ',';
    2266         }
    2267 
    2268         s += ');';
    2269 
    2270         return o ? eval("o." + f + s) : eval("f" + s);
     2339        o = !o ? window : o;
     2340        f = typeof(f) == 'function' ? f : o[f];
     2341
     2342        return f.apply(o, Array.prototype.slice.call(a, idx));
    22712343    },
    22722344
     
    22902362        l = tinyMCE.getParam(p, '');
    22912363
    2292         if (l != '' && (v = tinyMCE.evalFunc(typeof(l) == "function" ? l : eval(l), 3, a)) == s && m > 0)
     2364        if (l != '' && (v = tinyMCE.evalFunc(l, 3, a)) == s && m > 0)
    22932365            return true;
    22942366
     
    23132385    },
    23142386
    2315     xmlEncode : function(s) {
    2316         return s ? ('' + s).replace(new RegExp('[<>&"\']', 'g'), function (c, b) {
     2387    xmlEncode : function(s, skip_apos) {
     2388        return s ? ('' + s).replace(!skip_apos ? this.xmlEncodeAposRe : this.xmlEncodeRe, function (c, b) {
    23172389            switch (c) {
    23182390                case '&':
     
    23912463    this.foreColor = this.backColor = "#999999";
    23922464    this.data = {};
     2465    this.cssClasses = [];
    23932466
    23942467    this.cleanup.init({
     
    23992472        entity_encoding : s.entity_encoding,
    24002473        debug : s.cleanup_debug,
    2401         url_converter : 'TinyMCE_Cleanup.prototype._urlConverter',
    24022474        indent : s.apply_source_formatting,
    24032475        invalid_elements : s.invalid_elements,
    24042476        verify_html : s.verify_html,
    2405         fix_content_duplication : s.fix_content_duplication
     2477        fix_content_duplication : s.fix_content_duplication,
     2478        convert_fonts_to_spans : s.convert_fonts_to_spans
    24062479    });
    24072480
     
    25942667
    25952668    handleShortcut : function(e) {
    2596         var i, s = this.shortcuts, o;
     2669        var i, s, o;
     2670
     2671        // Normal key press, then ignore it
     2672        if (!e.altKey && !e.ctrlKey)
     2673            return false;
     2674
     2675        s = this.shortcuts;
    25972676
    25982677        for (i=0; i<s.length; i++) {
     
    27032782        this.contentDocument = doc; // <-- Strange, unless this is applied Mozilla 1.3 breaks
    27042783
    2705         if (tinyMCE.execCommandCallback(this, 'execcommand_callback', 'execCommand', this.editorId, this.getBody(), command, user_interface, value))
    2706             return;
     2784        // Don't dispatch key commands
     2785        if (!/mceStartTyping|mceEndTyping/.test(command)) {
     2786            if (tinyMCE.execCommandCallback(this, 'execcommand_callback', 'execCommand', this.editorId, this.getBody(), command, user_interface, value))
     2787                return;
     2788        }
    27072789
    27082790        // Fix align on images
     
    28142896                    focusElm = tinyMCE.getParentElement(focusElm, 'A');
    28152897
    2816                     if (focusElm && this.getRng(0).endOffset > 0 && this.getRng(0).endOffset != focusElm.innerHTML.length)
     2898                    if (focusElm)
    28172899                        this.selection.selectNode(focusElm, false);
    28182900                }
     
    28252907
    28262908                return true;
    2827 
    2828             case "FormatBlock":
    2829                 if (!this.cleanup.isValid(value))
    2830                     return true;
    2831 
    2832                 this.getDoc().execCommand(command, user_interface, value);
    2833                 tinyMCE.triggerNodeChange();
    2834                 break;
    28352909
    28362910            case "InsertUnorderedList":
     
    28582932                        this.execCommand("mceRemoveNode", false, elm);
    28592933                } else {
     2934                    if (!this.cleanup.isValid(value))
     2935                        return true;
     2936
    28602937                    if (tinyMCE.isGecko && new RegExp('<(div|blockquote|code|dt|dd|dl|samp)>', 'gi').test(value))
    28612938                        value = value.replace(/[^a-z]/gi, '');
     
    29162993                break;
    29172994
     2995            case "mceSetStyleInfo":
    29182996            case "SetStyleInfo":
    29192997                var rng = this.getRng();
     
    32473325
    32483326            case "mceSetCSSClass":
    3249                 this.execCommand("SetStyleInfo", false, {command : "setattrib", name : "class", value : value});
     3327                this.execCommand("mceSetStyleInfo", false, {command : "setattrib", name : "class", value : value});
    32503328            break;
    32513329
     
    34793557                break;
    34803558
     3559            case "RemoveFormat":
    34813560            case "removeformat":
    34823561                var text = this.selection.getSelectedText();
     
    34953574                    }
    34963575
    3497                     this.execCommand("SetStyleInfo", false, {command : "removeformat"});
     3576                    this.execCommand("mceSetStyleInfo", false, {command : "removeformat"});
    34983577                } else {
    34993578                    this.getDoc().execCommand(command, user_interface, value);
    35003579
    3501                     this.execCommand("SetStyleInfo", false, {command : "removeformat"});
     3580                    this.execCommand("mceSetStyleInfo", false, {command : "removeformat"});
    35023581                }
    35033582
     
    36423721            } else {
    36433722                hc = '<input type="hidden" id="' + form_element_name + '" name="' + form_element_name + '" />';
     3723                this.oldTargetDisplay = tinyMCE.getStyle(this.oldTargetElement, 'display', 'inline');
    36443724                this.oldTargetElement.style.display = "none";
    36453725            }
     
    36673747            this.oldTargetElement = replace_element;
    36683748
    3669             if (!tinyMCE.settings['debug'])
     3749            if (!tinyMCE.settings['debug']) {
     3750                this.oldTargetDisplay = tinyMCE.getStyle(this.oldTargetElement, 'display', 'inline');
    36703751                this.oldTargetElement.style.display = "none";
     3752            }
    36713753
    36723754            // Output HTML and set editable
     
    37413823        if (tinyMCE.isIE)
    37423824            window.setTimeout("tinyMCE.addEventHandlers(tinyMCE.instances[\"" + this.editorId + "\"]);", 1);
     3825
     3826        // Setup element references
     3827        var parentElm = this.targetDoc.getElementById(this.editorId + '_parent');
     3828        this.formElement = tinyMCE.isGecko ? parentElm.previousSibling : parentElm.nextSibling;
    37433829
    37443830        tinyMCE.setupContent(this.editorId, true);
     
    39984084                val = tinyMCE.convertRGBToHex(val, true);
    39994085
     4086            val = val.replace(/\"/g, '\'');
     4087
    40004088            if (val != "url('')")
    40014089                str += key.toLowerCase() + ": " + val + "; ";
     
    40444132    var sizes = tinyMCE.getParam('font_size_style_values').replace(/\s+/, '').split(',');
    40454133
    4046     var h = doc.body.innerHTML;
     4134    /*var h = doc.body.innerHTML;
    40474135    h = h.replace(/<span/gi, '<font');
    40484136    h = h.replace(/<\/span/gi, '</font');
    4049     tinyMCE.setInnerHTML(doc.body, h);
    4050 
    4051     var s = doc.getElementsByTagName("font");
     4137    tinyMCE.setInnerHTML(doc.body, h);*/
     4138
     4139    var s = tinyMCE.selectElements(doc, 'span,font');
    40524140    for (var i=0; i<s.length; i++) {
    40534141        var size = tinyMCE.trim(s[i].style.fontSize).toLowerCase();
     
    40834171    var sizes = tinyMCE.getParam('font_size_style_values').replace(/\s+/, '').split(',');
    40844172
    4085     var h = doc.body.innerHTML;
     4173/*  var h = doc.body.innerHTML;
    40864174    h = h.replace(/<font/gi, '<span');
    40874175    h = h.replace(/<\/font/gi, '</span');
    4088     tinyMCE.setInnerHTML(doc.body, h);
     4176    tinyMCE.setInnerHTML(doc.body, h);*/
    40894177
    40904178    var fsClasses = tinyMCE.getParam('font_size_classes');
     
    40944182        fsClasses = null;
    40954183
    4096     var s = doc.getElementsByTagName("span");
     4184    var s = tinyMCE.selectElements(doc, 'span,font');
    40974185    for (var i=0; i<s.length; i++) {
    40984186        var fSize, fFace, fColor;
     
    41834271        n = nl[i];
    41844272
    4185         if ((p = tinyMCE.getParentElement(n, 'p,div,h1,h2,h3,h4,h5,h6')) != null) {
     4273        if ((p = tinyMCE.getParentElement(n, 'p,h1,h2,h3,h4,h5,h6')) != null) {
    41864274            np = p.cloneNode(false);
    41874275            np.removeAttribute('id');
     
    43814469        this.fillStr = s.entity_encoding == "named" ? "&nbsp;" : "&#160;";
    43824470        this.idCount = 0;
     4471        this.xmlEncodeRe = new RegExp('[\u007F-\uFFFF<>&"]', 'g');
     4472        this.xmlEncodeAposRe = new RegExp('[\u007F-\uFFFF<>&"\']', 'g');
    43834473    },
    43844474
     
    44044494    isValid : function(n) {
    44054495        this._setupRules(); // Will initialize cleanup rules
     4496
     4497        // Empty is true since it removes formatting
     4498        if (!n)
     4499            return true;
    44064500
    44074501        // Clean the name up a bit
     
    46074701        var xd, el, i, l, cn, at, no, hc = false;
    46084702
    4609         if (this._isDuplicate(n))
     4703        if (tinyMCE.isRealIE && this._isDuplicate(n))
    46104704            return;
    46114705
     
    46504744
    46514745    serializeNodeAsHTML : function(n, inn) {
    4652         var en, no, h = '', i, l, t, st, r, cn, va = false, f = false, at, hc, cr;
     4746        var en, no, h = '', i, l, t, st, r, cn, va = false, f = false, at, hc, cr, nn;
    46534747
    46544748        this._setupRules(); // Will initialize cleanup rules
    46554749
    4656         if (this._isDuplicate(n))
     4750        if (tinyMCE.isRealIE && this._isDuplicate(n))
    46574751            return '';
    46584752
     
    46784772                    break;
    46794773
    4680                 if (this.vElementsRe.test(n.nodeName) && (!this.iveRe || !this.iveRe.test(n.nodeName)) && !inn) {
     4774                nn = n.nodeName;
     4775
     4776                // Convert fonts to spans
     4777                if (this.settings.convert_fonts_to_spans) {
     4778                    // On get content FONT -> SPAN
     4779                    if (this.settings.on_save && nn == 'FONT')
     4780                        nn = 'SPAN';
     4781
     4782                    // On insert content SPAN -> FONT
     4783                    if (!this.settings.on_save && nn == 'SPAN')
     4784                        nn = 'FONT';
     4785                }
     4786
     4787                if (this.vElementsRe.test(nn) && (!this.iveRe || !this.iveRe.test(nn)) && !inn) {
    46814788                    va = true;
    46824789
    4683                     r = this.rules[n.nodeName];
     4790                    r = this.rules[nn];
    46844791                    if (!r) {
    46854792                        at = this.rules;
    46864793                        for (no in at) {
    4687                             if (at[no] && at[no].validRe.test(n.nodeName)) {
     4794                            if (at[no] && at[no].validRe.test(nn)) {
    46884795                                r = at[no];
    46894796                                break;
     
    46924799                    }
    46934800
    4694                     en = r.isWild ? n.nodeName.toLowerCase() : r.oTagName;
     4801                    en = r.isWild ? nn.toLowerCase() : r.oTagName;
    46954802                    f = r.fill;
    46964803
     
    47294836
    47304837                    // Close these
    4731                     if (t != null && this.closeElementsRe.test(n.nodeName))
     4838                    if (t != null && this.closeElementsRe.test(nn))
    47324839                        return t + ' />';
    47334840
     
    47354842                        h += t + '>';
    47364843
    4737                     if (this.isIE && this.codeElementsRe.test(n.nodeName))
     4844                    if (this.isIE && this.codeElementsRe.test(nn))
    47384845                        h += n.innerHTML;
    47394846                }
     
    47964903            av = t;
    47974904
    4798         if (os && av.length != 0 && this.settings.url_converter.length != 0 && /^(src|href|longdesc)$/.test(an))
    4799             av = eval(this.settings.url_converter + '(this, n, av)');
     4905        if (os && av.length != 0 && /^(src|href|longdesc)$/.test(an))
     4906            av = this._urlConverter(this, n, av);
    48004907
    48014908        if (av.length != 0 && r.validAttribValues && r.validAttribValues[an] && !r.validAttribValues[an].test(av))
     
    48074914        if (av.length != 0) {
    48084915            if (an.indexOf('on') != 0)
    4809                 av = this.xmlEncode(av);
     4916                av = this.xmlEncode(av, 1);
    48104917
    48114918            return " " + an + "=" + '"' + av + '"';
     
    48534960    },
    48544961
    4855     xmlEncode : function(s) {
    4856         var cl = this;
     4962    xmlEncode : function(s, skip_apos) {
     4963        var cl = this, re = !skip_apos ? this.xmlEncodeAposRe : this.xmlEncodeRe;
    48574964
    48584965        this._setupEntities(); // Will intialize lookup table
     
    48604967        switch (this.settings.entity_encoding) {
    48614968            case "raw":
    4862                 return tinyMCE.xmlEncode(s);
     4969                return tinyMCE.xmlEncode(s, skip_apos);
    48634970
    48644971            case "named":
    4865                 return s.replace(new RegExp('[\u007F-\uFFFF<>&"\']', 'g'), function (c, b) {
     4972                return s.replace(re, function (c, b) {
    48664973                    b = cl.entities[c.charCodeAt(0)];
    48674974
     
    48704977
    48714978            case "numeric":
    4872                 return s.replace(new RegExp('[\u007F-\uFFFF<>&"\']', 'g'), function (c, b) {
     4979                return s.replace(re, function (c, b) {
    48734980                    return b ? '&#' + c.charCodeAt(0) + ';' : c;
    48744981                });
     
    48995006
    49005007    _getAttrib : function(e, n, d) {
     5008        var v, ex, nn;
     5009
    49015010        if (typeof(d) == "undefined")
    49025011            d = "";
     
    49055014            return d;
    49065015
    4907         var v = e.getAttribute(n, 0);
     5016        try {
     5017            v = e.getAttribute(n, 0);
     5018        } catch (ex) {
     5019            // IE 7 may cast exception on invalid attributes
     5020            v = e.getAttribute(n, 2);
     5021        }
    49085022
    49095023        if (n == "class" && !v)
    49105024            v = e.className;
    49115025
    4912         if (this.isIE && n == "http-equiv")
    4913             v = e.httpEquiv;
    4914 
    4915         if (this.isIE && e.nodeName == "FORM" && n == "enctype" && v == "application/x-www-form-urlencoded")
    4916             v = "";
    4917 
    4918         if (this.isIE && e.nodeName == "INPUT" && n == "size" && v == "20")
    4919             v = "";
    4920 
    4921         if (this.isIE && e.nodeName == "INPUT" && n == "maxlength" && v == "2147483647")
    4922             v = "";
    4923 
    4924         if (n == "style" && !tinyMCE.isOpera)
    4925             v = e.style.cssText;
    4926 
    4927         if (n == 'style')
     5026        if (this.isIE) {
     5027            if (n == "http-equiv")
     5028                v = e.httpEquiv;
     5029
     5030            nn = e.nodeName;
     5031
     5032            // Skip the default values that IE returns
     5033            if (nn == "FORM" && n == "enctype" && v == "application/x-www-form-urlencoded")
     5034                v = "";
     5035
     5036            if (nn == "INPUT" && n == "size" && v == "20")
     5037                v = "";
     5038
     5039            if (nn == "INPUT" && n == "maxlength" && v == "2147483647")
     5040                v = "";
     5041        }
     5042
     5043        if (n == 'style' && v) {
     5044            if (!tinyMCE.isOpera)
     5045                v = e.style.cssText;
     5046
    49285047            v = tinyMCE.serializeStyle(tinyMCE.parseStyle(v));
     5048        }
    49295049
    49305050        if (this.settings.on_save && n.indexOf('on') != -1 && this.settings.on_save && v && v != "")
     
    49375057        if (!c.settings.on_save)
    49385058            return tinyMCE.convertRelativeToAbsoluteURL(tinyMCE.settings.base_href, v);
    4939         else if (tinyMCE.getParam('convert_urls'))
    4940             return eval(tinyMCE.settings.urlconverter_callback + "(v, n, true);");
     5059        else if (tinyMCE.getParam('convert_urls')) {
     5060            if (!this.urlConverter)
     5061                this.urlConverter = eval(tinyMCE.settings.urlconverter_callback);
     5062
     5063            return this.urlConverter(v, n, true);
     5064        }
    49415065
    49425066        return v;
     
    51005224    // Convert all strong/em to b/i in Gecko
    51015225    if (tinyMCE.isGecko) {
    5102         h = h.replace(/<strong/gi, '<b');
    5103         h = h.replace(/<em(\/?)/gi, '<i');
    5104         h = h.replace(/<em /gi, '<i');
     5226        h = h.replace(/<embed([^>]*)>/gi, '<tmpembed$1>');
     5227        h = h.replace(/<em([^>]*)>/gi, '<i$1>');
     5228        h = h.replace(/<tmpembed([^>]*)>/gi, '<embed$1>');
     5229        h = h.replace(/<strong([^>]*)>/gi, '<b$1>');
    51055230        h = h.replace(/<\/strong>/gi, '</b>');
    51065231        h = h.replace(/<\/em>/gi, '</i>');
     
    52265351        return dv;
    52275352
    5228     v = elm.getAttribute(name);
     5353    try {
     5354        v = elm.getAttribute(name, 0);
     5355    } catch (ex) {
     5356        // IE 7 may cast exception on invalid attributes
     5357        v = elm.getAttribute(name, 2);
     5358    }
    52295359
    52305360    // Try className for class attrib
     
    54105540        height : w.innerHeight || (m ? de.clientHeight : b.clientHeight)
    54115541    };
     5542};
     5543
     5544TinyMCE_Engine.prototype.getStyle = function(n, na, d) {
     5545    if (!n)
     5546        return false;
     5547
     5548    // Gecko
     5549    if (tinyMCE.isGecko && n.ownerDocument.defaultView) {
     5550        try {
     5551            return n.ownerDocument.defaultView.getComputedStyle(n, null).getPropertyValue(na);
     5552        } catch (n) {
     5553            // Old safari might fail
     5554            return null;
     5555        }
     5556    }
     5557
     5558    // Camelcase it, if needed
     5559    na = na.replace(/-(\D)/g, function(a, b){
     5560        return b.toUpperCase();
     5561    });
     5562
     5563    // IE & Opera
     5564    if (n.currentStyle)
     5565        return n.currentStyle[na];
     5566
     5567    return false;
    54125568};
    54135569
     
    58776033            f(doc, ot[i], tinyMCE.handleEvent);
    58786034
    5879         eval('try { doc.designMode = "On"; } catch(e) {}'); // Force designmode
     6035        // Force designmode
     6036        try {
     6037            doc.designMode = "On";
     6038        } catch (e) {
     6039            // Ignore
     6040        }
    58806041    }
    58816042};
     
    60486209
    60496210        // When editing always use fonts internaly
    6050         if (tinyMCE.getParam("convert_fonts_to_spans"))
    6051             tinyMCE.convertSpansToFonts(inst.getDoc());
     6211        //if (tinyMCE.getParam("convert_fonts_to_spans"))
     6212        //  tinyMCE.convertSpansToFonts(inst.getDoc());
    60526213
    60536214        return h;
     
    62526413
    62536414        if (tinyMCE.isGecko || tinyMCE.isOpera) {
     6415            if (!sel)
     6416                return false;
     6417
    62546418            if (bookmark.rng) {
    62556419                sel.removeAllRanges();
     
    64636627            return '' + window.getSelection();
    64646628
    6465         return s.getRangeAt(0);
     6629        if (s.rangeCount > 0)
     6630            return s.getRangeAt(0);
     6631
     6632        return null;
     6633    },
     6634
     6635    isCollapsed : function() {
     6636        var r = this.getRng();
     6637
     6638        if (r.item)
     6639            return false;
     6640
     6641        return r.boundingWidth == 0 || this.getSel().isCollapsed;
     6642    },
     6643
     6644    collapse : function(b) {
     6645        var r = this.getRng(), s = this.getSel();
     6646
     6647        if (r.select) {
     6648            r.collapse(b);
     6649            r.select();
     6650        } else {
     6651            if (b)
     6652                s.collapseToStart();
     6653            else
     6654                s.collapseToEnd();
     6655        }
    64666656    },
    64676657
     
    70077197
    70087198    show : function() {
    7009         this.getElement().style.display = 'block';
    7010         this.updateBlocker();
     7199        var el = this.getElement();
     7200
     7201        if (el) {
     7202            el.style.display = 'block';
     7203            this.updateBlocker();
     7204        }
    70117205    },
    70127206
    70137207    hide : function() {
    7014         this.getElement().style.display = 'none';
    7015         this.updateBlocker();
     7208        var el = this.getElement();
     7209
     7210        if (el) {
     7211            el.style.display = 'none';
     7212            this.updateBlocker();
     7213        }
    70167214    },
    70177215
     
    71187316
    71197317        return parseInt(s);
     7318    },
     7319
     7320    remove : function() {
     7321        var e = this.getElement(), b = this.getBlocker();
     7322
     7323        if (e)
     7324            e.parentNode.removeChild(e);
     7325
     7326        if (b)
     7327            b.parentNode.removeChild(b);
    71207328    }
    71217329
     
    72097417
    72107418                default:
    7211                     h += '<tr><td><a href="#" onclick="return tinyMCE.cancelEvent(event);" onmousedown="return tinyMCE.cancelEvent(event);" onmouseup="' + tinyMCE.xmlEncode(m[i].js) + ';return tinyMCE.cancelEvent(event);"><span' + c +'>' + t + '</span></a>';
     7419                    h += '<tr><td><a href="' + tinyMCE.xmlEncode(m[i].js) + '" onmousedown="' + tinyMCE.xmlEncode(m[i].js) + ';return tinyMCE.cancelEvent(event);" onclick="return tinyMCE.cancelEvent(event);" onmouseup="return tinyMCE.cancelEvent(event);"><span' + c +'>' + t + '</span></a>';
    72127420            }
    72137421
  • tags/2.2/wp-includes/js/tinymce/tiny_mce_config.php

    r5468 r5480  
    4141    $mce_browsers = apply_filters('mce_browsers', array('msie', 'gecko', 'opera', 'safari'));
    4242    $mce_browsers = implode($mce_browsers, ',');
    43    
     43
    4444    $mce_popups_css = get_option('siteurl') . '/wp-includes/js/tinymce/plugins/wordpress/popups.css';
    4545    $mce_css = get_option('siteurl') . '/wp-includes/js/tinymce/plugins/wordpress/wordpress.css';
     
    4949        $mce_popups_css = str_replace('http://', 'https://', $mce_popups_css);
    5050    }
     51   
     52    $mce_locale = ( '' == get_locale() ) ? 'en' : strtolower(get_locale());
    5153?>
    5254
     
    5961    theme_advanced_buttons2 : "<?php echo $mce_buttons_2; ?>",
    6062    theme_advanced_buttons3 : "<?php echo $mce_buttons_3; ?>",
    61     language : "<?php echo strtolower(get_locale()); ?>",
     63    language : "<?php echo $mce_locale; ?>",
    6264    theme_advanced_toolbar_location : "top",
    6365    theme_advanced_toolbar_align : "left",
     
    7779    gecko_spellcheck : true,
    7880    entities : "38,amp,60,lt,62,gt",
     81    button_tile_map : true,
    7982    content_css : "<?php echo $mce_css; ?>",
    8083    valid_elements : "<?php echo $valid_elements; ?>",
  • tags/2.2/wp-includes/js/tinymce/tiny_mce_gzip.php

    r5468 r5480  
    11<?php
    22/**
    3  * $RCSfile: tiny_mce_gzip.php,v $
    4  * $Revision: $
    5  * $Date: $
     3 * $Id: tiny_mce_gzip.php 158 2006-12-21 14:32:19Z spocke $
    64 *
    7  * @version 1.08
    85 * @author Moxiecode
    96 * @copyright Copyright  2005-2006, Moxiecode Systems AB, All rights reserved.
     
    1411 */
    1512
    16 @require_once('../../../wp-config.php');
    17 
    18 // gzip_compression();
    19 
    20 function wp_tinymce_lang($path) {
    21     global $language;
    22 
    23     $text = '';
    24 
    25     // Look for xx_YY.js, xx_yy.js, xx.js
    26     $file = realpath(sprintf($path, $language));
    27     if ( file_exists($file) )
    28         $text = file_get_contents($file);
    29     $file = realpath(sprintf($path, strtolower($language)));
    30     if ( file_exists($file) )
    31         $text = file_get_contents($file);
    32     $file = realpath(sprintf($path, substr($language, 0, 2)));
    33     if ( file_exists($file) )
    34         $text = file_get_contents($file);
    35 
    36 
    37     // Fall back on en.js
    38     $file = realpath(sprintf($path, 'en'));
    39     if ( empty($text) && file_exists($file) )
    40         $text = file_get_contents($file);
    41 
    42     // Send lang file through gettext
    43     if ( function_exists('__') && strtolower(substr($language, 0, 2)) != 'en' ) {
    44         $search1 = "/^tinyMCELang\\[(['\"])(.*)\\1\]( ?= ?)(['\"])(.*)\\4/Uem";
    45         $replace1 = "'tinyMCELang[\\1\\2\\1]\\3'.stripslashes('\\4').__('\\5').stripslashes('\\4')";
    46 
    47         $search2 = "/\\s:\\s(['\"])(.*)\\1(,|\\s*})/Uem";
    48         $replace2 = "' : '.stripslashes('\\1').__('\\2').stripslashes('\\1').'\\3'";
    49 
    50         $search = array($search1, $search2);
    51         $replace = array($replace1, $replace2);
    52 
    53         $text = preg_replace($search, $replace, $text);
    54 
    55         return $text;
    56     }
    57 
    58     return $text;
    59 }
    60 
    61 function wp_compact_tinymce_js($text) {
    62     // This function was custom-made for TinyMCE 2.0, not expected to work with any other JS.
    63 
    64     // Strip comments
    65     $text = preg_replace("!(^|\s+)//.*$!m", '', $text);
    66     $text = preg_replace("!/\*.*?\*/!s", '', $text);
    67 
    68     // Strip leading tabs, carriage returns and unnecessary line breaks.
    69     $text = preg_replace("!^\t+!m", '', $text);
    70     $text = str_replace("\r", '', $text);
    71     $text = preg_replace("!(^|{|}|;|:|\))\n!m", '\\1', $text);
    72 
    73     return "$text\n";
    74 }
    75 
    76 
    77 // General options
    78 $suffix = "";                           // Set to "_src" to use source version
    79 $expiresOffset = 3600 * 24 * 10;        // 10 days util client cache expires
    80 $diskCache = false;                     // If you enable this option gzip files will be cached on disk.
    81 $cacheDir = realpath(".");              // Absolute directory path to where cached gz files will be stored
    82 $debug = false;                         // Enable this option if you need debuging info
    83 
    84 // Headers
    85 header("Content-Type: text/javascript; charset=" . get_bloginfo('charset'));
    86 // header("Cache-Control: must-revalidate");
    87 header("Vary: Accept-Encoding"); // Handle proxies
    88 header("Expires: " . gmdate("D, d M Y H:i:s", time() + $expiresOffset) . " GMT");
    89 
    90 // Get data to load
    91 $theme = isset($_GET['theme']) ? TinyMCE_cleanInput($_GET['theme']) : "";
    92 $language = isset($_GET['language']) ? TinyMCE_cleanInput($_GET['language']) : "";
    93 $plugins = isset($_GET['plugins']) ? TinyMCE_cleanInput($_GET['plugins']) : "";
    94 $lang = isset($_GET['lang']) ? TinyMCE_cleanInput($_GET['lang']) : "en";
    95 $index = isset($_GET['index']) ? TinyMCE_cleanInput($_GET['index']) : -1;
    96 $cacheKey = md5($theme . $language . $plugins . $lang . $index . $debug);
    97 $cacheFile = $cacheDir == "" ? "" : $cacheDir . "/" . "tinymce_" .  $cacheKey . ".gz";
    98 $cacheData = "";
    99 
    100 // Patch older versions of PHP < 4.3.0
    101 if (!function_exists('file_get_contents')) {
    102     function file_get_contents($filename) {
    103         $fd = fopen($filename, 'rb');
    104         $content = fread($fd, filesize($filename));
    105         fclose($fd);
    106         return $content;
    107     }
    108 }
    109 
    110 // Security check function, can only contain a-z 0-9 , _ - and whitespace.
    111 function TinyMCE_cleanInput($str) {
    112     return preg_replace("/[^0-9a-z\-_,]+/i", "", $str); // Remove anything but 0-9,a-z,-_
    113 }
    114 
    115 function TinyMCE_echo($str) {
    116     global $cacheData, $diskCache;
    117 
    118     if ($diskCache)
    119         $cacheData .= $str;
    120     else
    121         echo $str;
    122 }
    123 
    124 // Only gzip the contents if clients and server support it
    125 $encodings = array();
    126 
    127 if (isset($_SERVER['HTTP_ACCEPT_ENCODING']))
    128     $encodings = explode(',', strtolower(preg_replace("/\s+/", "", $_SERVER['HTTP_ACCEPT_ENCODING'])));
    129 
    130 // Check for gzip header or northon internet securities
    131 if ((in_array('gzip', $encodings) || in_array('x-gzip', $encodings) || isset($_SERVER['---------------'])) && function_exists('ob_gzhandler') && !ini_get('zlib.output_compression')) {
    132     $enc = in_array('x-gzip', $encodings) ? "x-gzip" : "gzip";
    133 
    134     // Use cached file if it exists but not in debug mode
    135     if (file_exists($cacheFile) && !$debug) {
    136         header("Content-Encoding: " . $enc);
    137         echo file_get_contents($cacheFile);
    138         die;
    139     }
    140 
    141     if (!$diskCache)
    142         ob_start("ob_gzhandler");
    143 } else
     13    @require_once('../../../wp-config.php');  // For get_bloginfo().
     14
     15    // Get input
     16    $plugins = explode(',', getParam("plugins", ""));
     17    $languages = explode(',', getParam("languages", ""));
     18    $themes = explode(',', getParam("themes", ""));
     19    $diskCache = getParam("diskcache", "") == "true";
     20    $isJS = getParam("js", "") == "true";
     21    $compress = getParam("compress", "true") == "true";
     22    $suffix = getParam("suffix", "_src") == "_src" ? "_src" : "";
     23    $cachePath = realpath("."); // Cache path, this is where the .gz files will be stored
     24    $expiresOffset = 3600 * 24 * 10; // Cache for 10 days in browser cache
     25    $content = "";
     26    $encodings = array();
     27    $supportsGzip = false;
     28    $enc = "";
     29    $cacheKey = "";
     30
     31    // Custom extra javascripts to pack
     32    $custom = array(/*
     33        "some custom .js file",
     34        "some custom .js file"
     35    */);
     36
     37    // WP
     38    $index = getParam("index", -1);
     39    $theme = getParam("theme", "");
     40    $themes = array($theme);
     41    $language = getParam("language", "en");
     42    if ( empty($language) )
     43        $language = 'en';
     44    $languages = array($language);
     45    if ( $language != strtolower($language) )
     46        $languages[] = strtolower($language);
     47    if ( $language != substr($language, 0, 2) )
     48        $languages[] = substr($language, 0, 2);
    14449    $diskCache = false;
     50    $isJS = true;
     51    $suffix = '';
     52
     53    // Headers
     54    header("Content-Type: text/javascript; charset=" . get_bloginfo('charset'));
     55    header("Vary: Accept-Encoding");  // Handle proxies
     56    header("Expires: " . gmdate("D, d M Y H:i:s", time() + $expiresOffset) . " GMT");
     57
     58    // Is called directly then auto init with default settings
     59    if (!$isJS) {
     60        echo getFileContents("tiny_mce_gzip.js");
     61        echo "tinyMCE_GZ.init({});";
     62        die();
     63    }
     64
     65    // Setup cache info
     66    if ($diskCache) {
     67        if (!$cachePath)
     68            die("alert('Real path failed.');");
     69
     70        $cacheKey = getParam("plugins", "") . getParam("languages", "") . getParam("themes", "");
     71
     72        foreach ($custom as $file)
     73            $cacheKey .= $file;
     74
     75        $cacheKey = md5($cacheKey);
     76
     77        if ($compress)
     78            $cacheFile = $cachePath . "/tiny_mce_" . $cacheKey . ".gz";
     79        else
     80            $cacheFile = $cachePath . "/tiny_mce_" . $cacheKey . ".js";
     81    }
     82
     83    // Check if it supports gzip
     84    if (isset($_SERVER['HTTP_ACCEPT_ENCODING']))
     85        $encodings = explode(',', strtolower(preg_replace("/\s+/", "", $_SERVER['HTTP_ACCEPT_ENCODING'])));
     86
     87    if ((in_array('gzip', $encodings) || in_array('x-gzip', $encodings) || isset($_SERVER['---------------'])) && function_exists('ob_gzhandler') && !ini_get('zlib.output_compression') && ini_get('output_handler') != 'ob_gzhandler') {
     88        $enc = in_array('x-gzip', $encodings) ? "x-gzip" : "gzip";
     89        $supportsGzip = true;
     90    }
     91
     92    // Use cached file disk cache
     93    if ($diskCache && $supportsGzip && file_exists($cacheFile)) {
     94        if ($compress)
     95            header("Content-Encoding: " . $enc);
     96
     97        echo getFileContents($cacheFile);
     98        die();
     99    }
    145100
    146101if ($index > -1) {
    147102    // Write main script and patch some things
    148     if ($index == 0) {
    149         TinyMCE_echo(wp_compact_tinymce_js(file_get_contents(realpath("tiny_mce" . $suffix . ".js")))); // WP
    150         TinyMCE_echo('TinyMCE.prototype.orgLoadScript = TinyMCE.prototype.loadScript;');
    151         TinyMCE_echo('TinyMCE.prototype.loadScript = function() {};var realTinyMCE = tinyMCE;');
     103    if ( $index == 0 ) {
     104        // Add core
     105        $content .= wp_compact_tinymce_js(getFileContents("tiny_mce" . $suffix . ".js"));
     106        $content .= 'TinyMCE.prototype.orgLoadScript = TinyMCE.prototype.loadScript;';
     107        $content .= 'TinyMCE.prototype.loadScript = function() {};var realTinyMCE = tinyMCE;';
    152108    } else
    153         TinyMCE_echo('tinyMCE = realTinyMCE;');
    154 
     109        $content .= 'tinyMCE = realTinyMCE;';
     110
     111    // Patch loading functions
     112    //$content .= "tinyMCE_GZ.start();";
     113   
    155114    // Do init based on index
    156     TinyMCE_echo("tinyMCE.init(tinyMCECompressed.configs[" . $index . "]);");
     115    $content .= "tinyMCE.init(tinyMCECompressed.configs[" . $index . "]);";
    157116
    158117    // Load external plugins
    159     if ($index == 0)
    160         TinyMCE_echo("tinyMCECompressed.loadPlugins();");
    161 
    162     // Load theme, language pack and theme language packs
    163     if ($theme) {
    164         TinyMCE_echo(wp_compact_tinymce_js(file_get_contents(realpath("themes/" . $theme . "/editor_template" . $suffix . ".js")))); // WP
    165         TinyMCE_echo(wp_tinymce_lang("themes/" . $theme . "/langs/%s.js")); // WP
    166     }
    167 
    168     /* WP if ($language) WP */
    169         TinyMCE_echo(wp_tinymce_lang("langs/%s.js")); // WP
    170 
    171     // Load all plugins and their language packs
    172     $plugins = explode(",", $plugins);
     118    if ( $index == 0 )
     119        $content .= "tinyMCECompressed.loadPlugins();";
     120
     121    // Add core languages
     122    $lang_content = '';
     123    foreach ($languages as $lang)
     124        $lang_content .= getFileContents("langs/" . $lang . ".js");
     125    if ( empty($lang_content) )
     126        $lang_content .= getFileContents("langs/en.js");
     127    $content .= $lang_content;
     128
     129    // Add themes
     130    foreach ($themes as $theme) {
     131        $content .= wp_compact_tinymce_js(getFileContents( "themes/" . $theme . "/editor_template" . $suffix . ".js"));
     132
     133        $lang_content = '';
     134        foreach ($languages as $lang)
     135            $lang_content .= getFileContents("themes/" . $theme . "/langs/" . $lang . ".js");
     136        if ( empty($lang_content) )
     137            $lang_content .= getFileContents("themes/" . $theme . "/langs/en.js");
     138        $content .= $lang_content;
     139    }
     140
     141    // Add plugins
    173142    foreach ($plugins as $plugin) {
    174         $pluginFile = realpath("plugins/" . $plugin . "/editor_plugin" . $suffix . ".js");
    175         /* WP $languageFile = realpath("plugins/" . $plugin . "/langs/" . $lang . ".js"); WP */
    176 
    177         if ($pluginFile)
    178             TinyMCE_echo(file_get_contents($pluginFile));
    179 
    180         /* WP if ($languageFile) WP */
    181             TinyMCE_echo(wp_tinymce_lang("plugins/" . $plugin . "/langs/%s.js")); // WP
    182     }
     143        $content .= getFileContents("plugins/" . $plugin . "/editor_plugin" . $suffix . ".js");
     144
     145        $lang_content = '';
     146        foreach ($languages as $lang)
     147            $lang_content .= getFileContents("plugins/" . $plugin . "/langs/" . $lang . ".js");
     148        if ( empty($lang_content) )
     149            $lang_content .= getFileContents("plugins/" . $plugin . "/langs/en.js");
     150        $content .= $lang_content;
     151    }
     152
     153    // Add custom files
     154    foreach ($custom as $file)
     155        $content .= getFileContents($file);
    183156
    184157    // Reset tinyMCE compressor engine
    185     TinyMCE_echo("tinyMCE = tinyMCECompressed;");
    186 
    187     // Write to cache
    188     if ($diskCache) {
    189         // Calculate compression ratio and debug target output path
    190         if ($debug) {
    191             $ratio = round(100 - strlen(gzencode($cacheData, 9, FORCE_GZIP)) / strlen($cacheData) * 100.0);
    192             TinyMCE_echo("alert('TinyMCE was compressed by " . $ratio . "%.\\nOutput cache file: " . $cacheFile . "');");
    193         }
    194 
    195         $cacheData = gzencode($cacheData, 9, FORCE_GZIP);
    196 
    197         // Write to file if possible
    198         $fp = @fopen($cacheFile, "wb");
     158    $content .= "tinyMCE = tinyMCECompressed;";
     159
     160    // Restore loading functions
     161    //$content .= "tinyMCE_GZ.end();";
     162
     163    // Generate GZIP'd content
     164    if ($supportsGzip) {
     165        if ($compress) {
     166            header("Content-Encoding: " . $enc);
     167            $cacheData = gzencode($content, 9, FORCE_GZIP);
     168        } else
     169            $cacheData = $content;
     170
     171        // Write gz file
     172        if ($diskCache && $cacheKey != "")
     173            putFileContents($cacheFile, $cacheData);
     174
     175        // Stream to client
     176        echo $cacheData;
     177    } else {
     178        // Stream uncompressed content
     179        echo $content;
     180    }
     181
     182    die;
     183}
     184
     185    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
     186
     187    function getParam($name, $def = false) {
     188        if (!isset($_GET[$name]))
     189            return $def;
     190
     191        return preg_replace("/[^0-9a-z\-_,]+/i", "", $_GET[$name]); // Remove anything but 0-9,a-z,-_
     192    }
     193
     194    function getFileContents($path) {
     195        $path = realpath($path);
     196
     197        if (!$path || !@is_file($path))
     198            return "";
     199
     200        if (function_exists("file_get_contents"))
     201            return @file_get_contents($path);
     202
     203        $content = "";
     204        $fp = @fopen($path, "r");
     205        if (!$fp)
     206            return "";
     207
     208        while (!feof($fp))
     209            $content .= fgets($fp);
     210
     211        fclose($fp);
     212
     213        return $content;
     214    }
     215
     216    function putFileContents($path, $content) {
     217        if (function_exists("file_put_contents"))
     218            return @file_put_contents($path, $content);
     219
     220        $fp = @fopen($path, "wb");
    199221        if ($fp) {
    200             fwrite($fp, $cacheData);
     222            fwrite($fp, $content);
    201223            fclose($fp);
    202224        }
    203 
    204         // Output
    205         header("Content-Encoding: " . $enc);
    206         echo $cacheData;
    207     }
    208 
    209     die;
    210 }
     225    }
     226
     227    // WP specific
     228    function wp_compact_tinymce_js($text) {
     229        // This function was custom-made for TinyMCE 2.0, not expected to work with any other JS.
     230
     231        // Strip comments
     232        $text = preg_replace("!(^|\s+)//.*$!m", '', $text);
     233        $text = preg_replace("!/\*.*?\*/!s", '', $text);
     234
     235        // Strip leading tabs, carriage returns and unnecessary line breaks.
     236        $text = preg_replace("!^\t+!m", '', $text);
     237        $text = str_replace("\r", '', $text);
     238        $text = preg_replace("!(^|{|}|;|:|\))\n!m", '\\1', $text);
     239
     240        return "$text\n";
     241    }
    211242?>
    212243
  • tags/2.2/wp-includes/js/tinymce/utils/form_utils.js

    r5468 r5480  
    11/**
    2  * $Id: form_utils.js 43 2006-08-08 16:10:07Z spocke $
     2 * $Id: form_utils.js 162 2007-01-03 16:16:52Z spocke $
    33 *
    44 * Various form utilitiy functions.
    55 *
    66 * @author Moxiecode
    7  * @copyright Copyright © 2004-2006, Moxiecode Systems AB, All rights reserved.
     7 * @copyright Copyright © 2004-2007, Moxiecode Systems AB, All rights reserved.
    88 */
    99
  • tags/2.2/wp-includes/js/tinymce/utils/mclayer.js

    r5468 r5480  
    11/**
    2  * $Id: mclayer.js 18 2006-06-29 14:11:23Z spocke $
     2 * $Id: mclayer.js 162 2007-01-03 16:16:52Z spocke $
    33 *
    44 * Moxiecode floating layer script.
    55 *
    66 * @author Moxiecode
    7  * @copyright Copyright © 2004-2006, Moxiecode Systems AB, All rights reserved.
     7 * @copyright Copyright © 2004-2007, Moxiecode Systems AB, All rights reserved.
    88 */
    99
  • tags/2.2/wp-includes/js/tinymce/utils/mctabs.js

    r5468 r5480  
    11/**
    2  * $Id: mctabs.js 18 2006-06-29 14:11:23Z spocke $
     2 * $Id: mctabs.js 162 2007-01-03 16:16:52Z spocke $
    33 *
    44 * Moxiecode DHTML Tabs script.
    55 *
    66 * @author Moxiecode
    7  * @copyright Copyright © 2004-2006, Moxiecode Systems AB, All rights reserved.
     7 * @copyright Copyright © 2004-2007, Moxiecode Systems AB, All rights reserved.
    88 */
    99
  • tags/2.2/wp-includes/js/tinymce/utils/validate.js

    r5468 r5480  
    11/**
    2  * $Id: validate.js 65 2006-08-24 15:54:55Z spocke $
     2 * $Id: validate.js 162 2007-01-03 16:16:52Z spocke $
    33 *
    44 * Various form validation methods.
    55 *
    66 * @author Moxiecode
    7  * @copyright Copyright © 2004-2006, Moxiecode Systems AB, All rights reserved.
     7 * @copyright Copyright © 2004-2007, Moxiecode Systems AB, All rights reserved.
    88 */
    99
  • tags/2.2/wp-includes/js/tinymce/wp-mce-help.php

    r5468 r5480  
    167167<div id="content4" class="hidden">
    168168    <h2><?php _e('About TinyMCE'); ?></h2>
    169     <p><?php printf(__('Version: %s'), '2.0.8') ?></p>
    170     <p><?php printf(__('TinyMCE is a platform independent web based Javascript HTML WYSIWYG editor control released as Open Source under %sLGPL</a> by Moxiecode Systems AB. It has the ability to convert HTML TEXTAREA fields or other HTML elements to editor instances.'), '<a href="'.get_bloginfo('home').'/wp-includes/js/tinymce/license.txt" target="_blank" title="'.__('GNU Library General Public Licence').'">') ?></p>
     169    <p><?php printf(__('Version: %s'), '2.0.9') ?></p>
     170    <p><?php printf(__('TinyMCE is a platform independent web based Javascript HTML WYSIWYG editor control released as Open Source under %sLGPL</a> by Moxiecode Systems AB. It has the ability to convert HTML TEXTAREA fields or other HTML elements to editor instances.'), '<a href="'.get_bloginfo('url').'/wp-includes/js/tinymce/license.txt" target="_blank" title="'.__('GNU Library General Public Licence').'">') ?></p>
    171171    <p><?php _e('Copyright &copy; 2005, <a href="http://www.moxiecode.com" target="_blank">Moxiecode Systems AB</a>, All rights reserved.') ?></p>
    172172    <p><?php _e('For more information about this software visit the <a href="http://tinymce.moxiecode.com" target="_blank">TinyMCE website</a>.') ?></p>
  • tags/2.2/wp-includes/l10n.php

    r5468 r5480  
    1818}
    1919
    20 // Return a translated string.
    21 function __($text, $domain = 'default') {
     20function translate($text, $domain) {
    2221    global $l10n;
    2322
     
    2827}
    2928
     29// Return a translated string.
     30function __($text, $domain = 'default') {
     31    return translate($text, $domain);
     32}
     33
    3034// Echo a translated string.
    3135function _e($text, $domain = 'default') {
    32     global $l10n;
     36    echo translate($text, $domain);
     37}
    3338
    34     if (isset($l10n[$domain]))
    35         echo apply_filters('gettext', $l10n[$domain]->translate($text), $text);
    36     else
    37         echo $text;
     39function _c($text, $domain = 'default') {
     40    $whole = translate($text, $domain);
     41    $last_bar = strrpos($whole, '|');
     42    if ( false == $last_bar ) {
     43        return $whole;
     44    } else {
     45        return substr($whole, 0, $last_bar);
     46    }
    3847}
    3948
     
    4352
    4453    if (isset($l10n[$domain])) {
    45         return $l10n[$domain]->ngettext($single, $plural, $number);
     54        return apply_filters('ngettext', $l10n[$domain]->ngettext($single, $plural, $number), $single, $plural, $number);
    4655    } else {
    4756        if ($number != 1)
  • tags/2.2/wp-includes/link-template.php

    r5468 r5480  
    99function permalink_link() { // For backwards compatibility
    1010    echo apply_filters('the_permalink', get_permalink());
     11}
     12
     13
     14/**
     15 * Conditionally adds a trailing slash if the permalink structure
     16 * has a trailing slash, strips the trailing slash if not
     17 * @global object Uses $wp_rewrite
     18 * @param $string string a URL with or without a trailing slash
     19 * @param $type_of_url string the type of URL being considered (e.g. single, category, etc) for use in the filter
     20 * @return string
     21 */
     22function user_trailingslashit($string, $type_of_url = '') {
     23    global $wp_rewrite;
     24    if ( $wp_rewrite->use_trailing_slashes )
     25        $string = trailingslashit($string);
     26    else
     27        $string = untrailingslashit($string);
     28
     29    // Note that $type_of_url can be one of following:
     30    // single, single_trackback, single_feed, single_paged, feed, category, page, year, month, day, paged
     31    $string = apply_filters('user_trailingslashit', $string, $type_of_url);
     32    return $string;
    1133}
    1234
     
    5476
    5577        $category = '';
    56         if ( strstr($permalink, '%category%') ) {
     78        if (strpos($permalink, '%category%') !== false) {
    5779            $cats = get_the_category($post->ID);
    5880            $category = $cats[0]->category_nicename;
     
    78100            $post->post_name,
    79101        );
    80         return apply_filters('post_link', get_option('home') . str_replace($rewritecode, $rewritereplace, $permalink), $post);
     102        $permalink = get_option('home') . str_replace($rewritecode, $rewritereplace, $permalink);
     103        $permalink = user_trailingslashit($permalink, 'single');
     104        return apply_filters('post_link', $permalink, $post);
    81105    } else { // if they're not using the fancy permalink option
    82106        $permalink = get_option('home') . '/?p=' . $post->ID;
     
    118142        $link = get_page_uri($id);
    119143        $link = str_replace('%pagename%', $link, $pagestruct);
    120         $link = get_option('home') . "/$link/";
     144        $link = get_option('home') . "/$link";
     145        $link = user_trailingslashit($link, 'page');
    121146    } else {
    122147        $link = get_option('home') . "/?page_id=$id";
     
    142167        else
    143168            $parentlink = get_permalink( $object->post_parent );
    144         if (! strstr($parentlink, '?') )
     169        if (strpos($parentlink, '?') === false)
    145170            $link = trim($parentlink, '/') . '/' . $object->post_name . '/';
    146171    }
    147172
    148173    if (! $link ) {
    149         $link = get_bloginfo('home') . "/?attachment_id=$id";
     174        $link = get_bloginfo('url') . "/?attachment_id=$id";
    150175    }
    151176
     
    160185    if ( !empty($yearlink) ) {
    161186        $yearlink = str_replace('%year%', $year, $yearlink);
    162         return apply_filters('year_link', get_option('home') . trailingslashit($yearlink), $year);
     187        return apply_filters('year_link', get_option('home') . user_trailingslashit($yearlink, 'year'), $year);
    163188    } else {
    164189        return apply_filters('year_link', get_option('home') . '/?m=' . $year, $year);
     
    176201        $monthlink = str_replace('%year%', $year, $monthlink);
    177202        $monthlink = str_replace('%monthnum%', zeroise(intval($month), 2), $monthlink);
    178         return apply_filters('month_link', get_option('home') . trailingslashit($monthlink), $year, $month);
     203        return apply_filters('month_link', get_option('home') . user_trailingslashit($monthlink, 'month'), $year, $month);
    179204    } else {
    180205        return apply_filters('month_link', get_option('home') . '/?m=' . $year . zeroise($month, 2), $year, $month);
     
    196221        $daylink = str_replace('%monthnum%', zeroise(intval($month), 2), $daylink);
    197222        $daylink = str_replace('%day%', zeroise(intval($day), 2), $daylink);
    198         return apply_filters('day_link', get_option('home') . trailingslashit($daylink), $year, $month, $day);
     223        return apply_filters('day_link', get_option('home') . user_trailingslashit($daylink, 'day'), $year, $month, $day);
    199224    } else {
    200225        return apply_filters('day_link', get_option('home') . '/?m=' . $year . zeroise($month, 2) . zeroise($day, 2), $year, $month, $day);
     
    219244
    220245        $permalink = str_replace('%feed%', $feed, $permalink);
    221         $permalink = preg_replace('#/+#', '/', "/$permalink/");
    222         $output =  get_option('home') . $permalink;
     246        $permalink = preg_replace('#/+#', '/', "/$permalink");
     247        $output =  get_option('home') . user_trailingslashit($permalink, 'feed');
    223248    } else {
    224249        if ( false !== strpos($feed, 'comments_') )
     
    229254
    230255    return apply_filters('feed_link', $output, $feed);
     256}
     257
     258function get_post_comments_feed_link($post_id = '', $feed = 'rss2') {
     259    global $id;
     260
     261    if ( empty($post_id) )
     262        $post_id = (int) $id;
     263
     264    if ( '' != get_option('permalink_structure') ) {
     265        $url = trailingslashit( get_permalink() ) . 'feed';
     266        if ( 'rss2' != $feed )
     267            $url .= "/$feed";
     268        $url = user_trailingslashit($url, 'single_feed');
     269    } else {
     270        $url = get_option('home') . "/?feed=$feed&amp;p=$id";
     271    }
     272
     273    return apply_filters('post_comments_feed_link', $url);
    231274}
    232275
     
    399442
    400443    // if we already have a QUERY style page string
    401     if ( stristr( $qstr, $page_querystring ) ) {
     444    if ( stripos( $qstr, $page_querystring ) !== false ) {
    402445        $replacement = "$page_querystring=$pagenum";
    403446        $qstr = preg_replace("/".$page_querystring."[^\d]+\d+/", $replacement, $qstr);
     
    412455        // we need to know the way queries are being written
    413456        // if there's a querystring_start (a "?" usually), it's definitely not mod_rewritten
    414         if ( stristr( $qstr, '?' ) ) {
     457        if ( stripos( $qstr, '?' ) !== false ) {
    415458            // so append the query string (using &, since we already have ?)
    416459            $qstr .=    '&amp;' . $page_querystring . '=' . $pagenum;
     
    437480    $qstr = preg_replace('|^/+|', '', $qstr);
    438481    if ( $permalink )
    439         $qstr = trailingslashit($qstr);
     482        $qstr = user_trailingslashit($qstr, 'paged');
    440483    $qstr = preg_replace('/&([^#])(?![a-z]{1,8};)/', '&#038;$1', trailingslashit( get_option('home') ) . $qstr );
    441484
    442485    // showing /page/1/ or ?paged=1 is redundant
    443486    if ( 1 === $pagenum ) {
    444         $qstr = str_replace('page/1/', '', $qstr); // for mod_rewrite style
     487        $qstr = str_replace(user_trailingslashit('index.php/page/1', 'paged'), '', $qstr); // for PATHINFO style
     488        $qstr = str_replace(user_trailingslashit('page/1', 'paged'), '', $qstr); // for mod_rewrite style
    445489        $qstr = remove_query_arg('paged', $qstr); // for query style
    446490    }
  • tags/2.2/wp-includes/locale.php

    r5468 r5480  
    1313    var $meridiem;
    1414
    15     var $text_direction = '';
     15    var $text_direction = 'ltr';
    1616    var $locale_vars = array('text_direction');
    1717
  • tags/2.2/wp-includes/pluggable.php

    r5468 r5480  
    9797
    9898    wp_cache_add($user_id, $user, 'users');
    99     wp_cache_add($user->user_login, $user, 'userlogins');
    100 
     99    wp_cache_add($user->user_login, $user_id, 'userlogins');
    101100    return $user;
    102101}
     
    117116        return false;
    118117
    119     $userdata = wp_cache_get($user_login, 'userlogins');
     118    $user_id = wp_cache_get($user_login, 'userlogins');
     119    $userdata = wp_cache_get($user_id, 'users');
     120
    120121    if ( $userdata )
    121122        return $userdata;
     123
     124    $user_login = $wpdb->escape($user_login);
    122125
    123126    if ( !$user = $wpdb->get_row("SELECT * FROM $wpdb->users WHERE user_login = '$user_login'") )
     
    148151
    149152    wp_cache_add($user->ID, $user, 'users');
    150     wp_cache_add($user->user_login, $user, 'userlogins');
    151 
     153    wp_cache_add($user->user_login, $user->ID, 'userlogins');
    152154    return $user;
    153155
     
    157159if ( !function_exists('wp_mail') ) :
    158160function wp_mail($to, $subject, $message, $headers = '') {
    159     if( $headers == '' ) {
     161    global $phpmailer;
     162
     163    if ( !is_object( $phpmailer ) ) {
     164        require_once(ABSPATH . WPINC . '/class-phpmailer.php');
     165        require_once(ABSPATH . WPINC . '/class-smtp.php');
     166        $phpmailer = new PHPMailer();
     167    }
     168
     169    $mail = compact('to', 'subject', 'message', 'headers');
     170    $mail = apply_filters('wp_mail', $mail);
     171    extract($mail);
     172
     173    if ( $headers == '' ) {
    160174        $headers = "MIME-Version: 1.0\n" .
    161             "From: wordpress@" . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME'])) . "\n" .
     175            "From: " . apply_filters('wp_mail_from', "wordpress@" . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME']))) . "\n" .
    162176            "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";
    163177    }
    164178
    165     return @mail($to, $subject, $message, $headers);
     179    $phpmailer->ClearAddresses();
     180    $phpmailer->ClearCCs();
     181    $phpmailer->ClearBCCs();
     182    $phpmailer->ClearReplyTos();
     183    $phpmailer->ClearAllRecipients();
     184    $phpmailer->ClearCustomHeaders();
     185
     186    $phpmailer->FromName = "WordPress";
     187    $phpmailer->AddAddress("$to", "");
     188    $phpmailer->Subject = $subject;
     189    $phpmailer->Body    = $message;
     190    $phpmailer->IsHTML(false);
     191    $phpmailer->IsMail(); // set mailer to use php mail()
     192
     193    do_action_ref_array('phpmailer_init', array(&$phpmailer));
     194
     195    $mailheaders = (array) explode( "\n", $headers );
     196    foreach ( $mailheaders as $line ) {
     197        $header = explode( ":", $line );
     198        switch ( trim( $header[0] ) ) {
     199            case "From":
     200                $from = trim( str_replace( '"', '', $header[1] ) );
     201                if ( strpos( $from, '<' ) ) {
     202                    $phpmailer->FromName = str_replace( '"', '', substr( $header[1], 0, strpos( $header[1], '<' ) - 1 ) );
     203                    $from = trim( substr( $from, strpos( $from, '<' ) + 1 ) );
     204                    $from = str_replace( '>', '', $from );
     205                } else {
     206                    $phpmailer->FromName = $from;
     207                }
     208                $phpmailer->From = trim( $from );
     209                break;
     210            default:
     211                if ( $line != '' && $header[0] != 'MIME-Version' && $header[0] != 'Content-Type' )
     212                    $phpmailer->AddCustomHeader( $line );
     213                break;
     214        }
     215    }
     216
     217    $result = @$phpmailer->Send();
     218
     219    return $result;
    166220}
    167221endif;
     
    229283    $referer = strtolower(wp_get_referer());
    230284    if ( !wp_verify_nonce($_REQUEST['_wpnonce'], $action) &&
    231         !(-1 == $action && strstr($referer, $adminurl)) ) {
     285        !(-1 == $action && strpos($referer, $adminurl) !== false)) {
    232286        wp_nonce_ays($action);
    233287        die();
     
    371425    }
    372426    $notify_message .= get_permalink($comment->comment_post_ID) . "#comments\r\n\r\n";
    373     $notify_message .= sprintf( __('To delete this comment, visit: %s'), get_option('siteurl')."/wp-admin/comment.php?action=cdc&c=$comment_id" ) . "\r\n";
    374     $notify_message .= sprintf( __('To mark this comment as spam, visit: %s'), get_option('siteurl')."/wp-admin/comment.php?action=cdc&dt=spam&c=$comment_id" ) . "\r\n";
     427    $notify_message .= sprintf( __('Delete it: %s'), get_option('siteurl')."/wp-admin/comment.php?action=cdc&c=$comment_id" ) . "\r\n";
     428    $notify_message .= sprintf( __('Spam it: %s'), get_option('siteurl')."/wp-admin/comment.php?action=cdc&dt=spam&c=$comment_id" ) . "\r\n";
    375429
    376430    $wp_email = 'wordpress@' . preg_replace('#^www\.#', '', strtolower($_SERVER['SERVER_NAME']));
  • tags/2.2/wp-includes/plugin.php

    r5468 r5480  
    11<?php
    22
    3 //
    4 // Filter functions, the core of the WP plugin architecture.
    5 //
    6 
     3/**
     4 * Hooks a function to a specific filter action.
     5 *
     6 * Filters are the hooks that WordPress launches to modify text of various types
     7 * before adding it to the database or sending it to the browser screen. Plugins
     8 * can specify that one or more of its PHP functions is executed to
     9 * modify specific types of text at these times, using the Filter API.
     10 * See the [Plugin API] for a list of filter hooks.
     11 *
     12 * @param string $tag The name of the filter to hook the <tt>$function_to_add</tt> to.
     13 * @param callback $function_to_add The name of the function to be called when the filter is applied.
     14 * @param int $priority optional. Used to specify the order in which the functions associated with a particular action are executed (default: 10). Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action.
     15 * @param int $accepted_args optional. The number of arguments the function accept (default 1). In WordPress 1.5.1+, hooked functions can take extra arguments that are set when the matching do_action() or apply_filters() call is run.
     16 * @return boolean true if the <tt>$function_to_add</tt> is added succesfully to filter <tt>$tag</tt>. How many arguments your function takes. In WordPress 1.5.1+, hooked functions can take extra arguments that are set when the matching <tt>do_action()</tt> or <tt>apply_filters()</tt> call is run. For example, the action <tt>comment_id_not_found</tt> will pass any functions that hook onto it the ID of the requested comment.
     17 */
    718function add_filter($tag, $function_to_add, $priority = 10, $accepted_args = 1) {
    8     global $wp_filter;
    9 
    10     // check that we don't already have the same filter at the same priority
    11     if ( isset($wp_filter[$tag]["$priority"]) ) {
    12         foreach ( $wp_filter[$tag]["$priority"] as $filter ) {
    13             // uncomment if we want to match function AND accepted_args
    14             // if ( $filter == array($function, $accepted_args) ) {
    15             if ( $filter['function'] == $function_to_add )
    16                 return true;
    17         }
    18     }
    19 
    20     // So the format is wp_filter['tag']['array of priorities']['array of ['array (functions, accepted_args)]']
    21     $wp_filter[$tag]["$priority"][] = array('function'=>$function_to_add, 'accepted_args'=>$accepted_args);
     19    global $wp_filter, $merged_filters;
     20
     21    // So the format is wp_filter['tag']['array of priorities']['array of functions serialized']['array of ['array (functions, accepted_args)]']
     22    $wp_filter[$tag][$priority][serialize($function_to_add)] = array('function' => $function_to_add, 'accepted_args' => $accepted_args);
     23    unset( $merged_filters[ $tag ] );
    2224    return true;
    2325}
    2426
     27/**
     28 * Call the functions added to a filter hook.
     29 *
     30 * The callback functions attached to filter hook <tt>$tag</tt> are invoked by
     31 * calling this function. This function can be used to create a new filter hook
     32 * by simply calling this function with the name of the new hook specified using
     33 * the <tt>$tag</a> parameter.
     34 * @uses merge_filters Merges the filter hooks using this function.
     35 * @param string $tag The name of the filter hook.
     36 * @param string $string The text on which the filters hooked to <tt>$tag</tt> are applied on.
     37 * @param mixed $var,... Additional variables passed to the functions hooked to <tt>$tag</tt>.
     38 * @return string The text in <tt>$string</tt> after all hooked functions are applied to it.
     39 */
    2540function apply_filters($tag, $string) {
    26     global $wp_filter;
    27 
    28     $args = array();
    29     for ( $a = 2; $a < func_num_args(); $a++ )
    30         $args[] = func_get_arg($a);
    31 
    32     merge_filters($tag);
     41    global $wp_filter, $merged_filters;
     42
     43    if ( !isset( $merged_filters[ $tag ] ) )
     44        merge_filters($tag);
    3345
    3446    if ( !isset($wp_filter[$tag]) )
    3547        return $string;
    3648
    37     foreach ( (array) $wp_filter[$tag] as $priority => $functions ) {
    38         if ( !is_null($functions) ) {
    39             foreach ( (array) $functions as $function ) {
    40                 $function_name = $function['function'];
    41                 $accepted_args = $function['accepted_args'];
    42                 $the_args = $args;
    43                 array_unshift($the_args, $string);
    44                 if ( $accepted_args > 0 )
    45                     $the_args = array_slice($the_args, 0, $accepted_args);
    46                 elseif ( 0 == $accepted_args )
    47                     $the_args = NULL;
    48                 $string = call_user_func_array($function_name, $the_args);
     49    reset( $wp_filter[ $tag ] );
     50
     51    $args = func_get_args();
     52
     53    do{
     54        foreach( (array) current($wp_filter[$tag]) as $the_ )
     55            if ( !is_null($the_['function']) ){
     56                $args[1] = $string;
     57                $string = call_user_func_array($the_['function'], array_slice($args, 1, (int) $the_['accepted_args']));
    4958            }
    50         }
     59
     60    } while ( next($wp_filter[$tag]) );
     61
     62    return $string;
     63}
     64
     65/**
     66 * Merge the filter functions of a specific filter hook with generic filter functions.
     67 *
     68 * It is possible to defined generic filter functions using the filter hook
     69 * <em>all</e>. These functions are called for every filter tag. This function
     70 * merges the functions attached to the <em>all</em> hook with the functions
     71 * of a specific hoook defined by <tt>$tag</tt>.
     72 * @param string $tag The filter hook of which the functions should be merged.
     73 */
     74function merge_filters($tag) {
     75    global $wp_filter, $merged_filters;
     76
     77    if ( isset($wp_filter['all']) && is_array($wp_filter['all']) )
     78        $wp_filter[$tag] = array_merge($wp_filter['all'], (array) $wp_filter[$tag]);
     79
     80    if ( isset($wp_filter[$tag]) ){
     81        reset($wp_filter[$tag]);
     82        uksort($wp_filter[$tag], "strnatcasecmp");
    5183    }
    52     return $string;
    53 }
    54 
    55 function merge_filters($tag) {
    56     global $wp_filter;
    57     if ( isset($wp_filter['all']) ) {
    58         foreach ( (array) $wp_filter['all'] as $priority => $functions ) {
    59             if ( isset($wp_filter[$tag][$priority]) )
    60                 $wp_filter[$tag][$priority] = array_merge($wp_filter['all'][$priority], $wp_filter[$tag][$priority]);
    61             else
    62                 $wp_filter[$tag][$priority] = array_merge($wp_filter['all'][$priority], array());
    63             $wp_filter[$tag][$priority] = array_unique($wp_filter[$tag][$priority]);
    64         }
    65     }
    66 
    67     if ( isset($wp_filter[$tag]) )
    68         uksort( $wp_filter[$tag], "strnatcasecmp" );
    69 }
    70 
     84    $merged_filters[ $tag ] = true;
     85}
     86
     87/**
     88 * Removes a function from a specified filter hook.
     89 *
     90 * This function removes a function attached to a specified filter hook. This
     91 * method can be used to remove default functions attached to a specific filter
     92 * hook and possibly replace them with a substitute.
     93 * @param string $tag The filter hook to which the function to be removed is hooked.
     94 * @param callback $function_to_remove The name of the function which should be removed.
     95 * @param int $priority optional. The priority of the function (default: 10).
     96 * @param int $accepted_args optional. The number of arguments the function accpets (default: 1).
     97 * @return boolean Whether the function is removed.
     98 */
    7199function remove_filter($tag, $function_to_remove, $priority = 10, $accepted_args = 1) {
    72     global $wp_filter;
    73 
    74     // rebuild the list of filters
    75     if ( isset($wp_filter[$tag]["$priority"]) ) {
    76         $new_function_list = array();
    77         foreach ( (array) $wp_filter[$tag]["$priority"] as $filter ) {
    78             if ( $filter['function'] != $function_to_remove )
    79                 $new_function_list[] = $filter;
    80         }
    81         $wp_filter[$tag]["$priority"] = $new_function_list;
    82     }
     100    global $wp_filter, $merged_filters;
     101
     102    unset($GLOBALS['wp_filter'][$tag][$priority][serialize($function_to_remove)]);
     103    unset( $merged_filters[ $tag ] );
     104
    83105    return true;
    84106}
    85107
    86 //
    87 // Action functions
    88 //
    89 
     108/**
     109 * Hooks a function on to a specific action.
     110 *
     111 * Actions are the hooks that the WordPress core launches at specific points
     112 * during execution, or when specific events occur. Plugins can specify that
     113 * one or more of its PHP functions are executed at these points, using the
     114 * Action API.
     115 *
     116 * @param string $tag The name of the action to which the <tt>$function_to-add</tt> is hooked.
     117 * @param callback $function_to_add The name of the function you wish to be called. Note: any of the syntaxes explained in the PHP documentation for the 'callback' type (http://us2.php.net/manual/en/language.pseudo-types.php#language.types.callback) are valid.
     118 * @param int $priority optional. Used to specify the order in which the functions associated with a particular action are executed (default: 10). Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action.
     119 * @param int $accepted_args optional. The number of arguments the function accept (default 1). In WordPress 1.5.1+, hooked functions can take extra arguments that are set when the matching do_action() or apply_filters() call is run.
     120 * @return boolean Always true.
     121 */
    90122function add_action($tag, $function_to_add, $priority = 10, $accepted_args = 1) {
    91123    add_filter($tag, $function_to_add, $priority, $accepted_args);
    92124}
    93125
     126/**
     127 * Execute functions hooked on a specific action hook.
     128 *
     129 * This function invokes all functions attached to action hook <tt>$tag</tt>.
     130 * It is possible to create new action hooks by simply calling this function,
     131 * specifying the name of the new hook using the <tt>$tag</tt> parameter.
     132 * @uses merge_filters
     133 * @param string $tag The name of the action to be executed.
     134 * @param mixed $arg,... Optional additional arguments which are passed on to the functions hooked to the action.
     135 */
    94136function do_action($tag, $arg = '') {
    95137    global $wp_filter, $wp_actions;
     138
     139    if ( is_array($wp_actions) )
     140        $wp_actions[] = $tag;
     141    else
     142        $wp_actions = array($tag);
    96143
    97144    $args = array();
     
    108155        return;
    109156
    110     foreach ( (array) $wp_filter[$tag] as $priority => $functions ) {
    111         if ( !is_null($functions) ) {
    112             foreach ( (array) $functions as $function ) {
    113                 $function_name = $function['function'];
    114                 $accepted_args = $function['accepted_args'];
    115 
    116                 if ( $accepted_args > 0 )
    117                     $the_args = array_slice($args, 0, $accepted_args);
    118                 elseif ( $accepted_args == 0 )
    119                     $the_args = NULL;
    120                 else
    121                     $the_args = $args;
    122 
    123                 call_user_func_array($function_name, $the_args);
    124             }
    125         }
    126     }
    127 
    128     if ( is_array($wp_actions) )
    129         $wp_actions[] = $tag;
    130     else
    131         $wp_actions = array($tag);
    132 }
    133 
    134 // Returns the number of times an action has been done
     157    do{
     158        foreach( (array) current($wp_filter[$tag]) as $the_ )
     159            if ( !is_null($the_['function']) )
     160                call_user_func_array($the_['function'], array_slice($args, 0, (int) $the_['accepted_args']));
     161
     162    } while ( next($wp_filter[$tag]) );
     163
     164}
     165
     166/**
     167 * Return the number times an action is fired.
     168 * @param string $tag The name of the action hook.
     169 * @return int The number of times action hook <tt>$tag</tt> is fired
     170 */
    135171function did_action($tag) {
    136172    global $wp_actions;
    137173
     174    if ( empty($wp_actions) )
     175        return 0;
     176
    138177    return count(array_keys($wp_actions, $tag));
    139178}
    140179
     180/**
     181 * Execute functions hooked on a specific action hook, specifying arguments in a array.
     182 *
     183 * This function is identical to {@link do_action}, but the argumetns passe to
     184 * the functions hooked to <tt>$tag</tt> are supplied using an array.
     185 * @param string $tag The name of the action to be executed.
     186 * @param array $args The arguments supplied to the functions hooked to <tt>$tag</tt>
     187 */
    141188function do_action_ref_array($tag, $args) {
    142189    global $wp_filter, $wp_actions;
     
    152199        return;
    153200
    154     foreach ( (array) $wp_filter[$tag] as $priority => $functions ) {
    155         if ( !is_null($functions) ) {
    156             foreach ( (array) $functions as $function ) {
    157                 $function_name = $function['function'];
    158                 $accepted_args = $function['accepted_args'];
    159                 if ( $accepted_args > 0 )
    160                     $the_args = array_slice($args, 0, $accepted_args);
    161                 elseif ( 0 == $accepted_args )
    162                     $the_args = NULL;
    163                 else
    164                     $the_args = $args;
    165 
    166                 call_user_func_array($function_name, $the_args);
    167             }
    168         }
    169     }
    170 }
    171 
     201    do{
     202        foreach( (array) current($wp_filter[$tag]) as $the_ )
     203            if ( !is_null($the_['function']) )
     204                call_user_func_array($the_['function'], array_slice($args, 0, (int) $the_['accepted_args']));
     205
     206    } while ( next($wp_filter[$tag]) );
     207
     208}
     209
     210/**
     211 * Removes a function from a specified action hook.
     212 *
     213 * This function removes a function attached to a specified action hook. This
     214 * method can be used to remove default functions attached to a specific filter
     215 * hook and possibly replace them with a substitute.
     216 * @param string $tag The action hook to which the function to be removed is hooked.
     217 * @param callback $function_to_remove The name of the function which should be removed.
     218 * @param int $priority optional The priority of the function (default: 10).
     219 * @param int $accepted_args optional. The number of arguments the function accpets (default: 1).
     220 * @return boolean Whether the function is removed.
     221 */
    172222function remove_action($tag, $function_to_remove, $priority = 10, $accepted_args = 1) {
    173223    remove_filter($tag, $function_to_remove, $priority, $accepted_args);
     
    178228//
    179229
     230/**
     231 * Gets the basename of a plugin.
     232 *
     233 * This method extract the name of a plugin from its filename.
     234 * @param string $file The filename of plugin.
     235 * @return string The name of a plugin.
     236 */
    180237function plugin_basename($file) {
    181238    $file = preg_replace('|\\\\+|', '\\\\', $file);
     
    184241}
    185242
     243/**
     244 * Hook a function on a plugin activation action hook.
     245 *
     246 * When a plugin is activated, the action 'activate_PLUGINNAME' hook is
     247 * activated. In the name of this hook, PLUGINNAME is replaced with the name of
     248 * the plugin, including the optional subdirectory. For example, when the plugin
     249 * is located in <tt>wp-content/plugin/sampleplugin/sample.php</tt>, then the
     250 * name of this hook will become 'activate_sampleplugin/sample.php'.
     251 * When the plugin consists of only one file and is (as by default) located at
     252 * <tt>wp-content/plugin/sample.php</tt> the name of this hook will be
     253 * 'activate_sample.php'.
     254 * @param string $file The filename of the plugin including the path.
     255 * @param string $function the function hooked to the 'activate_PLUGIN' action.
     256 */
    186257function register_activation_hook($file, $function) {
    187258    $file = plugin_basename($file);
     
    189260}
    190261
     262/**
     263 * Hook a function on a plugin deactivation action hook.
     264 *
     265 * When a plugin is deactivated, the action 'deactivate_PLUGINNAME' hook is
     266 * deactivated. In the name of this hook, PLUGINNAME is replaced with the name of
     267 * the plugin, including the optional subdirectory. For example, when the plugin
     268 * is located in <tt>wp-content/plugin/sampleplugin/sample.php</tt>, then the
     269 * name of this hook will become 'activate_sampleplugin/sample.php'.
     270 * When the plugin consists of only one file and is (as by default) located at
     271 * <tt>wp-content/plugin/sample.php</tt> the name of this hook will be
     272 * 'activate_sample.php'.
     273 * @param string $file The filename of the plugin including the path.
     274 * @param string $function the function hooked to the 'activate_PLUGIN' action.
     275 */
    191276function register_deactivation_hook($file, $function) {
    192277    $file = plugin_basename($file);
  • tags/2.2/wp-includes/post-template.php

    r5468 r5480  
    8181
    8282    $content = $pages[$page-1];
    83     if ( preg_match('/<!--more(.+?)?-->/', $content, $matches) ) {
     83    if ( preg_match('/<!--more(.*?)?-->/', $content, $matches) ) {
    8484        $content = explode($matches[0], $content, 2);
    8585        if ( !empty($matches[1]) && !empty($more_link_text) )
     
    9696    if ( count($content) > 1 ) {
    9797        if ( $more ) {
    98             $output .= '<a id="more-'.$id.'"></a>'.$content[1];
     98            $output .= '<span id="more-'.$id.'"></span>'.$content[1];
    9999        } else {
    100100            $output = balanceTags($output);
     
    102102                $output .= ' <a href="'. get_permalink() . "#more-$id\" class=\"more-link\">$more_link_text</a>";
    103103        }
    104            
     104
    105105    }
    106106    if ( $preview ) // preview fix for javascript bug with foreign languages
     
    132132
    133133function wp_link_pages($args = '') {
     134    global $post;
     135
    134136    if ( is_array($args) )
    135137        $r = &$args;
     
    156158                $output .= ' ';
    157159                if ( ($i != $page) || ((!$more) && ($page==1)) ) {
    158                     if ( '' == get_option('permalink_structure') )
    159                         $output .= '<a href="' . get_permalink() . '&amp;page=' . $i . '">';
    160                     else
    161                         $output .= '<a href="' . trailingslashit(get_permalink()) . $i . '/">';
     160                    if ( 1 == $i ) {
     161                        $output .= '<a href="' . get_permalink() . '">';
     162                    } else {
     163                        if ( '' == get_option('permalink_structure') || 'draft' == $post->post_status )
     164                            $output .= '<a href="' . get_permalink() . '&amp;page=' . $i . '">';
     165                        else
     166                            $output .= '<a href="' . trailingslashit(get_permalink()) . user_trailingslashit($i, 'single_paged') . '">';
     167                    }
    162168                }
    163169                $output .= $j;
     
    171177                $i = $page - 1;
    172178                if ( $i && $more ) {
    173                     if ( '' == get_option('permalink_structure') )
    174                         $output .= '<a href="' . get_permalink() . '&amp;page=' . $i . '">' . $previouspagelink . '</a>';
    175                     else
    176                         $output .= '<a href="' . get_permalink() . $i . '/">'.$previouspagelink.'</a>';
     179                    if ( 1 == $i ) {
     180                        $output .= '<a href="' . get_permalink() . '">' . $previouspagelink . '</a>';
     181                    } else {
     182                        if ( '' == get_option('permalink_structure') || 'draft' == $post->post_status )
     183                            $output .= '<a href="' . get_permalink() . '&amp;page=' . $i . '">' . $previouspagelink . '</a>';
     184                        else
     185                            $output .= '<a href="' . trailingslashit(get_permalink()) . user_trailingslashit($i, 'single_paged') . '">' . $previouspagelink . '</a>';
     186                    }
    177187                }
    178188                $i = $page + 1;
    179189                if ( $i <= $numpages && $more ) {
    180                     if ( '' == get_option('permalink_structure') )
    181                         $output .= '<a href="' . get_permalink() . '&amp;page=' . $i . '">'.$nextpagelink.'</a>';
    182                     else
    183                         $output .= '<a href="' . trailingslashit(get_permalink()) . $i . '/">' . $nextpagelink . '</a>';
     190                    if ( 1 == $i ) {
     191                        $output .= '<a href="' . get_permalink() . '">' . $nextpagelink . '</a>';
     192                    } else {
     193                        if ( '' == get_option('permalink_structure') || 'draft' == $post->post_status )
     194                            $output .= '<a href="' . get_permalink() . '&amp;page=' . $i . '">' . $nextpagelink . '</a>';
     195                        else
     196                            $output .= '<a href="' . trailingslashit(get_permalink()) . user_trailingslashit($i, 'single_paged') . '">' . $nextpagelink . '</a>';
     197                    }
    184198                }
    185199                $output .= $after;
     
    222236            $values = array_map('trim', get_post_custom_values($key));
    223237            $value = implode($values,', ');
    224             echo "<li><span class='post-meta-key'>$key:</span> $value</li>\n";
     238            echo apply_filters('the_meta_key', "<li><span class='post-meta-key'>$key:</span> $value</li>\n", $key, $value);
    225239        }
    226240        echo "</ul>\n";
     
    270284
    271285    $defaults = array('depth' => 0, 'show_date' => '', 'date_format' => get_option('date_format'),
    272         'child_of' => 0, 'exclude' => '', 'title_li' => __('Pages'), 'echo' => 1, 'authors' => '');
     286        'child_of' => 0, 'exclude' => '', 'title_li' => __('Pages'), 'echo' => 1, 'authors' => '', 'sort_column' => 'menu_order, post_title');
    273287    $r = array_merge($defaults, $r);
    274288
     
    334348    $_post = & get_post($id);
    335349
    336     if ( ('attachment' != $_post->post_type) || !$url = wp_get_attachment_url() )
     350    if ( ('attachment' != $_post->post_type) || !$url = wp_get_attachment_url($_post->ID) )
    337351        return __('Missing Attachment');
    338352
  • tags/2.2/wp-includes/post.php

    r5468 r5480  
    7575function get_extended($post) {
    7676    //Match the new style more links
    77     if ( preg_match('/<!--more(.*?)-->/', $post, $matches) ) {
     77    if ( preg_match('/<!--more(.*?)?-->/', $post, $matches) ) {
    7878        list($main, $extended) = explode($matches[0], $post, 2);
    7979    } else {
     
    8181        $extended = '';
    8282    }
    83    
     83
    8484    // Strip leading and trailing whitespace
    8585    $main = preg_replace('/^[\s]*(.*)[\s]*$/', '\\1', $main);
     
    107107    } else {
    108108        $post = (int) $post;
    109         if ( $_post = wp_cache_get($post, 'pages') )
     109        if ( isset($post_cache[$blog_id][$post]) )
     110            $_post = & $post_cache[$blog_id][$post];
     111        elseif ( $_post = wp_cache_get($post, 'pages') )
    110112            return get_page($_post, $output);
    111         elseif ( isset($post_cache[$blog_id][$post]) )
    112             $_post = & $post_cache[$blog_id][$post];
    113113        else {
    114114            $query = "SELECT * FROM $wpdb->posts WHERE ID = '$post' LIMIT 1";
     
    226226        $exclusions .= ')';
    227227
    228     $query ="SELECT DISTINCT * FROM $wpdb->posts " ;
    229     $query .= ( empty( $category ) ? "" : ", $wpdb->post2cat " );
    230     $query .= ( empty( $meta_key ) ? "" : ", $wpdb->postmeta " );
    231     $query .= " WHERE (post_type = 'post' AND post_status = 'publish') $exclusions $inclusions ";
    232     $query .= ( empty( $category ) ? "" : "AND ($wpdb->posts.ID = $wpdb->post2cat.post_id AND $wpdb->post2cat.category_id = " . $category. ") " );
    233     $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' )" );
    234     $query .= " GROUP BY $wpdb->posts.ID ORDER BY " . $orderby . " " . $order . " LIMIT " . $offset . ',' . $numberposts;
    235 
    236228    $query  = "SELECT DISTINCT * FROM $wpdb->posts ";
    237229    $query .= empty( $category ) ? '' : ", $wpdb->post2cat ";
     
    444436    }
    445437
     438    do_action('deleted_post', $postid);
     439   
    446440    return $post;
    447441}
     
    562556            $post_date_gmt = get_gmt_from_date($post_date);
    563557    }
    564        
     558
    565559    if ( 'publish' == $post_status ) {
    566560        $now = gmdate('Y-m-d H:i:59');
     
    679673        if ( defined('XMLRPC_REQUEST') )
    680674            do_action('xmlrpc_publish_post', $post_ID);
     675        if ( defined('APP_REQUEST') )
     676            do_action('app_publish_post', $post_ID);
    681677
    682678        if ( !defined('WP_IMPORTING') ) {
     
    709705    if ( 'future' == $post_status )
    710706        wp_schedule_single_event(strtotime($post_date_gmt. ' GMT'), 'publish_future_post', array($post_ID));
    711        
     707
    712708    do_action('save_post', $post_ID);
    713709    do_action('wp_insert_post', $post_ID);
     
    912908    if ( ! $page_ids = wp_cache_get('all_page_ids', 'pages') ) {
    913909        $page_ids = $wpdb->get_col("SELECT ID FROM $wpdb->posts WHERE post_type = 'page'");
    914         wp_cache_set('all_page_ids', $page_ids, 'pages');
     910        wp_cache_add('all_page_ids', $page_ids, 'pages');
    915911    }
    916912
     
    955951                // Potential issue: we're not checking to see if the post_type = 'page'
    956952                // So all non-'post' posts will get cached as pages.
    957                 wp_cache_set($_page->ID, $_page, 'pages');
     953                wp_cache_add($_page->ID, $_page, 'pages');
    958954            }
    959955        }
     
    11161112    if (!empty($authors)) {
    11171113        $post_authors = preg_split('/[\s,]+/',$authors);
    1118        
     1114
    11191115        if ( count($post_authors) ) {
    11201116            foreach ( $post_authors as $post_author ) {
     
    12071203
    12081204function is_local_attachment($url) {
    1209     if ( !strstr($url, get_bloginfo('home') ) )
    1210         return false;
    1211     if ( strstr($url, get_bloginfo('home') . '/?attachment_id=') )
     1205    if (strpos($url, get_bloginfo('url')) === false)
     1206        return false;
     1207    if (strpos($url, get_bloginfo('url') . '/?attachment_id=') !== false)
    12121208        return true;
    12131209    if ( $id = url_to_postid($url) ) {
     
    15651561}
    15661562
     1563/**
     1564 * This function provides a standardized way to appropriately select on
     1565 * the post_status of posts/pages. The function will return a piece of
     1566 * SQL code that can be added to a WHERE clause; this SQL is constructed
     1567 * to allow all published posts, and all private posts to which the user
     1568 * has access.
     1569 *
     1570 * @param string $post_type currently only supports 'post' or 'page'.
     1571 * @return string SQL code that can be added to a where clause.
     1572 */
     1573function get_private_posts_cap_sql($post_type) {
     1574    global $user_ID;
     1575    $cap = '';
     1576
     1577    // Private posts
     1578    if ($post_type == 'post') {
     1579        $cap = 'read_private_posts';
     1580    // Private pages
     1581    } elseif ($post_type == 'page') {
     1582        $cap = 'read_private_pages';
     1583    // Dunno what it is, maybe plugins have their own post type?
     1584    } else {
     1585        $cap = apply_filters('pub_priv_sql_capability', $cap);
     1586
     1587        if (empty($cap)) {
     1588            // We don't know what it is, filters don't change anything,
     1589            // so set the SQL up to return nothing.
     1590            return '1 = 0';
     1591        }
     1592    }
     1593
     1594    $sql = '(post_status = \'publish\'';
     1595
     1596    if (current_user_can($cap)) {
     1597        // Does the user have the capability to view private posts? Guess so.
     1598        $sql .= ' OR post_status = \'private\'';
     1599    } elseif (is_user_logged_in()) {
     1600        // Users can view their own private posts.
     1601        $sql .= ' OR post_status = \'private\' AND post_author = \'' . $user_ID . '\'';
     1602    }
     1603
     1604    $sql .= ')';
     1605
     1606    return $sql;
     1607}
     1608
    15671609?>
  • tags/2.2/wp-includes/query.php

    r5468 r5480  
    99
    1010    return $wp_query->get($var);
     11}
     12
     13function set_query_var($var, $value) {
     14    global $wp_query;
     15
     16    return $wp_query->set($var, $value);
    1117}
    1218
     
    2430    global $wp_query;
    2531
    26     return ( $wp_query->is_admin || strstr($_SERVER['REQUEST_URI'], 'wp-admin/') );
     32    return ($wp_query->is_admin || (strpos($_SERVER['REQUEST_URI'], 'wp-admin/') !== false));
    2733}
    2834
     
    195201    global $wp_query;
    196202
    197     return $wp_query->is_singular; 
     203    return $wp_query->is_singular;
    198204}
    199205
     
    249255    $wp_query->the_post();
    250256}
     257
     258/*
     259 * Comments loop.
     260 */
     261
     262function have_comments() {
     263    global $wp_query;
     264    return $wp_query->have_comments();
     265}
     266
     267function the_comment() {
     268    global $wp_query;
     269    return $wp_query->the_comment();
     270
    251271
    252272/*
     
    266286    var $in_the_loop = false;
    267287    var $post;
     288
     289    var $comments;
     290    var $comment_count = 0;
     291    var $current_comment = -1;
     292    var $comment;
    268293
    269294    var $found_posts = 0;
     
    283308    var $is_search = false;
    284309    var $is_feed = false;
     310    var $is_comment_feed = false;
    285311    var $is_trackback = false;
    286312    var $is_home = false;
     
    306332        $this->is_search = false;
    307333        $this->is_feed = false;
     334        $this->is_comment_feed = false;
    308335        $this->is_trackback = false;
    309336        $this->is_home = false;
     
    334361        $this->parse_query('');
    335362    }
    336    
     363
    337364    function fill_query_vars($array) {
    338365        $keys = array(
     
    369396                $array[$key] = '';
    370397        }
    371        
     398
    372399        return $array;
    373400    }
     
    378405            $this->init();
    379406            if ( is_array($query) )
    380                 $qv = & $query;
     407                $this->query_vars = $query;
    381408            else
    382                 parse_str($query, $qv);
     409                parse_str($query, $this->query_vars);
    383410            $this->query = $query;
    384             $this->query_vars = $qv;
    385         }
    386        
    387         $qv = $this->fill_query_vars($qv);
    388        
     411        }
     412
     413        $this->query_vars = $this->fill_query_vars($this->query_vars);
     414        $qv = &$this->query_vars;
     415
    389416        if ( ! empty($qv['robots']) ) {
    390417            $this->is_robots = true;
     
    400427        }
    401428
     429        $qv['p'] =  (int) $qv['p'];
     430        $qv['page_id'] =  (int) $qv['page_id'];
     431        $qv['year'] = (int) $qv['year'];
     432        $qv['monthnum'] = (int) $qv['monthnum'];
     433        $qv['day'] = (int) $qv['day'];
     434        $qv['w'] = (int) $qv['w'];
    402435        $qv['m'] =  (int) $qv['m'];
    403         $qv['p'] =  (int) $qv['p'];
     436        if ( '' != $qv['hour'] ) $qv['hour'] = (int) $qv['hour'];
     437        if ( '' != $qv['minute'] ) $qv['minute'] = (int) $qv['minute'];
     438        if ( '' != $qv['second'] ) $qv['second'] = (int) $qv['second'];
    404439
    405440        // Compat.  Map subpost to attachment.
     
    409444            $qv['attachment_id'] = $qv['subpost_id'];
    410445
    411         if ( ('' != $qv['attachment']) || (int) $qv['attachment_id'] ) {
     446        $qv['attachment_id'] = (int) $qv['attachment_id'];
     447       
     448        if ( ('' != $qv['attachment']) || !empty($qv['attachment_id']) ) {
    412449            $this->is_single = true;
    413450            $this->is_attachment = true;
    414         } elseif ('' != $qv['name']) {
     451        } elseif ( '' != $qv['name'] ) {
    415452            $this->is_single = true;
    416453        } elseif ( $qv['p'] ) {
    417454            $this->is_single = true;
    418         } elseif (('' != $qv['hour']) && ('' != $qv['minute']) &&('' != $qv['second']) && ('' != $qv['year']) && ('' != $qv['monthnum']) && ('' != $qv['day'])) {
     455        } elseif ( ('' != $qv['hour']) && ('' != $qv['minute']) &&('' != $qv['second']) && ('' != $qv['year']) && ('' != $qv['monthnum']) && ('' != $qv['day']) ) {
    419456            // If year, month, day, hour, minute, and second are set, a single
    420457            // post is being queried.
    421458            $this->is_single = true;
    422         } elseif ('' != $qv['static'] || '' != $qv['pagename'] || (int) $qv['page_id']) {
     459        } elseif ( '' != $qv['static'] || '' != $qv['pagename'] || !empty($qv['page_id']) ) {
    423460            $this->is_page = true;
    424461            $this->is_single = false;
    425         } elseif (!empty($qv['s'])) {
     462        } elseif ( !empty($qv['s']) ) {
    426463            $this->is_search = true;
    427464        } else {
    428465        // Look for archive queries.  Dates, categories, authors.
    429466
    430             if ( (int) $qv['second']) {
     467            if ( '' != $qv['second'] ) {
    431468                $this->is_time = true;
    432469                $this->is_date = true;
    433470            }
    434471
    435             if ( (int) $qv['minute']) {
     472            if ( '' != $qv['minute'] ) {
    436473                $this->is_time = true;
    437474                $this->is_date = true;
    438475            }
    439476
    440             if ( (int) $qv['hour']) {
     477            if ( '' != $qv['hour'] ) {
    441478                $this->is_time = true;
    442479                $this->is_date = true;
    443480            }
    444481
    445             if ( (int) $qv['day']) {
     482            if ( $qv['day'] ) {
    446483                if (! $this->is_date) {
    447484                    $this->is_day = true;
     
    450487            }
    451488
    452             if ( (int)  $qv['monthnum']) {
     489            if ( $qv['monthnum'] ) {
    453490                if (! $this->is_date) {
    454491                    $this->is_month = true;
     
    457494            }
    458495
    459             if ( (int)  $qv['year']) {
     496            if ( $qv['year'] ) {
    460497                if (! $this->is_date) {
    461498                    $this->is_year = true;
     
    464501            }
    465502
    466             if ( (int)  $qv['m']) {
     503            if ( $qv['m'] ) {
    467504                $this->is_date = true;
    468505                if (strlen($qv['m']) > 9) {
     
    481518            }
    482519
    483             if (empty($qv['cat']) || ($qv['cat'] == '0')) {
     520            if ( empty($qv['cat']) || ($qv['cat'] == '0') ) {
    484521                $this->is_category = false;
    485522            } else {
    486                 if (stristr($qv['cat'],'-')) {
     523                if (strpos($qv['cat'], '-') !== false) {
    487524                    $this->is_category = false;
    488525                } else {
     
    491528            }
    492529
    493             if ('' != $qv['category_name']) {
     530            if ( '' != $qv['category_name'] ) {
    494531                $this->is_category = true;
    495532            }
    496533
    497             if ((empty($qv['author'])) || ($qv['author'] == '0')) {
     534            if ( empty($qv['author']) || ($qv['author'] == '0') ) {
    498535                $this->is_author = false;
    499536            } else {
     
    501538            }
    502539
    503             if ('' != $qv['author_name']) {
     540            if ( '' != $qv['author_name'] ) {
    504541                $this->is_author = true;
    505542            }
    506543
    507             if ( ($this->is_date || $this->is_author || $this->is_category)) {
     544            if ( ($this->is_date || $this->is_author || $this->is_category) )
    508545                $this->is_archive = true;
    509             }
    510         }
    511 
    512         if ('' != $qv['feed']) {
     546        }
     547
     548        if ( '' != $qv['feed'] )
    513549            $this->is_feed = true;
    514         }
    515 
    516         if ('' != $qv['tb']) {
     550
     551        if ( '' != $qv['tb'] )
    517552            $this->is_trackback = true;
    518         }
    519 
    520         if ('' != $qv['paged']) {
     553
     554        if ( '' != $qv['paged'] )
    521555            $this->is_paged = true;
    522         }
    523 
    524         if ('' != $qv['comments_popup']) {
     556
     557        if ( '' != $qv['comments_popup'] )
    525558            $this->is_comments_popup = true;
    526         }
    527 
    528         //if we're previewing inside the write screen
    529         if ('' != $qv['preview']) {
     559
     560        // if we're previewing inside the write screen
     561        if ('' != $qv['preview'])
    530562            $this->is_preview = true;
    531         }
    532 
    533         if (strstr($_SERVER['PHP_SELF'], 'wp-admin/')) {
     563
     564        if ( strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false )
    534565            $this->is_admin = true;
    535         }
    536 
    537         if ( $this->is_single || $this->is_page || $this->is_attachment )
    538             $this->is_singular = true;
    539 
    540         if ( ! ($this->is_singular || $this->is_archive || $this->is_search || $this->is_feed || $this->is_trackback || $this->is_404 || $this->is_admin || $this->is_comments_popup)) {
     566
     567        if ( false !== strpos($qv['feed'], 'comments-') ) {
     568            $qv['feed'] = str_replace('comments-', '', $qv['feed']);
     569            $qv['withcomments'] = 1;
     570        }
     571
     572        $this->is_singular = $this->is_single || $this->is_page || $this->is_attachment;
     573
     574        if ( $this->is_feed && ( !empty($qv['withcomments']) || ( empty($qv['withoutcomments']) && $this->is_singular ) ) )
     575            $this->is_comment_feed = true;
     576
     577        if ( !( $this->is_singular || $this->is_archive || $this->is_search || $this->is_feed || $this->is_trackback || $this->is_404 || $this->is_admin || $this->is_comments_popup ) )
    541578            $this->is_home = true;
    542         }
    543 
    544         if ( !empty($query) ) {
     579
     580        // Correct is_* for page_on_front and page_for_posts
     581        if ( $this->is_home && ( empty($this->query) || $qv['preview'] == 'true' ) && 'page' == get_option('show_on_front') && get_option('page_on_front') ) {
     582            $this->is_page = true;
     583            $this->is_home = false;
     584            $qv['page_id'] = get_option('page_on_front');
     585        }
     586
     587        if ( '' != $qv['pagename'] ) {
     588            $this->queried_object =& get_page_by_path($qv['pagename']);
     589            if ( !empty($this->queried_object) )
     590                $this->queried_object_id = (int) $this->queried_object->ID;
     591            else
     592                unset($this->queried_object);
     593
     594            if  ( 'page' == get_option('show_on_front') && isset($this->queried_object_id) && $this->queried_object_id == get_option('page_for_posts') ) {
     595                $this->is_page = false;
     596                $this->is_home = true;
     597                $this->is_posts_page = true;
     598            }
     599        }
     600
     601        if ( $qv['page_id'] ) {
     602            if  ( 'page' == get_option('show_on_front') && $qv['page_id'] == get_option('page_for_posts') ) {
     603                $this->is_page = false;
     604                $this->is_home = true;
     605                $this->is_posts_page = true;
     606            }
     607        }
     608
     609        if ( $this->is_posts_page && !$qv['withcomments'] )
     610            $this->is_comment_feed = false;
     611
     612        $this->is_singular = $this->is_single || $this->is_page || $this->is_attachment;
     613        // Done correcting is_* for page_on_front and page_for_posts
     614
     615        if ( !empty($query) )
    545616            do_action_ref_array('parse_query', array(&$this));
    546         }
    547617    }
    548618
     
    575645        // Shorthand.
    576646        $q = &$this->query_vars;
    577        
     647
    578648        $q = $this->fill_query_vars($q);
    579649
     
    635705
    636706        // If a month is specified in the querystring, load that month
    637         if ( (int) $q['m'] ) {
     707        if ( $q['m'] ) {
    638708            $q['m'] = '' . preg_replace('|[^0-9]|', '', $q['m']);
    639709            $where .= ' AND YEAR(post_date)=' . substr($q['m'], 0, 4);
     
    650720        }
    651721
    652         if ( (int) $q['hour'] ) {
    653             $q['hour'] = '' . intval($q['hour']);
     722        if ( '' != $q['hour'] )
    654723            $where .= " AND HOUR(post_date)='" . $q['hour'] . "'";
    655         }
    656 
    657         if ( (int) $q['minute'] ) {
    658             $q['minute'] = '' . intval($q['minute']);
     724
     725        if ( '' != $q['minute'] )
    659726            $where .= " AND MINUTE(post_date)='" . $q['minute'] . "'";
    660         }
    661 
    662         if ( (int) $q['second'] ) {
    663             $q['second'] = '' . intval($q['second']);
     727
     728        if ( '' != $q['second'] )
    664729            $where .= " AND SECOND(post_date)='" . $q['second'] . "'";
    665         }
    666 
    667         if ( (int) $q['year'] ) {
    668             $q['year'] = '' . intval($q['year']);
     730
     731        if ( $q['year'] )
    669732            $where .= " AND YEAR(post_date)='" . $q['year'] . "'";
    670         }
    671 
    672         if ( (int) $q['monthnum'] ) {
    673             $q['monthnum'] = '' . intval($q['monthnum']);
     733
     734        if ( $q['monthnum'] )
    674735            $where .= " AND MONTH(post_date)='" . $q['monthnum'] . "'";
    675         }
    676 
    677         if ( (int) $q['day'] ) {
    678             $q['day'] = '' . intval($q['day']);
     736
     737        if ( $q['day'] )
    679738            $where .= " AND DAYOFMONTH(post_date)='" . $q['day'] . "'";
    680         }
    681 
    682         // Compat.  Map subpost to attachment.
    683         if ( '' != $q['subpost'] )
    684             $q['attachment'] = $q['subpost'];
    685         if ( '' != $q['subpost_id'] )
    686             $q['attachment_id'] = $q['subpost_id'];
    687739
    688740        if ('' != $q['name']) {
     
    690742            $where .= " AND post_name = '" . $q['name'] . "'";
    691743        } else if ('' != $q['pagename']) {
    692             $reqpage = get_page_by_path($q['pagename']);
    693             if ( !empty($reqpage) )
    694                 $reqpage = $reqpage->ID;
    695             else
    696                 $reqpage = 0;
    697 
    698             if  ( ('page' == get_option('show_on_front') ) && ( $reqpage == get_option('page_for_posts') ) ) {
    699                 $this->is_singular = false;
    700                 $this->is_page = false;
    701                 $this->is_home = true;
    702                 $this->is_posts_page = true;
    703             } else {
     744            if ( isset($this->queried_object_id) )
     745                $reqpage = $this->queried_object_id;
     746            else {
     747                $reqpage = get_page_by_path($q['pagename']);
     748                if ( !empty($reqpage) )
     749                    $reqpage = $reqpage->ID;
     750                else
     751                    $reqpage = 0;
     752            }
     753
     754            if  ( ('page' != get_option('show_on_front') ) || ( $reqpage != get_option('page_for_posts') ) ) {
    704755                $q['pagename'] = str_replace('%2F', '/', urlencode(urldecode($q['pagename'])));
    705756                $page_paths = '/' . trim($q['pagename'], '/');
     
    716767        }
    717768
    718         if ( (int) $q['w'] ) {
    719             $q['w'] = ''.intval($q['w']);
     769        if ( $q['w'] )
    720770            $where .= " AND WEEK(post_date, 1)='" . $q['w'] . "'";
    721         }
    722771
    723772        if ( intval($q['comments_popup']) )
    724773            $q['p'] = intval($q['comments_popup']);
    725774
    726         // If a attachment is requested by number, let it supercede any post number.
    727         if ( ($q['attachment_id'] != '') && (intval($q['attachment_id']) != 0) )
    728             $q['p'] = (int) $q['attachment_id'];
     775        // If an attachment is requested by number, let it supercede any post number.
     776        if ( $q['attachment_id'] )
     777            $q['p'] = $q['attachment_id'];
    729778
    730779        // If a post number is specified, load that post
    731         if (($q['p'] != '') && intval($q['p']) != 0) {
    732             $q['p'] =  (int) $q['p'];
     780        if ( $q['p'] )
    733781            $where = ' AND ID = ' . $q['p'];
    734         }
    735 
    736         if (($q['page_id'] != '') && (intval($q['page_id']) != 0)) {
    737             $q['page_id'] = intval($q['page_id']);
    738             if  ( ('page' == get_option('show_on_front') ) && ( $q['page_id'] == get_option('page_for_posts') ) ) {
    739                 $this->is_singular = false;
    740                 $this->is_page = false;
    741                 $this->is_home = true;
    742                 $this->is_posts_page = true;
    743             } else {
     782
     783        if ( $q['page_id'] ) {
     784            if  ( ('page' != get_option('show_on_front') ) || ( $q['page_id'] != get_option('page_for_posts') ) ) {
    744785                $q['p'] = $q['page_id'];
    745                 $where = ' AND ID = '.$q['page_id'];
     786                $where = ' AND ID = ' . $q['page_id'];
    746787            }
    747788        }
    748789
    749790        // If a search pattern is specified, load the posts that match
    750         if (!empty($q['s'])) {
     791        if ( !empty($q['s']) ) {
    751792            // added slashes screw with quote grouping when done early, so done later
    752793            $q['s'] = stripslashes($q['s']);
     
    775816        // Category stuff
    776817
    777         if ((empty($q['cat'])) || ($q['cat'] == '0') ||
     818        if ( empty($q['cat']) || ($q['cat'] == '0') ||
    778819                // Bypass cat checks if fetching specific posts
    779                 ( $this->is_single || $this->is_page )) {
    780             $whichcat='';
     820                $this->is_singular ) {
     821            $whichcat = '';
    781822        } else {
    782823            $q['cat'] = ''.urldecode($q['cat']).'';
     
    787828            foreach ( $cat_array as $cat ) {
    788829                $cat = intval($cat);
    789                 $in = strstr($cat, '-') ? false : true;
     830                $in = (strpos($cat, '-') !== false) ? false : true;
    790831                $cat = trim($cat, '-');
    791832                if ( $in )
     
    815856
    816857        // Category stuff for nice URLs
    817         if ('' != $q['category_name']) {
     858        if ( '' != $q['category_name'] ) {
    818859            $reqcat = get_category_by_path($q['category_name']);
    819860            $q['category_name'] = str_replace('%2F', '/', urlencode(urldecode($q['category_name'])));
     
    848889        }
    849890
     891
     892
    850893        // Author/user stuff
    851894
    852         if ((empty($q['author'])) || ($q['author'] == '0')) {
     895        if ( empty($q['author']) || ($q['author'] == '0') ) {
    853896            $whichauthor='';
    854897        } else {
    855898            $q['author'] = ''.urldecode($q['author']).'';
    856899            $q['author'] = addslashes_gpc($q['author']);
    857             if (stristr($q['author'], '-')) {
     900            if (strpos($q['author'], '-') !== false) {
    858901                $eq = '!=';
    859902                $andor = 'AND';
     
    875918
    876919        if ('' != $q['author_name']) {
    877             if (stristr($q['author_name'],'/')) {
     920            if (strpos($q['author_name'], '/') !== false) {
    878921                $q['author_name'] = explode('/',$q['author_name']);
    879922                if ($q['author_name'][count($q['author_name'])-1]) {
     
    890933        $where .= $search.$whichcat.$whichauthor;
    891934
    892         if ((empty($q['order'])) || ((strtoupper($q['order']) != 'ASC') && (strtoupper($q['order']) != 'DESC'))) {
    893             $q['order']='DESC';
    894         }
     935        if ( empty($q['order']) || ((strtoupper($q['order']) != 'ASC') && (strtoupper($q['order']) != 'DESC')) )
     936            $q['order'] = 'DESC';
    895937
    896938        // Order by
    897         if (empty($q['orderby'])) {
     939        if ( empty($q['orderby']) ) {
    898940            $q['orderby'] = 'post_date '.$q['order'];
    899941        } else {
     
    951993
    952994        // Paging
    953         if (empty($q['nopaging']) && !$this->is_singular) {
     995        if ( empty($q['nopaging']) && !$this->is_singular ) {
    954996            $page = abs(intval($q['paged']));
    955997            if (empty($page)) {
     
    9661008                $limits = 'LIMIT ' . $pgstrt . $q['posts_per_page'];
    9671009            }
     1010        }
     1011
     1012        // Comments feeds
     1013        if ( $this->is_comment_feed && ( $this->is_archive || $this->is_search || !$this->is_singular ) ) {
     1014            if ( $this->is_archive || $this->is_search ) {
     1015                $cjoin = "LEFT JOIN $wpdb->posts ON ($wpdb->comments.comment_post_ID = $wpdb->posts.ID) $join ";
     1016                $cwhere = "WHERE comment_approved = '1' $where";
     1017                $cgroupby = "GROUP BY $wpdb->comments.comment_id";
     1018            } else { // Other non singular e.g. front
     1019                $cjoin = "LEFT JOIN $wpdb->posts ON ( $wpdb->comments.comment_post_ID = $wpdb->posts.ID )";
     1020                $cwhere = "WHERE post_status = 'publish' AND comment_approved = '1'";
     1021                $cgroupby = '';
     1022            }
     1023
     1024            $cjoin = apply_filters('comment_feed_join', $cjoin);
     1025            $cwhere = apply_filters('comment_feed_where', $cwhere);
     1026            $cgroupby = apply_filters('comment_feed_groupby', $cgroupby);
     1027
     1028            $this->comments = (array) $wpdb->get_results("SELECT $distinct $wpdb->comments.* FROM $wpdb->comments $cjoin $cwhere $cgroupby ORDER BY comment_date_gmt DESC LIMIT " . get_option('posts_per_rss'));
     1029            $this->comment_count = count($this->comments);
     1030
     1031            $post_ids = array();
     1032
     1033            foreach ($this->comments as $comment)
     1034                $post_ids[] = (int) $comment->comment_post_ID;
     1035
     1036            $post_ids = join(',', $post_ids);
     1037            $join = '';
     1038            if ( $post_ids )
     1039                $where = "AND $wpdb->posts.ID IN ($post_ids) ";
     1040            else
     1041                $where = "AND 0";
    9681042        }
    9691043
     
    9871061
    9881062        $this->posts = $wpdb->get_results($this->request);
     1063
     1064        if ( $this->is_comment_feed && $this->is_singular ) {
     1065            $cjoin = apply_filters('comment_feed_join', '');
     1066            $cwhere = apply_filters('comment_feed_where', "WHERE comment_post_ID = {$this->posts[0]->ID} AND comment_approved = '1'");
     1067            $comments_request = "SELECT $wpdb->comments.* FROM $wpdb->comments $cjoin $cwhere ORDER BY comment_date_gmt DESC LIMIT " . get_option('posts_per_rss');
     1068            $this->comments = $wpdb->get_results($comments_request);
     1069            $this->comment_count = count($this->comments);
     1070        }
     1071
    9891072        if ( !empty($limits) ) {
    9901073            $found_posts_query = apply_filters( 'found_posts_query', 'SELECT FOUND_ROWS()' );
     
    9931076            $this->max_num_pages = ceil($this->found_posts / $q['posts_per_page']);
    9941077        }
     1078
    9951079        // Check post status to determine if post should be displayed.
    9961080        if ( !empty($this->posts) && ($this->is_single || $this->is_page) ) {
     
    10731157    }
    10741158
     1159    function next_comment() {
     1160        $this->current_comment++;
     1161
     1162        $this->comment = $this->comments[$this->current_comment];
     1163        return $this->comment;
     1164    }
     1165
     1166    function the_comment() {
     1167        global $comment;
     1168
     1169        $comment = $this->next_comment();
     1170
     1171        if ($this->current_comment == 0) {
     1172            do_action('comment_loop_start');
     1173        }
     1174    }
     1175
     1176    function have_comments() {
     1177        if ($this->current_comment + 1 < $this->comment_count) {
     1178            return true;
     1179        } elseif ($this->current_comment + 1 == $this->comment_count) {
     1180            $this->rewind_comments();
     1181        }
     1182
     1183        return false;
     1184    }
     1185
     1186    function rewind_comments() {
     1187        $this->current_comment = -1;
     1188        if ($this->comment_count > 0) {
     1189            $this->comment = $this->comments[0];
     1190        }
     1191    }
     1192
    10751193    function &query($query) {
    10761194        $this->parse_query($query);
     
    10901208            $category = &get_category($cat);
    10911209            $this->queried_object = &$category;
    1092             $this->queried_object_id = $cat;
     1210            $this->queried_object_id = (int) $cat;
    10931211        } else if ($this->is_posts_page) {
    10941212            $this->queried_object = & get_page(get_option('page_for_posts'));
    1095             $this->queried_object_id = $this->queried_object->ID;
     1213            $this->queried_object_id = (int) $this->queried_object->ID;
    10961214        } else if ($this->is_single) {
    10971215            $this->queried_object = $this->post;
    1098             $this->queried_object_id = $this->post->ID;
     1216            $this->queried_object_id = (int) $this->post->ID;
    10991217        } else if ($this->is_page) {
    11001218            $this->queried_object = $this->post;
    1101             $this->queried_object_id = $this->post->ID;
     1219            $this->queried_object_id = (int) $this->post->ID;
    11021220        } else if ($this->is_author) {
    1103             $author_id = $this->get('author');
     1221            $author_id = (int) $this->get('author');
    11041222            $author = get_userdata($author_id);
    11051223            $this->queried_object = $author;
     
    11701288    global $pagenow;
    11711289
    1172     $id = $post->ID;
     1290    $id = (int) $post->ID;
    11731291
    11741292    $authordata = get_userdata($post->post_author);
  • tags/2.2/wp-includes/registration-functions.php

    • Property svn:eol-style set to native
  • tags/2.2/wp-includes/rewrite.php

    r5468 r5480  
    5151//pseudo-places
    5252define('EP_NONE',       0  );
    53 define('EP_ALL',        255);
     53define('EP_ALL',        4095);
    5454
    5555//and an endpoint, like /trackback/
     
    6363function url_to_postid($url) {
    6464    global $wp_rewrite;
     65   
     66    $url = apply_filters('url_to_postid', $url);
    6567
    6668    // First, check to see if there is a 'p=N' or 'page_id=N' to match against
     
    149151class WP_Rewrite {
    150152    var $permalink_structure;
     153    var $use_trailing_slashes;
    151154    var $category_base;
    152155    var $category_structure;
     
    582585                $rewrite = array_merge($rewrite, array($pagematch => $pagequery));
    583586
     587            //do endpoints
     588            if ($endpoints) {
     589                foreach ($ep_query_append as $regex => $ep) {
     590                    //add the endpoints on if the mask fits
     591                    if ($ep[0] & $ep_mask || $ep[0] & $ep_mask_specific) {
     592                        $rewrite[$match . $regex] = $index . '?' . $query . $ep[1] . $this->preg_index($num_toks + 2);
     593                    }
     594                }
     595            }
     596
    584597            //if we've got some tags in this dir
    585598            if ($num_toks) {
     
    591604                //2) post ID, 3) page name, 4) timestamp (year, month, day, hour, second and
    592605                //minute all present). Set these flags now as we need them for the endpoints.
    593                 if (strstr($struct, '%postname%') || strstr($struct, '%post_id%')
    594                         || strstr($struct, '%pagename%')
    595                         || (strstr($struct, '%year%') &&  strstr($struct, '%monthnum%') && strstr($struct, '%day%') && strstr($struct, '%hour%') && strstr($struct, '%minute') && strstr($struct, '%second%'))) {
     606                if (strpos($struct, '%postname%') !== false || strpos($struct, '%post_id%') !== false
     607                        || strpos($struct, '%pagename%') !== false
     608                        || (strpos($struct, '%year%') !== false && strpos($struct, '%monthnum%') !== false && strpos($struct, '%day%') !== false && strpos($struct, '%hour%') !== false && strpos($struct, '%minute%') !== false && strpos($struct, '%second%') !== false)) {
    596609                    $post = true;
    597                     if  ( strstr($struct, '%pagename%') )
     610                    if (strpos($struct, '%pagename%') !== false)
    598611                        $page = true;
    599                 }
    600 
    601                 //do endpoints
    602                 if ($endpoints) {
    603                     foreach ($ep_query_append as $regex => $ep) {
    604                         //add the endpoints on if the mask fits
    605                         if ($ep[0] & $ep_mask || $ep[0] & $ep_mask_specific) {
    606                             $rewrite[$match . $regex] = $index . '?' . $query . $ep[1] . $this->preg_index($num_toks + 2);
    607                         }
    608                     }
    609612                }
    610613
     
    809812                }
    810813
    811                 if (strstr($query, $this->index)) {
     814                if (strpos($query, $this->index) !== false) {
    812815                    $rules .= 'RewriteRule ^' . $match . ' ' . $home_root . $query . " [QSA,L]\n";
    813816                } else {
     
    877880        unset($this->feed_structure);
    878881        unset($this->comment_feed_structure);
     882        $this->use_trailing_slashes = ( substr($this->permalink_structure, -1, 1) == '/' ) ? true : false;
    879883    }
    880884
  • tags/2.2/wp-includes/rss-functions.php

    • Property svn:eol-style set to native
  • tags/2.2/wp-includes/script-loader.php

    r5468 r5480  
    1414        $this->add( 'fat', '/wp-includes/js/fat.js', false, '1.0-RC1_3660' );
    1515        $this->add( 'sack', '/wp-includes/js/tw-sack.js', false, '1.6.1' );
    16         $this->add( 'quicktags', '/wp-includes/js/quicktags.js', false, '3517' );
     16        $this->add( 'quicktags', '/wp-includes/js/quicktags.js', false, '3958' );
     17        $this->localize( 'quicktags', 'quicktagsL10n', array(
     18            'quickLinks' => __('(Quick Links)'),
     19            'wordLookup' => __('Enter a word to look up:'),
     20            'dictionaryLookup' => attribute_escape(__('Dictionary lookup')),
     21            'lookup' => attribute_escape(__('lookup')),
     22            'closeAllOpenTags' => attribute_escape(__('Close all open tags')),
     23            'closeTags' => attribute_escape(__('close tags')),
     24            'enterURL' => __('Enter the URL'),
     25            'enterImageURL' => __('Enter the URL of the image'),
     26            'enterImageDescription' => __('Enter a description of the image')
     27        ) );
    1728        $this->add( 'colorpicker', '/wp-includes/js/colorpicker.js', false, '3517' );
    18         $this->add( 'tiny_mce', '/wp-includes/js/tinymce/tiny_mce_gzip.php', false, '20061113' );
     29        $this->add( 'tiny_mce', '/wp-includes/js/tinymce/tiny_mce_gzip.php', false, '20070326' );
    1930        $mce_config = apply_filters('tiny_mce_config_url', '/wp-includes/js/tinymce/tiny_mce_config.php');
    2031        $this->add( 'wp_tiny_mce', $mce_config, array('tiny_mce'), '20070225' );
    21         $this->add( 'prototype', '/wp-includes/js/prototype.js', false, '1.5.0');
    22         $this->add( 'autosave', '/wp-includes/js/autosave-js.php', array('prototype', 'sack'), '20070116');
    23         $this->add( 'wp-ajax', '/wp-includes/js/wp-ajax-js.php', array('prototype'), '20070118');
    24         $this->add( 'listman', '/wp-includes/js/list-manipulation-js.php', array('wp-ajax', 'fat'), '20070118');
    25         $this->add( 'scriptaculous-root', '/wp-includes/js/scriptaculous/wp-scriptaculous.js', array('prototype'), '1.6.1');
    26         $this->add( 'scriptaculous-builder', '/wp-includes/js/scriptaculous/builder.js', array('scriptaculous-root'), '1.6.1');
    27         $this->add( 'scriptaculous-dragdrop', '/wp-includes/js/scriptaculous/dragdrop.js', array('scriptaculous-builder'), '1.6.1');
    28         $this->add( 'scriptaculous-effects', '/wp-includes/js/scriptaculous/effects.js', array('scriptaculous-root'), '1.6.1');
    29         $this->add( 'scriptaculous-slider', '/wp-includes/js/scriptaculous/slider.js', array('scriptaculous-effects'), '1.6.1');
    30         $this->add( 'scriptaculous-controls', '/wp-includes/js/scriptaculous/controls.js', array('scriptaculous-root'), '1.6.1');
    31         $this->add( 'scriptaculous', '', array('scriptaculous-dragdrop', 'scriptaculous-slider', 'scriptaculous-controls'), '1.6.1');
     32        $this->add( 'prototype', '/wp-includes/js/prototype.js', false, '1.5.0-0');
     33        $this->add( 'autosave', '/wp-includes/js/autosave.js', array('prototype', 'sack'), '20070306');
     34        $this->localize( 'autosave', 'autosaveL10n', array(
     35            'autosaveInterval' => apply_filters('autosave_interval', '120'),
     36            'errorText' => __('Error: %response%'),
     37            'saveText' => __('Saved at %time%.'),
     38            'requestFile' => get_option( 'siteurl' ) . '/wp-admin/admin-ajax.php',
     39            'savingText' => __('Saving Draft...')
     40        ) );
     41        $this->add( 'wp-ajax', '/wp-includes/js/wp-ajax.js', array('prototype'), '20070306');
     42        $this->localize( 'wp-ajax', 'WPAjaxL10n', array(
     43            'defaultUrl' => get_option( 'siteurl' ) . '/wp-admin/admin-ajax.php',
     44            'permText' => __("You don't have permission to do that."),
     45            'strangeText' => __("Something strange happened.  Try refreshing the page."),
     46            'whoaText' => __("Slow down, I'm still sending your data!")
     47        ) );
     48        $this->add( 'listman', '/wp-includes/js/list-manipulation.js', array('wp-ajax', 'fat'), '20070306' );
     49        $this->localize( 'listman', 'listManL10n', array(
     50            'jumpText' => __('Jump to new item'),
     51            'delText' => __('Are you sure you want to delete this %thing%?')
     52        ) );
     53        $this->add( 'scriptaculous-root', '/wp-includes/js/scriptaculous/wp-scriptaculous.js', array('prototype'), '1.7.0');
     54        $this->add( 'scriptaculous-builder', '/wp-includes/js/scriptaculous/builder.js', array('scriptaculous-root'), '1.7.0');
     55        $this->add( 'scriptaculous-dragdrop', '/wp-includes/js/scriptaculous/dragdrop.js', array('scriptaculous-builder', 'scriptaculous-effects'), '1.7.0');
     56        $this->add( 'scriptaculous-effects', '/wp-includes/js/scriptaculous/effects.js', array('scriptaculous-root'), '1.7.0');
     57        $this->add( 'scriptaculous-slider', '/wp-includes/js/scriptaculous/slider.js', array('scriptaculous-effects'), '1.7.0');
     58        $this->add( 'scriptaculous-controls', '/wp-includes/js/scriptaculous/controls.js', array('scriptaculous-root'), '1.7.0');
     59        $this->add( 'scriptaculous', '', array('scriptaculous-dragdrop', 'scriptaculous-slider', 'scriptaculous-controls'), '1.7.0');
    3260        $this->add( 'cropper', '/wp-includes/js/crop/cropper.js', array('scriptaculous-dragdrop'), '20070118');
     61        $this->add( 'jquery', '/wp-includes/js/jquery/jquery.js', false, '1.1.2');
     62        $this->add( 'interface', '/wp-includes/js/jquery/interface.js', array('jquery'), '1.2');
    3363        if ( is_admin() ) {
    34             $this->add( 'dbx-admin-key', '/wp-admin/dbx-admin-key-js.php', array('dbx'), '3651' );
    35             $this->add( 'ajaxcat', '/wp-admin/cat-js.php', array('listman'), '20070118' );
     64            global $pagenow;
     65            $man = false;
     66            switch ( $pagenow ) :
     67            case 'post.php' :
     68            case 'post-new.php' :
     69                $man = 'postmeta';
     70                break;
     71            case 'page.php' :
     72            case 'page-new.php' :
     73                $man = 'pagemeta';
     74                break;
     75            case 'link-add.php' :
     76            case 'link.php' :
     77                $man = 'linkmeta';
     78                break;
     79            endswitch;
     80            if ( $man ) {
     81                $this->add( 'dbx-admin-key', '/wp-admin/dbx-admin-key.js', array('dbx'), '20070417' );
     82                $this->localize( 'dbx-admin-key', 'dbxL10n', array(
     83                    'manager' => $man,
     84                    'open' => __('open'),
     85                    'close' => __('close'),
     86                    'moveMouse' => __('click-down and drag to move this box'),
     87                    'toggleMouse' => __('click to %toggle% this box'),
     88                    'moveKey' => __('use the arrow keys to move this box'),
     89                    'toggleKey' => __(', or press the enter key to %toggle% it'),
     90                ) );
     91            }
     92            $this->add( 'ajaxcat', '/wp-admin/cat.js', array('listman'), '20070417' );
     93            $this->localize( 'ajaxcat', 'catL10n', array(
     94                'add' => attribute_escape(__('Add')),
     95                'how' => __('Separate multiple categories with commas.')
     96            ) );
    3697            $this->add( 'admin-categories', '/wp-admin/categories.js', array('listman'), '3684' );
    3798            $this->add( 'admin-custom-fields', '/wp-admin/custom-fields.js', array('listman'), '3733' );
    38             $this->add( 'admin-comments', '/wp-admin/edit-comments.js', array('listman'), '3847' );
     99            $this->add( 'admin-comments', '/wp-admin/edit-comments.js', array('listman'), '20070327' );
    39100            $this->add( 'admin-users', '/wp-admin/users.js', array('listman'), '4583' );
    40101            $this->add( 'xfn', '/wp-admin/xfn.js', false, '3517' );
    41             $this->add( 'upload', '/wp-admin/upload-js.php', array('prototype'), '20070118' );
     102            $this->add( 'upload', '/wp-admin/upload.js', array('prototype'), '20070306' );
     103            $this->localize( 'upload', 'uploadL10n', array(
     104                'browseTitle' => attribute_escape(__('Browse your files')),
     105                'back' => __('&laquo; Back'),
     106                'directTitle' => attribute_escape(__('Direct link to file')),
     107                'edit' => __('Edit'),
     108                'thumb' => __('Thumbnail'),
     109                'full' => __('Full size'),
     110                'icon' => __('Icon'),
     111                'title' => __('Title'),
     112                'show' => __('Show:'),
     113                'link' => __('Link to:'),
     114                'file' => __('File'),
     115                'page' => __('Page'),
     116                'none' => __('None'),
     117                'editorText' => attribute_escape(__('Send to editor &raquo;')),
     118                'insert' => __('Insert'),
     119                'urlText' => __('URL'),
     120                'desc' => __('Description'),
     121                'deleteText' => attribute_escape(__('Delete File')),
     122                'saveText' => attribute_escape(__('Save &raquo;')),
     123                'confirmText' => __("Are you sure you want to delete the file '%title%'?\nClick ok to delete or cancel to go back.")
     124            ) );
    42125        }
    43126    }
     
    79162                        $ver .= '&amp;' . $this->args[$handle];
    80163                    $src = 0 === strpos($this->scripts[$handle]->src, 'http://') ? $this->scripts[$handle]->src : get_option( 'siteurl' ) . $this->scripts[$handle]->src;
    81                     $src = clean_url(add_query_arg('ver', $ver, $src));
     164                    $src = $this->scripts[$handle]->src;
     165                   
     166                    if (!preg_match('|^https?://|', $src)) {
     167                        $src = get_option('siteurl') . $src;
     168                    }
     169                   
     170                    $src = add_query_arg('ver', $ver, $src);
     171                    $src = clean_url(apply_filters( 'script_loader_src', $src ));
    82172                    echo "<script type='text/javascript' src='$src'></script>\n";
     173                    $this->print_scripts_l10n( $handle );
    83174                }
    84175                $this->printed[] = $handle;
     
    87178    }
    88179
     180    function print_scripts_l10n( $handle ) {
     181        if ( empty($this->scripts[$handle]->l10n_object) || empty($this->scripts[$handle]->l10n) || !is_array($this->scripts[$handle]->l10n) )
     182            return;
     183
     184        $object_name = $this->scripts[$handle]->l10n_object;
     185
     186        echo "<script type='text/javascript'>\n";
     187        echo "/* <![CDATA[ */\n";
     188        echo "\t$object_name = {\n";
     189        $eol = '';
     190        foreach ( $this->scripts[$handle]->l10n as $var => $val ) {
     191            echo "$eol\t\t$var: \"" . js_escape( $val ) . '"';
     192            $eol = ",\n";
     193        }
     194        echo "\n\t}\n";
     195        echo "/* ]]> */\n";
     196        echo "</script>\n";
     197    }
    89198
    90199    /**
     
    138247    }
    139248
     249    /**
     250     * Localizes a script
     251     *
     252     * Localizes only if script has already been added
     253     *
     254     * @param string handle Script name
     255     * @param string object_name Name of JS object to hold l10n info
     256     * @param array l10n Array of JS var name => localized string
     257     * @return bool Successful localization
     258     */
     259    function localize( $handle, $object_name, $l10n ) {
     260        if ( !isset($this->scripts[$handle]) )
     261            return false;
     262        return $this->scripts[$handle]->localize( $object_name, $l10n );
     263    }
     264
    140265    function remove( $handles ) {
    141266        foreach ( (array) $handles as $handle )
     
    180305    var $deps = array();
    181306    var $ver = false;
    182     var $args = false;
     307    var $l10n_object = '';
     308    var $l10n = array();
    183309
    184310    function _WP_Script() {
     
    189315            $this->ver = false;
    190316    }
     317
     318    function localize( $object_name, $l10n ) {
     319        if ( !$object_name || !is_array($l10n) )
     320            return false;
     321        $this->l10n_object = $object_name;
     322        $this->l10n = $l10n;
     323        return true;
     324    }
    191325}
    192326
     
    225359}
    226360
     361/**
     362 * Localizes a script
     363 *
     364 * Localizes only if script has already been added
     365 *
     366 * @see WP_Script::localize()
     367 */
     368function wp_localize_script( $handle, $object_name, $l10n ) {
     369    global $wp_scripts;
     370    if ( !is_a($wp_scripts, 'WP_Scripts') )
     371        return false;
     372
     373    return $wp_scripts->localize( $handle, $object_name, $l10n );
     374}
     375
    227376function wp_deregister_script( $handle ) {
    228377    global $wp_scripts;
  • tags/2.2/wp-includes/template-loader.php

    r5468 r5480  
    44    if ( is_robots() ) {
    55        do_action('do_robots');
    6         exit;
     6        return;
    77    } else if ( is_feed() ) {
    88        do_feed();
    9         exit;
     9        return;
    1010    } else if ( is_trackback() ) {
    1111        include(ABSPATH . '/wp-trackback.php');
    12         exit;
     12        return;
    1313    } else if ( is_404() && $template = get_404_template() ) {
    1414        include($template);
    15         exit;
     15        return;
    1616    } else if ( is_search() && $template = get_search_template() ) {
    1717        include($template);
    18         exit;
     18        return;
    1919    } else if ( is_home() && $template = get_home_template() ) {
    2020        include($template);
    21         exit;
     21        return;
    2222    } else if ( is_attachment() && $template = get_attachment_template() ) {
    2323        include($template);
    24         exit;
     24        return;
    2525    } else if ( is_single() && $template = get_single_template() ) {
    2626        if ( is_attachment() )
    2727            add_filter('the_content', 'prepend_attachment');
    2828        include($template);
    29         exit;
     29        return;
    3030    } else if ( is_page() && $template = get_page_template() ) {
    3131        if ( is_attachment() )
    3232            add_filter('the_content', 'prepend_attachment');
    3333        include($template);
    34         exit;
     34        return;
    3535    } else if ( is_category() && $template = get_category_template()) {
    3636        include($template);
    37         exit;
     37        return;
    3838    } else if ( is_author() && $template = get_author_template() ) {
    3939        include($template);
    40         exit;
     40        return;
    4141    } else if ( is_date() && $template = get_date_template() ) {
    4242        include($template);
    43         exit;
     43        return;
    4444    } else if ( is_archive() && $template = get_archive_template() ) {
    4545        include($template);
    46         exit;
     46        return;
    4747    } else if ( is_comments_popup() && $template = get_comments_popup_template() ) {
    4848        include($template);
    49         exit;
     49        return;
    5050    } else if ( is_paged() && $template = get_paged_template() ) {
    5151        include($template);
    52         exit;
     52        return;
    5353    } else if ( file_exists(TEMPLATEPATH . "/index.php") ) {
    5454        if ( is_attachment() )
    5555            add_filter('the_content', 'prepend_attachment');
    5656        include(TEMPLATEPATH . "/index.php");
    57         exit;
     57        return;
    5858    }
    5959} else {
     
    6161    if ( is_robots() ) {
    6262        do_action('do_robots');
    63         exit;
     63        return;
    6464    } else if ( is_feed() ) {
    6565        do_feed();
    66         exit;
     66        return;
    6767    } else if ( is_trackback() ) {
    6868        include(ABSPATH . '/wp-trackback.php');
    69         exit;
     69        return;
    7070    }
    7171}
  • tags/2.2/wp-includes/theme.php

    r5468 r5480  
    7979    $name = trim( $name );
    8080    $theme = $name;
     81    $theme_uri = trim( $theme_uri[1] );
    8182
    8283    if ( '' == $author_uri[1] ) {
     
    8687    }
    8788
    88     return array( 'Name' => $name, 'Title' => $theme, 'Description' => $description, 'Author' => $author, 'Version' => $version, 'Template' => $template[1], 'Status' => $status );
     89    return array( 'Name' => $name, 'Title' => $theme, 'URI' => $theme_uri, 'Description' => $description, 'Author' => $author, 'Version' => $version, 'Template' => $template[1], 'Status' => $status );
    8990}
    9091
     
    163164        $stylesheet  = dirname($theme_file);
    164165
     166        $screenshot = false;
    165167        foreach ( array('png', 'gif', 'jpg', 'jpeg') as $ext ) {
    166168            if (file_exists("$theme_root/$stylesheet/screenshot.$ext")) {
     
    187189            $parent_dir = dirname(dirname($theme_file));
    188190            if ( file_exists("$theme_root/$parent_dir/$template/index.php") ) {
    189                 $template = "$parent_dir/$template";    
     191                $template = "$parent_dir/$template";
    190192            } else {
    191193                $wp_broken_themes[$name] = array('Name' => $name, 'Title' => $title, 'Description' => __('Template is missing.'));
     
    441443
    442444    if ( isset($mods[$name]) )
    443         return $mods[$name];
    444 
    445     return sprintf($default, get_template_directory_uri());
     445        return apply_filters( "theme_mod_$name", $mods[$name] );
     446
     447    return apply_filters( "theme_mod_$name", sprintf($default, get_template_directory_uri()) );
    446448}
    447449
     
    485487
    486488function header_textcolor() {
    487     echo get_header_textcolor();   
     489    echo get_header_textcolor();
    488490}
    489491
     
    493495
    494496function header_image() {
    495     echo get_header_image();   
     497    echo get_header_image();
    496498}
    497499
  • tags/2.2/wp-includes/user.php

    r5468 r5480  
    1111    global $wpdb;
    1212    $userid = (int) $userid;
    13     return $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = '$userid' AND post_type = 'post' AND post_status = 'publish'");
     13    return $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = '$userid' AND post_type = 'post' AND " . get_private_posts_cap_sql('post'));
    1414}
    1515
     
    5050        $option_name = $wpdb->prefix . $option_name;
    5151    return update_usermeta( $user_id, $option_name, $newvalue );
     52}
     53
     54// Get users with capabilities for the current blog.
     55// For setups that use the multi-blog feature.
     56function get_users_of_blog( $id = '' ) {
     57    global $wpdb, $blog_id;
     58    if ( empty($id) )
     59        $id = (int) $blog_id;
     60    $users = $wpdb->get_results( "SELECT user_id, user_login, display_name, user_email, meta_value FROM $wpdb->users, $wpdb->usermeta WHERE " . $wpdb->users . ".ID = " . $wpdb->usermeta . ".user_id AND meta_key = '" . $wpdb->prefix . "capabilities' ORDER BY {$wpdb->usermeta}.user_id" );
     61    return $users;
    5262}
    5363
  • tags/2.2/wp-includes/vars.php

    r5468 r5480  
    1414
    1515// Simple browser detection
    16 // We should probably be doing true/false instead of 1/0 here ~ Mark
    17 $is_lynx = 0; $is_gecko = 0; $is_winIE = 0; $is_macIE = 0; $is_opera = 0; $is_NS4 = 0;
     16$is_lynx = $is_gecko = $is_winIE = $is_macIE = $is_opera = $is_NS4 = false;
    1817
    19 if ( preg_match('/Lynx/', $_SERVER['HTTP_USER_AGENT']) )
    20     $is_lynx = 1;
    21 elseif ( preg_match('/Gecko/', $_SERVER['HTTP_USER_AGENT']) )
    22     $is_gecko = 1;
    23 elseif ( preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT']) && preg_match('/Win/', $_SERVER['HTTP_USER_AGENT']) )
    24     $is_winIE = 1;
    25 elseif ( preg_match('/MSIE/', $_SERVER['HTTP_USER_AGENT']) && preg_match('/Mac/', $_SERVER['HTTP_USER_AGENT']) )
    26     $is_macIE = 1;
    27 elseif ( preg_match('/Opera/', $_SERVER['HTTP_USER_AGENT']) )
    28     $is_opera = 1;
    29 elseif ( preg_match('/Nav/', $_SERVER['HTTP_USER_AGENT']) || preg_match('/Mozilla\/4\./', $_SERVER['HTTP_USER_AGENT']) )
    30     $is_NS4 = 1;
     18if (strpos($_SERVER['HTTP_USER_AGENT'], 'Lynx') !== false) {
     19    $is_lynx = true;
     20} elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Gecko') !== false) {
     21    $is_gecko = true;
     22} elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false && strpos($_SERVER['HTTP_USER_AGENT'], 'Win') !== false) {
     23    $is_winIE = true;
     24} elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false && strpos($_SERVER['HTTP_USER_AGENT'], 'Mac') !== false) {
     25    $is_macIE = true;
     26} elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Opera') !== false) {
     27    $is_opera = true;
     28} elseif (strpos($_SERVER['HTTP_USER_AGENT'], 'Nav') !== false && strpos($_SERVER['HTTP_USER_AGENT'], 'Mozilla/4.') !== false) {
     29    $is_NS4 = true;
     30}
    3131
    3232$is_IE = ( $is_macIE || $is_winIE );
    3333
    3434// Server detection
    35 $is_apache = ( strstr($_SERVER['SERVER_SOFTWARE'], 'Apache') || strstr($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') ) ? 1 : 0;
    36 $is_IIS = strstr($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS') ? 1 : 0;
    37 
    38 // if the config file does not provide the smilies array, let's define it here
    39 if (!isset($wpsmiliestrans)) {
    40     $wpsmiliestrans = array(
    41     ':mrgreen:' => 'icon_mrgreen.gif',
    42     ':neutral:' => 'icon_neutral.gif',
    43     ':twisted:' => 'icon_twisted.gif',
    44       ':arrow:' => 'icon_arrow.gif',
    45       ':shock:' => 'icon_eek.gif',
    46       ':smile:' => 'icon_smile.gif',
    47         ':???:' => 'icon_confused.gif',
    48        ':cool:' => 'icon_cool.gif',
    49        ':evil:' => 'icon_evil.gif',
    50        ':grin:' => 'icon_biggrin.gif',
    51        ':idea:' => 'icon_idea.gif',
    52        ':oops:' => 'icon_redface.gif',
    53        ':razz:' => 'icon_razz.gif',
    54        ':roll:' => 'icon_rolleyes.gif',
    55        ':wink:' => 'icon_wink.gif',
    56         ':cry:' => 'icon_cry.gif',
    57         ':eek:' => 'icon_surprised.gif',
    58         ':lol:' => 'icon_lol.gif',
    59         ':mad:' => 'icon_mad.gif',
    60         ':sad:' => 'icon_sad.gif',
    61           '8-)' => 'icon_cool.gif',
    62           '8-O' => 'icon_eek.gif',
    63           ':-(' => 'icon_sad.gif',
    64           ':-)' => 'icon_smile.gif',
    65           ':-?' => 'icon_confused.gif',
    66           ':-D' => 'icon_biggrin.gif',
    67           ':-P' => 'icon_razz.gif',
    68           ':-o' => 'icon_surprised.gif',
    69           ':-x' => 'icon_mad.gif',
    70           ':-|' => 'icon_neutral.gif',
    71           ';-)' => 'icon_wink.gif',
    72            '8)' => 'icon_cool.gif',
    73            '8O' => 'icon_eek.gif',
    74            ':(' => 'icon_sad.gif',
    75            ':)' => 'icon_smile.gif',
    76            ':?' => 'icon_confused.gif',
    77            ':D' => 'icon_biggrin.gif',
    78            ':P' => 'icon_razz.gif',
    79            ':o' => 'icon_surprised.gif',
    80            ':x' => 'icon_mad.gif',
    81            ':|' => 'icon_neutral.gif',
    82            ';)' => 'icon_wink.gif',
    83           ':!:' => 'icon_exclaim.gif',
    84           ':?:' => 'icon_question.gif',
    85     );
    86 }
    87 
    88 // generates smilies' search & replace arrays
    89 foreach ( (array) $wpsmiliestrans as $smiley => $img ) {
    90     $wp_smiliessearch[] = '/(\s|^)'.preg_quote($smiley, '/').'(\s|$)/';
    91     $smiley_masked = htmlspecialchars(trim($smiley), ENT_QUOTES);
    92     $wp_smiliesreplace[] = " <img src='" . get_option('siteurl') . "/wp-includes/images/smilies/$img' alt='$smiley_masked' class='wp-smiley' /> ";
    93 }
     35$is_apache = ((strpos($_SERVER['SERVER_SOFTWARE'], 'Apache') !== false) || (strpos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false)) ? true : false;
     36$is_IIS = (strpos($_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS') !== false) ? true : false;
    9437
    9538?>
  • tags/2.2/wp-includes/version.php

    r5468 r5480  
    33// This holds the version number in a separate file so we can bump it without cluttering the SVN
    44
    5 $wp_version = '2.1.3';
    6 $wp_db_version = 4773;
     5$wp_version = '2.2';
     6$wp_db_version = 5183;
    77
    88?>
  • tags/2.2/wp-includes/wp-db.php

    r5468 r5480  
    3636    var $postmeta;
    3737
     38    var $charset;
     39    var $collate;
     40
    3841    /**
    3942     * Connects to the database server and selects a database
     
    4649        return $this->__construct($dbuser, $dbpassword, $dbname, $dbhost);
    4750    }
    48    
     51
    4952    function __construct($dbuser, $dbpassword, $dbname, $dbhost) {
    5053        register_shutdown_function(array(&$this, "__destruct"));
     54
     55        if ( defined('DB_CHARSET') )
     56            $this->charset = DB_CHARSET;
     57
     58        if ( defined('DB_COLLATE') )
     59            $this->collate = DB_COLLATE;
    5160
    5261        $this->dbh = @mysql_connect($dbhost, $dbuser, $dbpassword);
     
    6473        }
    6574
     75        if ( !empty($this->charset) && version_compare(mysql_get_server_info(), '4.1.0', '>=') )
     76            $this->query("SET NAMES '$this->charset'");
     77
    6678        $this->select($dbname);
    6779    }
    6880
    6981    function __destruct() {
    70         return true;       
     82        return true;   
    7183    }
    7284
     
    170182        $this->result = @mysql_query($query, $this->dbh);
    171183        ++$this->num_queries;
    172    
     184
    173185        if (SAVEQUERIES)
    174186            $this->queries[] = array( $query, $this->timer_stop() );
     
    181193
    182194        if ( preg_match("/^\\s*(insert|delete|update|replace) /i",$query) ) {
    183             $this->rows_affected = mysql_affected_rows();
     195            $this->rows_affected = mysql_affected_rows($this->dbh);
    184196            // Take note of the insert_id
    185197            if ( preg_match("/^\\s*(insert|replace) /i",$query) ) {
     
    244256        if ( $query )
    245257            $this->query($query);
    246        
     258   
    247259        if ( !isset($this->last_result[$y]) )
    248260            return null;
     
    361373        header('Content-Type: text/html; charset=utf-8');
    362374
    363         if ( strstr($_SERVER['PHP_SELF'], 'wp-admin') )
     375        if (strpos($_SERVER['PHP_SELF'], 'wp-admin') !== false)
    364376            $admin_dir = '';
    365377        else
  • tags/2.2/wp-links-opml.php

    r5468 r5480  
    1818<opml version="1.0">
    1919    <head>
    20         <title>Links for <?php echo get_bloginfo('name').$cat_name ?></title>
     20        <title>Links for <?php echo attribute_escape(get_bloginfo('name').$cat_name); ?></title>
    2121        <dateCreated><?php echo gmdate("D, d M Y H:i:s"); ?> GMT</dateCreated>
    2222    </head>
     
    3030
    3131foreach ((array) $cats as $cat) {
     32    $catname = apply_filters('link_category', $cat->cat_name);
     33
    3234?>
    33 <outline type="category" title="<?php echo attribute_escape($cat->cat_name); ?>">
     35<outline type="category" title="<?php echo attribute_escape($catname); ?>">
    3436<?php
    3537
    3638    $bookmarks = get_bookmarks("category={$cat->cat_ID}");
    3739    foreach ((array) $bookmarks as $bookmark) {
     40        $title = attribute_escape(apply_filters('link_title', $bookmark->link_name));
    3841?>
    39     <outline text="<?php echo attribute_escape($bookmark->link_name); ?>" type="link" xmlUrl="<?php echo attribute_escape($bookmark->link_rss); ?>" htmlUrl="<?php echo attribute_escape($bookmark->link_url); ?>" updated="<?php if ('0000-00-00 00:00:00' != $bookmark->link_updated) echo $bookmark->link_updated; ?>" />
     42    <outline text="<?php echo $title; ?>" type="link" xmlUrl="<?php echo attribute_escape($bookmark->link_rss); ?>" htmlUrl="<?php echo attribute_escape($bookmark->link_url); ?>" updated="<?php if ('0000-00-00 00:00:00' != $bookmark->link_updated) echo $bookmark->link_updated; ?>" />
    4043<?php
    4144
  • tags/2.2/wp-login.php

    r5468 r5480  
    4747<body class="login">
    4848
    49 <div id="login"><h1><a href="<?php echo apply_filters('login_headerurl', 'http://wordpress.org/'); ?>" title="<?php echo apply_filters('login_headertitle', __('Powered by WordPress')); ?>"><span class="hide"><?php bloginfo('name'); ?></span></a></h1>
     49<div id="login"><h1><a href="<?php echo apply_filters('login_headerurl', 'http://wordpress.org/'); ?>" title="<?php echo apply_filters('login_headertitle', __('Powered by WordPress')); ?>"><?php bloginfo('name'); ?></a></h1>
    5050<?php
    5151    if ( !empty( $message ) ) echo apply_filters('login_message', $message) . "\n";
     
    9797
    9898        do_action('lostpassword_post');
    99        
     99
    100100        if ( empty( $errors ) ) {
    101101            $user_data = get_userdatabylogin(trim($_POST['user_login']));
     
    146146    </p>
    147147<?php do_action('lostpassword_form'); ?>
    148     <p class="submit"><input type="submit" name="submit" id="submit" value="<?php _e('Get New Password &raquo;'); ?>" tabindex="100" /></p>
     148    <p class="submit"><input type="submit" name="wp-submit" id="wp-submit" value="<?php _e('Get New Password &raquo;'); ?>" tabindex="100" /></p>
    149149</form>
    150150</div>
     
    154154    <li><a href="<?php bloginfo('wpurl'); ?>/wp-login.php"><?php _e('Login') ?></a></li>
    155155    <li><a href="<?php bloginfo('wpurl'); ?>/wp-login.php?action=register"><?php _e('Register') ?></a></li>
    156     <li><a href="<?php bloginfo('home'); ?>/" title="<?php _e('Are you lost?') ?>"><?php printf(__('Back to %s'), get_bloginfo('title')); ?></a></li>
     156    <li><a href="<?php bloginfo('url'); ?>/" title="<?php _e('Are you lost?') ?>"><?php printf(__('Back to %s'), get_bloginfo('title')); ?></a></li>
    157157<?php else : ?>
    158     <li><a href="<?php bloginfo('home'); ?>/" title="<?php _e('Are you lost?') ?>"><?php printf(__('Back to %s'), get_bloginfo('title')); ?></a></li>
     158    <li><a href="<?php bloginfo('url'); ?>/" title="<?php _e('Are you lost?') ?>"><?php printf(__('Back to %s'), get_bloginfo('title')); ?></a></li>
    159159    <li><a href="<?php bloginfo('wpurl'); ?>/wp-login.php"><?php _e('Login') ?></a></li>
    160160<?php endif; ?>
     
    195195    } else {
    196196        // send a copy of password change notification to the admin
    197         $message = sprintf(__('Password Lost and Changed for user: %s'), $user->user_login) . "\r\n";
    198         wp_mail(get_option('admin_email'), sprintf(__('[%s] Password Lost/Changed'), get_option('blogname')), $message);
     197        // but check to see if it's the admin whose password we're changing, and skip this
     198        if ($user->user_email != get_option('admin_email')) {
     199            $message = sprintf(__('Password Lost and Changed for user: %s'), $user->user_login) . "\r\n";
     200            wp_mail(get_option('admin_email'), sprintf(__('[%s] Password Lost/Changed'), get_option('blogname')), $message);
     201        }
    199202
    200203        wp_redirect('wp-login.php?checkemail=newpass');
     
    266269<?php do_action('register_form'); ?>
    267270    <p id="reg_passmail"><?php _e('A password will be e-mailed to you.') ?></p>
    268     <p class="submit"><input type="submit" name="submit" id="submit" value="<?php _e('Register &raquo;'); ?>" tabindex="100" /></p>
     271    <p class="submit"><input type="submit" name="wp-submit" id="wp-submit" value="<?php _e('Register &raquo;'); ?>" tabindex="100" /></p>
    269272</form>
    270273</div>
     
    273276    <li><a href="<?php bloginfo('wpurl'); ?>/wp-login.php"><?php _e('Login') ?></a></li>
    274277    <li><a href="<?php bloginfo('wpurl'); ?>/wp-login.php?action=lostpassword" title="<?php _e('Password Lost and Found') ?>"><?php _e('Lost your password?') ?></a></li>
    275     <li><a href="<?php bloginfo('home'); ?>/" title="<?php _e('Are you lost?') ?>"><?php printf(__('Back to %s'), get_bloginfo('title')); ?></a></li>
     278    <li><a href="<?php bloginfo('url'); ?>/" title="<?php _e('Are you lost?') ?>"><?php printf(__('Back to %s'), get_bloginfo('title')); ?></a></li>
    276279</ul>
    277280
     
    326329        }
    327330    }
    328    
     331
    329332    if ( $_POST && empty( $user_login ) )
    330333        $errors['user_login'] = __('<strong>ERROR</strong>: The username field is empty.');
     
    354357    <p><label><input name="rememberme" type="checkbox" id="rememberme" value="forever" tabindex="90" /> <?php _e('Remember me'); ?></label></p>
    355358    <p class="submit">
    356         <input type="submit" name="submit" id="submit" value="<?php _e('Login'); ?> &raquo;" tabindex="100" />
     359        <input type="submit" name="wp-submit" id="wp-submit" value="<?php _e('Login'); ?> &raquo;" tabindex="100" />
    357360        <input type="hidden" name="redirect_to" value="<?php echo attribute_escape($redirect_to); ?>" />
    358361    </p>
     
    364367    <li><a href="<?php bloginfo('wpurl'); ?>/wp-login.php?action=register"><?php _e('Register') ?></a></li>
    365368    <li><a href="<?php bloginfo('wpurl'); ?>/wp-login.php?action=lostpassword" title="<?php _e('Password Lost and Found') ?>"><?php _e('Lost your password?') ?></a></li>
    366     <li><a href="<?php bloginfo('home'); ?>/" title="<?php _e('Are you lost?') ?>"><?php printf(__('Back to %s'), get_bloginfo('title')); ?></a></li>
     369    <li><a href="<?php bloginfo('url'); ?>/" title="<?php _e('Are you lost?') ?>"><?php printf(__('Back to %s'), get_bloginfo('title')); ?></a></li>
    367370<?php else : ?>
    368     <li><a href="<?php bloginfo('home'); ?>/" title="<?php _e('Are you lost?') ?>"><?php printf(__('Back to %s'), get_bloginfo('title')); ?></a></li>
     371    <li><a href="<?php bloginfo('url'); ?>/" title="<?php _e('Are you lost?') ?>"><?php printf(__('Back to %s'), get_bloginfo('title')); ?></a></li>
    369372    <li><a href="<?php bloginfo('wpurl'); ?>/wp-login.php?action=lostpassword" title="<?php _e('Password Lost and Found') ?>"><?php _e('Lost your password?') ?></a></li>
    370373<?php endif; ?>
  • tags/2.2/wp-mail.php

    r5468 r5480  
    2525    $content = '';
    2626    $content_type = '';
     27    $content_transfer_encoding = '';
    2728    $boundary = '';
    2829    $bodysignal = 0;
    29     $dmonths = array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
    30                      'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
     30    $dmonths = array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
    3131    foreach ($message as $line) :
    3232        if (strlen($line) < 3) $bodysignal = 1;
     
    4040                $content_type = explode(';', $content_type);
    4141                $content_type = $content_type[0];
     42            }
     43            if (preg_match('/Content-Transfer-Encoding: /i', $line)) {
     44                $content_transfer_encoding = trim($line);
     45                $content_transfer_encoding = substr($content_transfer_encoding, 27, strlen($content_transfer_encoding)-14);
     46                $content_transfer_encoding = explode(';', $content_transfer_encoding);
     47                $content_transfer_encoding = $content_transfer_encoding[0];
    4248            }
    4349            if (($content_type == 'multipart/alternative') && (preg_match('/boundary="/', $line)) && ($boundary == '')) {
     
    5763            // Set the author using the email address (To or Reply-To, the last used)
    5864            // otherwise use the site admin
    59             if (preg_match('/From: /', $line) | preg_match('Reply-To: /', $line))  {
     65            if (preg_match('/From: /', $line) | preg_match('/Reply-To: /', $line))  {
    6066                $author=trim($line);
    6167            if ( ereg("([a-zA-Z0-9\_\-\.]+@[\a-zA-z0-9\_\-\.]+)", $author , $regs) ) {
     
    112118    }
    113119    $content = trim($content);
     120   
     121    if (stripos($content_transfer_encoding, "quoted-printable") !== false) {
     122        $content = quoted_printable_decode($content);
     123    }
     124
    114125    // Captures any text in the body after $phone_delim as the body
    115126    $content = explode($phone_delim, $content);
    116127    $content[1] ? $content = $content[1] : $content = $content[0];
    117128
    118     echo "<p><b>Content-type:</b> $content_type, <b>boundary:</b> $boundary</p>\n";
     129    echo "<p><b>Content-type:</b> $content_type, <b>Content-Transfer-Encoding:</b> $content_transfer_encoding, <b>boundary:</b> $boundary</p>\n";
    119130    echo "<p><b>Raw content:</b><br /><pre>".$content.'</pre></p>';
    120131
  • tags/2.2/wp-rdf.php

    r5468 r5480  
    66}
    77
    8 header('Content-type: application/rdf+xml; charset=' . get_option('blog_charset'), true);
    9 $more = 1;
     8require (ABSPATH . WPINC . '/feed-rdf.php');
    109
    1110?>
    12 <?php echo '<?xml version="1.0" encoding="'.get_option('blog_charset').'"?'.'>'; ?>
    13 <!-- generator="wordpress/<?php echo $wp_version ?>" -->
    14 <rdf:RDF
    15     xmlns="http://purl.org/rss/1.0/"
    16     xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    17     xmlns:dc="http://purl.org/dc/elements/1.1/"
    18     xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
    19     xmlns:admin="http://webns.net/mvcb/"
    20     xmlns:content="http://purl.org/rss/1.0/modules/content/"
    21     <?php do_action('rdf_ns'); ?>
    22 >
    23 <channel rdf:about="<?php bloginfo_rss("url") ?>">
    24     <title><?php bloginfo_rss('name') ?></title>
    25     <link><?php bloginfo_rss('url') ?></link>
    26     <description><?php bloginfo_rss('description') ?></description>
    27     <dc:date><?php echo mysql2date('Y-m-d\TH:i:s\Z', get_lastpostmodified('GMT'), false); ?></dc:date>
    28     <admin:generatorAgent rdf:resource="http://wordpress.org/?v=<?php echo $wp_version ?>"/>
    29     <sy:updatePeriod>hourly</sy:updatePeriod>
    30     <sy:updateFrequency>1</sy:updateFrequency>
    31     <sy:updateBase>2000-01-01T12:00+00:00</sy:updateBase>
    32     <?php do_action('rdf_header'); ?>
    33     <items>
    34         <rdf:Seq>
    35         <?php while (have_posts()): the_post(); ?>
    36             <rdf:li rdf:resource="<?php permalink_single_rss() ?>"/>
    37         <?php endwhile; ?>
    38         </rdf:Seq>
    39     </items>
    40 </channel>
    41 <?php rewind_posts(); while (have_posts()): the_post(); ?>
    42 <item rdf:about="<?php permalink_single_rss() ?>">
    43     <title><?php the_title_rss() ?></title>
    44     <link><?php permalink_single_rss() ?></link>
    45      <dc:date><?php echo mysql2date('Y-m-d\TH:i:s\Z', $post->post_date_gmt, false); ?></dc:date>
    46     <dc:creator><?php the_author() ?></dc:creator>
    47     <?php the_category_rss('rdf') ?>
    48 <?php if (get_option('rss_use_excerpt')) : ?>
    49     <description><?php the_excerpt_rss() ?></description>
    50 <?php else : ?>
    51     <description><?php the_content_rss('', 0, '', get_option('rss_excerpt_length'), 2) ?></description>
    52     <content:encoded><![CDATA[<?php the_content('', 0, '') ?>]]></content:encoded>
    53 <?php endif; ?>
    54     <?php do_action('rdf_item'); ?>
    55 </item>
    56 <?php endwhile;  ?>
    57 </rdf:RDF>
  • tags/2.2/wp-rss.php

    r5468 r5480  
    66}
    77
    8 header('Content-type: text/xml; charset=' . get_option('blog_charset'), true);
    9 $more = 1;
     8require (ABSPATH . WPINC . '/feed-rss.php');
    109
    1110?>
    12 <?php echo '<?xml version="1.0" encoding="'.get_option('blog_charset').'"?'.'>'; ?>
    13 <!-- generator="wordpress/<?php echo $wp_version ?>" -->
    14 <rss version="0.92">
    15 <channel>
    16     <title><?php bloginfo_rss('name') ?></title>
    17     <link><?php bloginfo_rss('url') ?></link>
    18     <description><?php bloginfo_rss('description') ?></description>
    19     <lastBuildDate><?php echo mysql2date('D, d M Y H:i:s +0000', get_lastpostmodified('GMT'), false); ?></lastBuildDate>
    20     <docs>http://backend.userland.com/rss092</docs>
    21     <language><?php echo get_option('rss_language'); ?></language>
    22     <?php do_action('rss_head'); ?>
    23 
    24 <?php while (have_posts()) : the_post(); ?>
    25     <item>
    26         <title><?php the_title_rss() ?></title>
    27 <?php if (get_option('rss_use_excerpt')) { ?>
    28         <description><![CDATA[<?php the_excerpt_rss() ?>]]></description>
    29 <?php } else { // use content ?>
    30         <description><?php the_content_rss('', 0, '', get_option('rss_excerpt_length')) ?></description>
    31 <?php } ?>
    32         <link><?php permalink_single_rss() ?></link>
    33         <?php do_action('rss_item'); ?>
    34     </item>
    35 <?php endwhile; ?>
    36 </channel>
    37 </rss>
  • tags/2.2/wp-rss2.php

    r5468 r5480  
    66}
    77
    8 header('Content-type: text/xml; charset=' . get_option('blog_charset'), true);
    9 $more = 1;
     8require (ABSPATH . WPINC . '/feed-rss2.php');
    109
    1110?>
    12 <?php echo '<?xml version="1.0" encoding="'.get_option('blog_charset').'"?'.'>'; ?>
    13 
    14 <!-- generator="wordpress/<?php bloginfo_rss('version') ?>" -->
    15 <rss version="2.0"
    16     xmlns:content="http://purl.org/rss/1.0/modules/content/"
    17     xmlns:wfw="http://wellformedweb.org/CommentAPI/"
    18     xmlns:dc="http://purl.org/dc/elements/1.1/"
    19     <?php do_action('rss2_ns'); ?>
    20 >
    21 
    22 <channel>
    23     <title><?php bloginfo_rss('name'); ?></title>
    24     <link><?php bloginfo_rss('url') ?></link>
    25     <description><?php bloginfo_rss("description") ?></description>
    26     <pubDate><?php echo mysql2date('D, d M Y H:i:s +0000', get_lastpostmodified('GMT'), false); ?></pubDate>
    27     <generator>http://wordpress.org/?v=<?php bloginfo_rss('version'); ?></generator>
    28     <language><?php echo get_option('rss_language'); ?></language>
    29     <?php do_action('rss2_head'); ?>
    30     <?php while( have_posts()) : the_post(); ?>
    31     <item>
    32         <title><?php the_title_rss() ?></title>
    33         <link><?php permalink_single_rss() ?></link>
    34         <comments><?php comments_link(); ?></comments>
    35         <pubDate><?php echo mysql2date('D, d M Y H:i:s +0000', get_post_time('Y-m-d H:i:s', true), false); ?></pubDate>
    36         <dc:creator><?php the_author() ?></dc:creator>
    37         <?php the_category_rss() ?>
    38 
    39         <guid isPermaLink="false"><?php the_guid(); ?></guid>
    40 <?php if (get_option('rss_use_excerpt')) : ?>
    41         <description><![CDATA[<?php the_excerpt_rss() ?>]]></description>
    42 <?php else : ?>
    43         <description><![CDATA[<?php the_excerpt_rss() ?>]]></description>
    44     <?php if ( strlen( $post->post_content ) > 0 ) : ?>
    45         <content:encoded><![CDATA[<?php the_content() ?>]]></content:encoded>
    46     <?php else : ?>
    47         <content:encoded><![CDATA[<?php the_excerpt_rss() ?>]]></content:encoded>
    48     <?php endif; ?>
    49 <?php endif; ?>
    50         <wfw:commentRss><?php echo comments_rss(); ?></wfw:commentRss>
    51 <?php rss_enclosure(); ?>
    52     <?php do_action('rss2_item'); ?>
    53     </item>
    54     <?php endwhile; ?>
    55 </channel>
    56 </rss>
  • tags/2.2/wp-settings.php

    r5468 r5480  
    4141
    4242// Fix for Dreamhost and other PHP as CGI hosts
    43 if ( strstr( $_SERVER['SCRIPT_NAME'], 'php.cgi' ) )
     43if (strpos($_SERVER['SCRIPT_NAME'], 'php.cgi') !== false)
    4444    unset($_SERVER['PATH_INFO']);
    4545
     
    123123    $wpdb->usermeta = CUSTOM_USER_META_TABLE;
    124124
    125 // To be removed in 2.2
    126 $tableposts = $tableusers = $tablecategories = $tablepost2cat = $tablecomments = $tablelink2cat = $tablelinks = $tablelinkcategories = $tableoptions = $tablepostmeta = '';
    127 
    128125if ( file_exists(ABSPATH . 'wp-content/object-cache.php') )
    129126    require (ABSPATH . 'wp-content/object-cache.php');
     
    134131
    135132require (ABSPATH . WPINC . '/functions.php');
     133require (ABSPATH . WPINC . '/classes.php');
    136134require (ABSPATH . WPINC . '/plugin.php');
    137135require (ABSPATH . WPINC . '/default-filters.php');
     
    140138require_once (ABSPATH . WPINC . '/l10n.php');
    141139
    142 if ( !is_blog_installed() && (!strstr($_SERVER['PHP_SELF'], 'install.php') && !defined('WP_INSTALLING')) ) {
    143     if ( strstr($_SERVER['PHP_SELF'], 'wp-admin') )
     140if ( !is_blog_installed() && (strpos($_SERVER['PHP_SELF'], 'install.php') === false && !defined('WP_INSTALLING')) ) {
     141    if (strpos($_SERVER['PHP_SELF'], 'wp-admin') !== false)
    144142        $link = 'install.php';
    145143    else
     
    150148require (ABSPATH . WPINC . '/formatting.php');
    151149require (ABSPATH . WPINC . '/capabilities.php');
    152 require (ABSPATH . WPINC . '/classes.php');
    153150require (ABSPATH . WPINC . '/query.php');
    154151require (ABSPATH . WPINC . '/theme.php');
     
    173170require (ABSPATH . WPINC . '/script-loader.php');
    174171
    175 if (!strstr($_SERVER['PHP_SELF'], 'install.php')) :
     172if (strpos($_SERVER['PHP_SELF'], 'install.php') === false) {
    176173    // Used to guarantee unique hash cookies
    177174    $cookiehash = md5(get_option('siteurl'));
    178175    define('COOKIEHASH', $cookiehash);
    179 endif;
     176}
    180177
    181178if ( !defined('USER_COOKIE') )
     
    202199    if ( is_array($current_plugins) ) {
    203200        foreach ($current_plugins as $plugin) {
    204             if ('' != $plugin && file_exists(ABSPATH . 'wp-content/plugins/' . $plugin))
    205                 include_once(ABSPATH . 'wp-content/plugins/' . $plugin);
     201            if ('' != $plugin && file_exists(ABSPATH . PLUGINDIR . '/' . $plugin))
     202                include_once(ABSPATH . PLUGINDIR . '/' . $plugin);
    206203        }
    207204    }
  • tags/2.2/wp-trackback.php

    r5468 r5480  
    6767}
    6868
    69 if ( !empty($tb_url) && !empty($title) && !empty($tb_url) ) {
     69if ( !empty($tb_url) && !empty($title) ) {
    7070    header('Content-Type: text/xml; charset=' . get_option('blog_charset') );
    7171
  • tags/2.2/xmlrpc.php

    r5468 r5480  
    55// Some browser-embedded clients send cookies. We don't want them.
    66$_COOKIE = array();
     7
     8// A bug in PHP < 5.2.2 makes $HTTP_RAW_POST_DATA not set by default,
     9// but we can do it ourself.
     10if ( !isset( $HTTP_RAW_POST_DATA ) ) {
     11    $HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
     12}
    713
    814# fix for mozBlog and other cases where '<?xml' isn't on the very first line
     
    2329    <homePageLink><?php bloginfo_rss('url') ?></homePageLink>
    2430    <apis>
     31      <api name="WordPress" blogID="1" preferred="false" apiLink="<?php bloginfo_rss('url') ?>/xmlrpc.php" />
    2532      <api name="Movable Type" blogID="1" preferred="true" apiLink="<?php bloginfo_rss('url') ?>/xmlrpc.php" />
    2633      <api name="MetaWeblog" blogID="1" preferred="false" apiLink="<?php bloginfo_rss('url') ?>/xmlrpc.php" />
     
    6875    function wp_xmlrpc_server() {
    6976        $this->methods = array(
     77            // WordPress API
     78            'wp.getPage'            => 'this:wp_getPage',
     79            'wp.getPages'           => 'this:wp_getPages',
     80            'wp.newPage'            => 'this:wp_newPage',
     81            'wp.deletePage'         => 'this:wp_deletePage',
     82            'wp.editPage'           => 'this:wp_editPage',
     83            'wp.getPageList'        => 'this:wp_getPageList',
     84            'wp.getAuthors'         => 'this:wp_getAuthors',
     85            'wp.getCategories'      => 'this:mw_getCategories',     // Alias
     86            'wp.newCategory'        => 'this:wp_newCategory',
     87            'wp.suggestCategories'  => 'this:wp_suggestCategories',
     88            'wp.uploadFile'         => 'this:mw_newMediaObject',    // Alias
     89
    7090            // Blogger API
    7191            'blogger.getUsersBlogs' => 'this:blogger_getUsersBlogs',
     
    127147    function login_pass_ok($user_login, $user_pass) {
    128148        if (!user_pass_ok($user_login, $user_pass)) {
    129             $this->error = new IXR_Error(403, 'Bad login/pass combination.');
     149            $this->error = new IXR_Error(403, __('Bad login/pass combination.'));
    130150            return false;
    131151        }
     
    136156        global $wpdb;
    137157
    138         foreach ( (array) $array as $k => $v ) {
    139             if (is_array($v)) {
    140                 $this->escape($array[$k]);
    141             } else if (is_object($v)) {
    142                 //skip
    143             } else {
    144                 $array[$k] = $wpdb->escape($v);
     158        if(!is_array($array)) {
     159            return($wpdb->escape($array));
     160        }
     161        else {
     162            foreach ( (array) $array as $k => $v ) {
     163                if (is_array($v)) {
     164                    $this->escape($array[$k]);
     165                } else if (is_object($v)) {
     166                    //skip
     167                } else {
     168                    $array[$k] = $wpdb->escape($v);
     169                }
    145170            }
    146171        }
    147172    }
     173
     174    /**
     175     * WordPress XML-RPC API
     176     * wp_getPage
     177     */
     178    function wp_getPage($args) {
     179        $this->escape($args);
     180
     181        $blog_id    = (int) $args[0];
     182        $page_id    = (int) $args[1];
     183        $username   = $args[2];
     184        $password   = $args[3];
     185
     186        if(!$this->login_pass_ok($username, $password)) {
     187            return($this->error);
     188        }
     189
     190        // Lookup page info.
     191        $page = get_page($page_id);
     192
     193        // If we found the page then format the data.
     194        if($page->ID && ($page->post_type == "page")) {
     195            // Get all of the page content and link.
     196            $full_page = get_extended($page->post_content);
     197            $link = post_permalink($page->ID);
     198
     199            // Get info the page parent if there is one.
     200            $parent_title = "";
     201            if(!empty($page->post_parent)) {
     202                $parent = get_page($page->post_parent);
     203                $parent_title = $parent->post_title;
     204            }
     205
     206            // Determine comment and ping settings.
     207            $allow_comments = ("open" == $page->comment_status) ? 1 : 0;
     208            $allow_pings = ("open" == $page->ping_status) ? 1 : 0;
     209
     210            // Format page date.
     211            $page_date = mysql2date("Ymd\TH:i:s", $page->post_date_gmt);
     212
     213            // Pull the categories info together.
     214            $categories = array();
     215            foreach(wp_get_post_categories($page->ID) as $cat_id) {
     216                $categories[] = get_cat_name($cat_id);
     217            }
     218
     219            // Get the author info.
     220            $author = get_userdata($page->post_author);
     221
     222            $page_struct = array(
     223                "dateCreated"           => new IXR_Date($page_date),
     224                "userid"                => $page->post_author,
     225                "page_id"               => $page->ID,
     226                "page_status"           => $page->post_status,
     227                "description"           => $full_page["main"],
     228                "title"                 => $page->post_title,
     229                "link"                  => $link,
     230                "permaLink"             => $link,
     231                "categories"            => $categories,
     232                "excerpt"               => $page->post_excerpt,
     233                "text_more"             => $full_page["extended"],
     234                "mt_allow_comments"     => $allow_comments,
     235                "mt_allow_pings"        => $allow_pings,
     236                "wp_slug"               => $page->post_name,
     237                "wp_password"           => $page->post_password,
     238                "wp_author"             => $author->display_name,
     239                "wp_page_parent_id"     => $page->post_parent,
     240                "wp_page_parent_title"  => $parent_title,
     241                "wp_page_order"         => $page->menu_order,
     242                "wp_author_id"          => $author->ID,
     243                "wp_author_display_name"    => $author->display_name
     244            );
     245
     246            return($page_struct);
     247        }
     248        // If the page doesn't exist indicate that.
     249        else {
     250            return(new IXR_Error(404, __("Sorry, no such page.")));
     251        }
     252    }
     253
     254    /**
     255     * WordPress XML-RPC API
     256     * wp_getPages
     257     */
     258    function wp_getPages($args) {
     259        $this->escape($args);
     260
     261        $blog_id    = (int) $args[0];
     262        $username   = $args[1];
     263        $password   = $args[2];
     264
     265        if(!$this->login_pass_ok($username, $password)) {
     266            return($this->error);
     267        }
     268
     269        // Lookup info on pages.
     270        $pages = get_pages();
     271        $num_pages = count($pages);
     272
     273        // If we have pages, put together their info.
     274        if($num_pages >= 1) {
     275            $pages_struct = array();
     276
     277            for($i = 0; $i < $num_pages; $i++) {
     278                $page = wp_xmlrpc_server::wp_getPage(array(
     279                    $blog_id, $pages[$i]->ID, $username, $password
     280                ));
     281                $pages_struct[] = $page;
     282            }
     283
     284            return($pages_struct);
     285        }
     286        // If no pages were found return an error.
     287        else {
     288            return(array());
     289        }
     290    }
     291
     292    /**
     293     * WordPress XML-RPC API
     294     * wp_newPage
     295     */
     296    function wp_newPage($args) {
     297        // Items not escaped here will be escaped in newPost.
     298        $username   = $this->escape($args[1]);
     299        $password   = $this->escape($args[2]);
     300        $page       = $args[3];
     301        $publish    = $args[4];
     302
     303        if(!$this->login_pass_ok($username, $password)) {
     304            return($this->error);
     305        }
     306
     307        // Set the user context and check if they are allowed
     308        // to add new pages.
     309        $user = set_current_user(0, $username);
     310        if(!current_user_can("publish_pages")) {
     311            return(new IXR_Error(401, __("Sorry, you can not add new pages.")));
     312        }
     313
     314        // Mark this as content for a page.
     315        $args[3]["post_type"] = "page";
     316
     317        // Let mw_newPost do all of the heavy lifting.
     318        return($this->mw_newPost($args));
     319    }
     320
     321    /**
     322     * WordPress XML-RPC API
     323     * wp_deletePage
     324     */
     325    function wp_deletePage($args) {
     326        $this->escape($args);
     327
     328        $blog_id    = (int) $args[0];
     329        $username   = $args[1];
     330        $password   = $args[2];
     331        $page_id    = (int) $args[3];
     332
     333        if(!$this->login_pass_ok($username, $password)) {
     334            return($this->error);
     335        }
     336
     337        // Get the current page based on the page_id and
     338        // make sure it is a page and not a post.
     339        $actual_page = wp_get_single_post($page_id, ARRAY_A);
     340        if(
     341            !$actual_page
     342            || ($actual_page["post_type"] != "page")
     343        ) {
     344            return(new IXR_Error(404, __("Sorry, no such page.")));
     345        }
     346
     347        // Set the user context and make sure they can delete pages.
     348        set_current_user(0, $username);
     349        if(!current_user_can("delete_page", $page_id)) {
     350            return(new IXR_Error(401, __("Sorry, you do not have the right to delete this page.")));
     351        }
     352
     353        // Attempt to delete the page.
     354        $result = wp_delete_post($page_id);
     355        if(!$result) {
     356            return(new IXR_Error(500, __("Failed to delete the page.")));
     357        }
     358
     359        return(true);
     360    }
     361
     362    /**
     363     * WordPress XML-RPC API
     364     * wp_editPage
     365     */
     366    function wp_editPage($args) {
     367        // Items not escaped here will be escaped in editPost.
     368        $blog_id    = (int) $args[0];
     369        $page_id    = (int) $this->escape($args[1]);
     370        $username   = $this->escape($args[2]);
     371        $password   = $this->escape($args[3]);
     372        $content    = $args[4];
     373        $publish    = $args[5];
     374
     375        if(!$this->login_pass_ok($username, $password)) {
     376            return($this->error);
     377        }
     378
     379        // Get the page data and make sure it is a page.
     380        $actual_page = wp_get_single_post($page_id, ARRAY_A);
     381        if(
     382            !$actual_page
     383            || ($actual_page["post_type"] != "page")
     384        ) {
     385            return(new IXR_Error(404, __("Sorry, no such page.")));
     386        }
     387
     388        // Set the user context and make sure they are allowed to edit pages.
     389        set_current_user(0, $username);
     390        if(!current_user_can("edit_page", $page_id)) {
     391            return(new IXR_Error(401, __("Sorry, you do not have the right to edit this page.")));
     392        }
     393
     394        // Mark this as content for a page.
     395        $content["post_type"] = "page";
     396
     397        // Arrange args in the way mw_editPost understands.
     398        $args = array(
     399            $page_id,
     400            $username,
     401            $password,
     402            $content,
     403            $publish
     404        );
     405
     406        // Let mw_editPost do all of the heavy lifting.
     407        return($this->mw_editPost($args));
     408    }
     409
     410    /**
     411     * WordPress XML-RPC API
     412     * wp_getPageList
     413     */
     414    function wp_getPageList($args) {
     415        global $wpdb;
     416
     417        $this->escape($args);
     418
     419        $blog_id                = (int) $args[0];
     420        $username               = $args[1];
     421        $password               = $args[2];
     422
     423        if(!$this->login_pass_ok($username, $password)) {
     424            return($this->error);
     425        }
     426
     427        // Get list of pages ids and titles
     428        $page_list = $wpdb->get_results("
     429            SELECT ID page_id,
     430                post_title page_title,
     431                post_parent page_parent_id,
     432                post_date_gmt
     433            FROM {$wpdb->posts}
     434            WHERE post_type = 'page'
     435            ORDER BY ID
     436        ");
     437
     438        // The date needs to be formated properly.
     439        $num_pages = count($page_list);
     440        for($i = 0; $i < $num_pages; $i++) {
     441            $post_date = mysql2date("Ymd\TH:i:s", $page_list[$i]->post_date_gmt);
     442            $page_list[$i]->dateCreated = new IXR_Date($post_date);
     443
     444            unset($page_list[$i]->post_date_gmt);
     445        }
     446
     447        return($page_list);
     448    }
     449
     450    /**
     451     * WordPress XML-RPC API
     452     * wp_getAuthors
     453     */
     454    function wp_getAuthors($args) {
     455        global $wpdb;
     456
     457        $this->escape($args);
     458
     459        $blog_id    = (int) $args[0];
     460        $username   = $args[1];
     461        $password   = $args[2];
     462
     463        if(!$this->login_pass_ok($username, $password)) {
     464            return($this->error);
     465        }
     466
     467        return(get_users_of_blog());
     468    }
     469
     470    /**
     471     * WordPress XML-RPC API
     472     * wp_newCategory
     473     */
     474    function wp_newCategory($args) {
     475        $this->escape($args);
     476
     477        $blog_id                = (int) $args[0];
     478        $username               = $args[1];
     479        $password               = $args[2];
     480        $category               = $args[3];
     481
     482        if(!$this->login_pass_ok($username, $password)) {
     483            return($this->error);
     484        }
     485
     486        // Set the user context and make sure they are
     487        // allowed to add a category.
     488        set_current_user(0, $username);
     489        if(!current_user_can("manage_categories", $page_id)) {
     490            return(new IXR_Error(401, __("Sorry, you do not have the right to add a category.")));
     491        }
     492
     493        // We need this to make use of the wp_insert_category()
     494        // funciton.
     495        require_once(ABSPATH . "wp-admin/admin-db.php");
     496
     497        // If no slug was provided make it empty so that
     498        // WordPress will generate one.
     499        if(empty($category["slug"])) {
     500            $category["slug"] = "";
     501        }
     502
     503        // If no parent_id was provided make it empty
     504        // so that it will be a top level page (no parent).
     505        if ( !isset($category["parent_id"]) )
     506            $category["parent_id"] = "";
     507
     508        // If no description was provided make it empty.
     509        if(empty($category["description"])) {
     510            $category["description"] = "";
     511        }
     512   
     513        $new_category = array(
     514            "cat_name"              => $category["name"],
     515            "category_nicename"     => $category["slug"],
     516            "category_parent"       => $category["parent_id"],
     517            "category_description"  => $category["description"]
     518        );
     519
     520        $cat_id = wp_insert_category($new_category);
     521        if(!$cat_id) {
     522            return(new IXR_Error(500, __("Sorry, the new category failed.")));
     523        }
     524
     525        return($cat_id);
     526    }
     527
     528    /**
     529     * WordPress XML-RPC API
     530     * wp_suggestCategories
     531     */
     532    function wp_suggestCategories($args) {
     533        global $wpdb;
     534
     535        $this->escape($args);
     536
     537        $blog_id                = (int) $args[0];
     538        $username               = $args[1];
     539        $password               = $args[2];
     540        $category               = $args[3];
     541        $max_results            = $args[4];
     542
     543        if(!$this->login_pass_ok($username, $password)) {
     544            return($this->error);
     545        }
     546
     547        // Only set a limit if one was provided.
     548        $limit = "";
     549        if(!empty($max_results)) {
     550            $limit = "LIMIT {$max_results}";
     551        }
     552
     553        $category_suggestions = $wpdb->get_results("
     554            SELECT cat_ID category_id,
     555                cat_name category_name
     556            FROM {$wpdb->categories}
     557            WHERE cat_name LIKE '{$category}%'
     558            {$limit}
     559        ");
     560
     561        return($category_suggestions);
     562    }
     563
    148564
    149565    /* Blogger API functions
     
    157573        $this->escape($args);
    158574
    159       $user_login = $args[1];
    160       $user_pass  = $args[2];
    161 
    162       if (!$this->login_pass_ok($user_login, $user_pass)) {
    163         return $this->error;
    164       }
    165 
    166       set_current_user(0, $user_login);
    167       $is_admin = current_user_can('level_8');
    168 
    169       $struct = array(
    170         'isAdmin'  => $is_admin,
    171         'url'      => get_option('home') . '/',
    172         'blogid'   => '1',
    173         'blogName' => get_option('blogname')
    174       );
    175 
    176       return array($struct);
     575        $user_login = $args[1];
     576        $user_pass  = $args[2];
     577
     578        if (!$this->login_pass_ok($user_login, $user_pass)) {
     579            return $this->error;
     580        }
     581
     582        set_current_user(0, $user_login);
     583        $is_admin = current_user_can('level_8');
     584
     585        $struct = array(
     586            'isAdmin'  => $is_admin,
     587            'url'      => get_option('home') . '/',
     588            'blogid'   => '1',
     589            'blogName' => get_option('blogname')
     590        );
     591
     592        return array($struct);
    177593    }
    178594
     
    257673
    258674        if (!$posts_list) {
    259             $this->error = new IXR_Error(500, 'Either there are no posts, or something went wrong.');
     675            $this->error = new IXR_Error(500, __('Either there are no posts, or something went wrong.'));
    260676            return $this->error;
    261677        }
     
    304720      set_current_user(0, $user_login);
    305721      if ( !current_user_can('edit_themes') ) {
    306         return new IXR_Error(401, 'Sorry, this user can not edit the template.');
     722        return new IXR_Error(401, __('Sorry, this user can not edit the template.'));
    307723      }
    308724
     
    339755      set_current_user(0, $user_login);
    340756      if ( !current_user_can('edit_themes') ) {
    341         return new IXR_Error(401, 'Sorry, this user can not edit the template.');
     757        return new IXR_Error(401, __('Sorry, this user can not edit the template.'));
    342758      }
    343759
     
    350766        fclose($f);
    351767      } else {
    352         return new IXR_Error(500, 'Either the file is not writable, or something wrong happened. The file has not been updated.');
     768        return new IXR_Error(500, __('Either the file is not writable, or something wrong happened. The file has not been updated.'));
    353769      }
    354770
     
    377793      $user = set_current_user(0, $user_login);
    378794      if ( !current_user_can($cap) )
    379         return new IXR_Error(401, 'Sorry, you can not post on this weblog or category.');
     795        return new IXR_Error(401, __('Sorry, you can not post on this weblog or category.'));
    380796
    381797      $post_status = ($publish) ? 'publish' : 'draft';
     
    395811
    396812      if (!$post_ID) {
    397         return new IXR_Error(500, 'Sorry, your entry could not be posted. Something wrong happened.');
     813        return new IXR_Error(500, __('Sorry, your entry could not be posted. Something wrong happened.'));
    398814      }
    399815      $this->attach_uploads( $post_ID, $post_content );
     
    425841
    426842      if (!$actual_post) {
    427         return new IXR_Error(404, 'Sorry, no such post.');
     843        return new IXR_Error(404, __('Sorry, no such post.'));
    428844      }
    429845
     
    432848      set_current_user(0, $user_login);
    433849      if ( !current_user_can('edit_post', $post_ID) )
    434         return new IXR_Error(401, 'Sorry, you do not have the right to edit this post.');
     850        return new IXR_Error(401, __('Sorry, you do not have the right to edit this post.'));
    435851
    436852      extract($actual_post);
    437853
    438854      if ( ('publish' == $post_status) && !current_user_can('publish_posts') )
    439         return new IXR_Error(401, 'Sorry, you do not have the right to publish this post.');
     855        return new IXR_Error(401, __('Sorry, you do not have the right to publish this post.'));
    440856
    441857      $post_title = xmlrpc_getposttitle($content);
     
    448864
    449865      if (!$result) {
    450         return new IXR_Error(500, 'For some strange yet very annoying reason, this post could not be edited.');
     866        return new IXR_Error(500, __('For some strange yet very annoying reason, this post could not be edited.'));
    451867      }
    452868      $this->attach_uploads( $ID, $post_content );
     
    475891
    476892      if (!$actual_post) {
    477         return new IXR_Error(404, 'Sorry, no such post.');
     893        return new IXR_Error(404, __('Sorry, no such post.'));
    478894      }
    479895
    480896      set_current_user(0, $user_login);
    481897      if ( !current_user_can('edit_post', $post_ID) )
    482         return new IXR_Error(401, 'Sorry, you do not have the right to delete this post.');
     898        return new IXR_Error(401, __('Sorry, you do not have the right to delete this post.'));
    483899
    484900      $result = wp_delete_post($post_ID);
    485901
    486902      if (!$result) {
    487         return new IXR_Error(500, 'For some strange yet very annoying reason, this post could not be deleted.');
     903        return new IXR_Error(500, __('For some strange yet very annoying reason, this post could not be deleted.'));
    488904      }
    489905
     
    516932      $user = set_current_user(0, $user_login);
    517933      if ( !current_user_can('publish_posts') )
    518         return new IXR_Error(401, 'Sorry, you can not post on this weblog or category.');
     934        return new IXR_Error(401, __('Sorry, you can not post on this weblog or category.'));
     935
     936        // The post_type defaults to post, but could also be page.
     937        $post_type = "post";
     938        if(
     939            !empty($content_struct["post_type"])
     940            && ($content_struct["post_type"] == "page")
     941        ) {
     942            $post_type = "page";
     943        }
     944
     945        // Let WordPress generate the post_name (slug) unless
     946        // one has been provided.
     947        $post_name = "";
     948        if(isset($content_struct["wp_slug"])) {
     949            $post_name = $content_struct["wp_slug"];
     950        }
     951
     952        // Only use a password if one was given.
     953        if(isset($content_struct["wp_password"])) {
     954            $post_password = $content_struct["wp_password"];
     955        }
     956
     957        // Only set a post parent if one was provided.
     958        if(isset($content_struct["wp_page_parent_id"])) {
     959            $post_parent = $content_struct["wp_page_parent_id"];
     960        }
     961
     962        // Only set the menu_order if it was provided.
     963        if(isset($content_struct["wp_page_order"])) {
     964            $menu_order = $content_struct["wp_page_order"];
     965        }
    519966
    520967      $post_author = $user->ID;
     968
     969        // If an author id was provided then use it instead.
     970        if(
     971            isset($content_struct["wp_author_id"])
     972            && ($user->ID != $content_struct["wp_author_id"])
     973        ) {
     974            switch($post_type) {
     975                case "post":
     976                    if(!current_user_can("edit_others_posts")) {
     977                        return(new IXR_Error(401, "You are not allowed to " .
     978                            "post as this user"));
     979                    }
     980                    break;
     981                case "page":
     982                    if(!current_user_can("edit_others_pages")) {
     983                        return(new IXR_Error(401, "You are not allowed to " .
     984                            "create pages as this user"));
     985                    }
     986                    break;
     987                default:
     988                    return(new IXR_Error(401, __("Invalid post type.")));
     989                    break;
     990            }
     991            $post_author = $content_struct["wp_author_id"];
     992        }
    521993
    522994      $post_title = $content_struct['title'];
     
    527999      $post_more = $content_struct['mt_text_more'];
    5281000
    529       $comment_status = (empty($content_struct['mt_allow_comments'])) ?
    530         get_option('default_comment_status')
    531         : $content_struct['mt_allow_comments'];
    532 
    533       $ping_status = (empty($content_struct['mt_allow_pings'])) ?
    534         get_option('default_ping_status')
    535         : $content_struct['mt_allow_pings'];
     1001        if(isset($content_struct["mt_allow_comments"])) {
     1002            switch((int) $content_struct["mt_allow_comments"]) {
     1003                case 0:
     1004                    $comment_status = "closed";
     1005                    break;
     1006                case 1:
     1007                    $comment_status = "open";
     1008                    break;
     1009                default:
     1010                    $comment_status = get_option("default_comment_status");
     1011                    break;
     1012            }
     1013        }
     1014
     1015        if(isset($content_struct["mt_allow_pings"])) {
     1016            switch((int) $content_struct["mt_allow_pings"]) {
     1017                case 0:
     1018                    $ping_status = "closed";
     1019                    break;
     1020                case 1:
     1021                    $ping_status = "open";
     1022                    break;
     1023                default:
     1024                    $ping_status = get_option("default_ping_status");
     1025                    break;
     1026            }
     1027        }
    5361028
    5371029      if ($post_more) {
     
    5481040        $dateCreated = $dateCreatedd->getIso();
    5491041        $post_date     = get_date_from_gmt(iso8601_to_datetime($dateCreated));
    550         $post_date_gmt = iso8601_to_datetime($dateCreated, GMT);
     1042        $post_date_gmt = iso8601_to_datetime($dateCreated. "Z", GMT);
    5511043      } else {
    5521044        $post_date     = current_time('mysql');
     
    5651057
    5661058      // We've got all the data -- post it:
    567       $postdata = compact('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'comment_status', 'ping_status', 'to_ping');
     1059      $postdata = compact('post_author', 'post_date', 'post_date_gmt', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'comment_status', 'ping_status', 'to_ping', 'post_type', 'post_name', 'post_password', 'post_parent', 'menu_order');
    5681060
    5691061      $post_ID = wp_insert_post($postdata);
    5701062
    5711063      if (!$post_ID) {
    572         return new IXR_Error(500, 'Sorry, your entry could not be posted. Something wrong happened.');
     1064        return new IXR_Error(500, __('Sorry, your entry could not be posted. Something wrong happened.'));
    5731065      }
    5741066
     
    6111103      }
    6121104
    613       set_current_user(0, $user_login);
    614       if ( !current_user_can('edit_post', $post_ID) )
    615         return new IXR_Error(401, 'Sorry, you can not edit this post.');
     1105        $user = set_current_user(0, $user_login);
     1106
     1107        // The post_type defaults to post, but could also be page.
     1108        $post_type = "post";
     1109        if(
     1110            !empty($content_struct["post_type"])
     1111            && ($content_struct["post_type"] == "page")
     1112        ) {
     1113            $post_type = "page";
     1114        }
     1115
     1116      // Edit page caps are checked in editPage.  Just check post here.
     1117      if ( ( 'post' == $post_type ) && !current_user_can('edit_post', $post_ID) )
     1118        return new IXR_Error(401, __('Sorry, you can not edit this post.'));
    6161119
    6171120      $postdata = wp_get_single_post($post_ID, ARRAY_A);
     1121
     1122        // If there is no post data for the give post id, stop
     1123        // now and return an error.  Other wise a new post will be
     1124        // created (which was the old behavior).
     1125        if(empty($postdata["ID"])) {
     1126            return(new IXR_Error(404, __("Invalid post id.")));
     1127        }
     1128
    6181129      extract($postdata);
    6191130        $this->escape($postdata);
     1131
     1132        // Let WordPress manage slug if none was provided.
     1133        $post_name = "";
     1134        if(isset($content_struct["wp_slug"])) {
     1135            $post_name = $content_struct["wp_slug"];
     1136        }
     1137
     1138        // Only use a password if one was given.
     1139        if(isset($content_struct["wp_password"])) {
     1140            $post_password = $content_struct["wp_password"];
     1141        }
     1142
     1143        // Only set a post parent if one was given.
     1144        if(isset($content_struct["wp_page_parent_id"])) {
     1145            $post_parent = $content_struct["wp_page_parent_id"];
     1146        }
     1147
     1148        // Only set the menu_order if it was given.
     1149        if(isset($content_struct["wp_page_order"])) {
     1150            $menu_order = $content_struct["wp_page_order"];
     1151        }
     1152
     1153        $post_author = $user->ID;
     1154
     1155        // Only set the post_author if one is set.
     1156        if(
     1157            isset($content_struct["wp_author_id"])
     1158            && ($user->ID != $content_struct["wp_author_id"])
     1159        ) {
     1160            switch($post_type) {
     1161                case "post":
     1162                    if(!current_user_can("edit_others_posts")) {
     1163                        return(new IXR_Error(401, "You are not allowed to " .
     1164                            "change the post author as this user."));
     1165                    }
     1166                    break;
     1167                case "page":
     1168                    if(!current_user_can("edit_others_pages")) {
     1169                        return(new IXR_Error(401, "You are not allowed to " .
     1170                            "change the page author as this user."));
     1171                    }
     1172                    break;
     1173                default:
     1174                    return(new IXR_Error(401, __("Invalid post type.")));
     1175                    break;
     1176            }
     1177            $post_author = $content_struct["wp_author_id"];
     1178        }
     1179
     1180        // Only set ping_status if it was provided.
     1181        if(isset($content_struct["mt_allow_pings"])) {
     1182            switch((int) $content_struct["mt_allow_pings"]) {
     1183                case 0:
     1184                    $ping_status = "closed";
     1185                    break;
     1186                case 1:
     1187                    $ping_status = "open";
     1188                    break;
     1189            }
     1190        }
    6201191
    6211192      $post_title = $content_struct['title'];
     
    6351206      $post_status = $publish ? 'publish' : 'draft';
    6361207
    637 
    638       if ( ('publish' == $post_status) && !current_user_can('publish_posts') )
    639         return new IXR_Error(401, 'Sorry, you do not have the right to publish this post.');
     1208      if ( ('publish' == $post_status) ) {
     1209        if ( ( 'page' == $post_type ) && !current_user_can('publish_pages') )
     1210            return new IXR_Error(401, __('Sorry, you do not have the right to publish this page.'));
     1211        else if ( !current_user_can('publish_posts') )
     1212            return new IXR_Error(401, __('Sorry, you do not have the right to publish this post.'));
     1213      }
    6401214
    6411215      if ($post_more) {
     
    6461220      if ( is_array($to_ping) )
    6471221        $to_ping = implode(' ', $to_ping);
     1222
     1223      if(isset($content_struct["mt_allow_comments"])) {
     1224        $comment_status = (int) $content_struct["mt_allow_comments"];
     1225      }
    6481226     
    649       $comment_status = (empty($content_struct['mt_allow_comments'])) ?
    650         get_option('default_comment_status')
    651         : $content_struct['mt_allow_comments'];
    652 
    653       $ping_status = (empty($content_struct['mt_allow_pings'])) ?
    654         get_option('default_ping_status')
    655         : $content_struct['mt_allow_pings'];
    656 
    6571227      // Do some timestamp voodoo
    6581228      $dateCreatedd = $content_struct['dateCreated'];
     
    6601230        $dateCreated = $dateCreatedd->getIso();
    6611231        $post_date     = get_date_from_gmt(iso8601_to_datetime($dateCreated));
    662         $post_date_gmt = iso8601_to_datetime($dateCreated, GMT);
     1232        $post_date_gmt = iso8601_to_datetime($dateCreated . "Z", GMT);
    6631233      } else {
    6641234        $post_date     = $postdata['post_date'];
     
    6671237
    6681238      // We've got all the data -- post it:
    669       $newpost = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'comment_status', 'ping_status', 'post_date', 'post_date_gmt', 'to_ping');
     1239      $newpost = compact('ID', 'post_content', 'post_title', 'post_category', 'post_status', 'post_excerpt', 'comment_status', 'ping_status', 'post_date', 'post_date_gmt', 'to_ping', 'post_name', 'post_password', 'post_parent', 'menu_order', 'post_author');
    6701240
    6711241      $result = wp_update_post($newpost);
    6721242      if (!$result) {
    673         return new IXR_Error(500, 'Sorry, your entry could not be edited. Something wrong happened.');
     1243        return new IXR_Error(500, __('Sorry, your entry could not be edited. Something wrong happened.'));
    6741244      }
    6751245      $this->attach_uploads( $ID, $post_content );
     
    7001270      if ($postdata['post_date'] != '') {
    7011271
    702         $post_date = mysql2date('Ymd\TH:i:s', $postdata['post_date']);
     1272        $post_date = mysql2date('Ymd\TH:i:s', $postdata['post_date_gmt']);
    7031273
    7041274        $categories = array();
     
    7101280        $post = get_extended($postdata['post_content']);
    7111281        $link = post_permalink($postdata['ID']);
     1282
     1283        // Get the author info.
     1284        $author = get_userdata($postdata['post_author']);
    7121285
    7131286        $allow_comments = ('open' == $postdata['comment_status']) ? 1 : 0;
     
    7281301          'mt_text_more' => $post['extended'],
    7291302          'mt_allow_comments' => $allow_comments,
    730           'mt_allow_pings' => $allow_pings
     1303          'mt_allow_pings' => $allow_pings,
     1304          'wp_slug' => $postdata['post_name'],
     1305          'wp_password' => $postdata['post_password'],
     1306          'wp_author_id' => $author->ID,
     1307          'wp_author_display_name'  => $author->display_name
    7311308        );
    7321309
    7331310        return $resp;
    7341311      } else {
    735         return new IXR_Error(404, 'Sorry, no such post.');
     1312        return new IXR_Error(404, __('Sorry, no such post.'));
    7361313      }
    7371314    }
     
    7551332
    7561333        if (!$posts_list) {
    757             $this->error = new IXR_Error(500, 'Either there are no posts, or something went wrong.');
     1334            $this->error = new IXR_Error(500, __('Either there are no posts, or something went wrong.'));
    7581335            return $this->error;
    7591336        }
     
    7611338        foreach ($posts_list as $entry) {
    7621339
    763             $post_date = mysql2date('Ymd\TH:i:s', $entry['post_date']);
     1340            $post_date = mysql2date('Ymd\TH:i:s', $entry['post_date_gmt']);
    7641341            $categories = array();
    7651342            $catids = wp_get_post_categories($entry['ID']);
     
    7701347            $post = get_extended($entry['post_content']);
    7711348            $link = post_permalink($entry['ID']);
     1349
     1350            // Get the post author info.
     1351            $author = get_userdata($entry['post_author']);
    7721352
    7731353            $allow_comments = ('open' == $entry['comment_status']) ? 1 : 0;
     
    7881368                'mt_text_more' => $post['extended'],
    7891369                'mt_allow_comments' => $allow_comments,
    790                 'mt_allow_pings' => $allow_pings
     1370                'mt_allow_pings' => $allow_pings,
     1371                'wp_slug' => $entry['post_name'],
     1372                'wp_password' => $entry['post_password'],
     1373                'wp_author_id' => $author->ID,
     1374                'wp_author_display_name' => $author->display_name
    7911375            );
    7921376
     
    8201404
    8211405        // FIXME: can we avoid using direct SQL there?
    822         if ($cats = $wpdb->get_results("SELECT cat_ID,cat_name FROM $wpdb->categories", ARRAY_A)) {
     1406        if ($cats = $wpdb->get_results("SELECT cat_ID,cat_name,category_parent FROM $wpdb->categories", ARRAY_A)) {
    8231407            foreach ($cats as $cat) {
    8241408                $struct['categoryId'] = $cat['cat_ID'];
     1409                $struct['parentId'] = $cat['category_parent'];
    8251410                $struct['description'] = $cat['cat_name'];
    8261411                $struct['categoryName'] = $cat['cat_name'];
     
    8521437        $bits = $data['bits'];
    8531438
     1439        if(!empty($data["overwrite"]) && ($data["overwrite"] == true)) {
     1440            // Get postmeta info on the object.
     1441            $old_file = $wpdb->get_row("
     1442                SELECT ID
     1443                FROM {$wpdb->posts}
     1444                WHERE post_title = '{$name}'
     1445                    AND post_type = 'attachment'
     1446            ");
     1447
     1448            // Delete previous file.
     1449            wp_delete_attachment($old_file->ID);
     1450
     1451            // Make sure the new name is different by pre-pending the
     1452            // previous post id.
     1453            $filename = preg_replace("/^wpid\d+-/", "", $name);
     1454            $name = "wpid{$old_file->ID}-{$filename}";
     1455        }
     1456
    8541457        logIO('O', '(MW) Received '.strlen($bits).' bytes');
    8551458
     
    8601463        if ( !current_user_can('upload_files') ) {
    8611464            logIO('O', '(MW) User does not have upload_files capability');
    862             $this->error = new IXR_Error(401, 'You are not allowed to upload files to this site.');
     1465            $this->error = new IXR_Error(401, __('You are not allowed to upload files to this site.'));
    8631466            return $this->error;
    8641467        }
     
    8671470            return new IXR_Error(500, $upload_err);
    8681471
    869         $upload = wp_upload_bits($name, $type, $bits);
     1472        $upload = wp_upload_bits($name, $type, $bits, $overwrite);
    8701473        if ( ! empty($upload['error']) ) {
    8711474            $errorString = 'Could not write file ' . $name . ' (' . $upload['error'] . ')';
     
    8841487            'guid' => $upload[ 'url' ]
    8851488        );
     1489
    8861490        // Save the data
    8871491        $id = wp_insert_attachment( $attachment, $upload[ 'file' ], $post_id );
    8881492        wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $upload['file'] ) );
    8891493
    890         return apply_filters( 'wp_handle_upload', array( 'file' => $upload[ 'file' ], 'url' => $upload[ 'url' ], 'type' => $type ) );
     1494        return apply_filters( 'wp_handle_upload', array( 'file' => $name, 'url' => $upload[ 'url' ], 'type' => $type ) );
    8911495    }
    8921496
     
    9131517
    9141518        if (!$posts_list) {
    915             $this->error = new IXR_Error(500, 'Either there are no posts, or something went wrong.');
     1519            $this->error = new IXR_Error(500, __('Either there are no posts, or something went wrong.'));
    9161520            return $this->error;
    9171521        }
     
    9191523        foreach ($posts_list as $entry) {
    9201524
    921             $post_date = mysql2date('Ymd\TH:i:s', $entry['post_date']);
     1525            $post_date = mysql2date('Ymd\TH:i:s', $entry['post_date_gmt']);
    9221526
    9231527            $struct[] = array(
     
    10161620        set_current_user(0, $user_login);
    10171621        if ( !current_user_can('edit_post', $post_ID) )
    1018             return new IXR_Error(401, 'Sorry, you can not edit this post.');
     1622            return new IXR_Error(401, __('Sorry, you can not edit this post.'));
    10191623
    10201624        foreach($categories as $cat) {
     
    10431647         support per-post text filters yet */
    10441648    function mt_supportedTextFilters($args) {
    1045         return array();
     1649        return apply_filters('xmlrpc_text_filters', array());
    10461650    }
    10471651
     
    10571661
    10581662        if (!$actual_post) {
    1059             return new IXR_Error(404, 'Sorry, no such post.');
     1663            return new IXR_Error(404, __('Sorry, no such post.'));
    10601664        }
    10611665
     
    10981702        set_current_user(0, $user_login);
    10991703        if ( !current_user_can('edit_post', $post_ID) )
    1100             return new IXR_Error(401, 'Sorry, you can not edit this post.');
     1704            return new IXR_Error(401, __('Sorry, you can not edit this post.'));
    11011705
    11021706        $postdata = wp_get_single_post($post_ID,ARRAY_A);
     
    11391743        $pos1 = strpos($pagelinkedto, str_replace(array('http://www.','http://','https://www.','https://'), '', get_option('home')));
    11401744        if( !$pos1 )
    1141                 return new IXR_Error(0, 'Is there no link to us?');
     1745                return new IXR_Error(0, __('Is there no link to us?'));
    11421746
    11431747        // let's find which post is linked to
     
    11921796
    11931797        if ( $post_ID == url_to_postid($pagelinkedfrom) )
    1194             return new IXR_Error(0, 'The source URL and the target URL cannot both point to the same resource.');
     1798            return new IXR_Error(0, __('The source URL and the target URL cannot both point to the same resource.'));
    11951799
    11961800        // Check if pings are on
     
    12021806
    12031807        if ( $wpdb->num_rows ) // We already have a Pingback from this URL
    1204             return new IXR_Error(48, 'The pingback has already been registered.');
     1808            return new IXR_Error(48, __('The pingback has already been registered.'));
    12051809
    12061810        // very stupid, but gives time to the 'from' server to publish !
     
    12101814        $linea = wp_remote_fopen( $pagelinkedfrom );
    12111815        if ( !$linea )
    1212             return new IXR_Error(16, 'The source URL does not exist.');
     1816            return new IXR_Error(16, __('The source URL does not exist.'));
    12131817
    12141818        // Work around bug in strip_tags():
     
    12201824        $title = $matchtitle[1];
    12211825        if ( empty( $title ) )
    1222             return new IXR_Error(32, 'We cannot find a title on that page.');
     1826            return new IXR_Error(32, __('We cannot find a title on that page.'));
    12231827
    12241828        $linea = strip_tags( $linea, '<a>' ); // just keep the tag we need
     
    12561860
    12571861        if ( empty($context) ) // Link to target not found
    1258             return new IXR_Error(17, 'The source URL does not contain a link to the target URL, and so cannot be used as a source.');
     1862            return new IXR_Error(17, __('The source URL does not contain a link to the target URL, and so cannot be used as a source.'));
    12591863
    12601864        $pagelinkedfrom = preg_replace('#&([^amp\;])#is', '&amp;$1', $pagelinkedfrom);
     
    13031907        if (!$actual_post) {
    13041908            // No such post = resource not found
    1305             return new IXR_Error(32, 'The specified target URL does not exist.');
     1909            return new IXR_Error(32, __('The specified target URL does not exist.'));
    13061910        }
    13071911
Note: See TracChangeset for help on using the changeset viewer.