clarify comment
[lhc/web/wiklou.git] / includes / Article.php
index 86028de..efc4f65 100644 (file)
@@ -1,7 +1,6 @@
 <?php
 /**
  * File for articles
- * @package MediaWiki
  */
 
 /**
@@ -11,7 +10,6 @@
  * Note: edit user interface and cache support functions have been
  * moved to separate EditPage and HTMLFileCache classes.
  *
- * @package MediaWiki
  */
 class Article {
        /**@{{
@@ -38,12 +36,24 @@ class Article {
        var $mUserText;                 //!<
        /**@}}*/
 
+       /**
+        * Constants used by internal components to get rollback results
+        */
+       const SUCCESS = 0;                      // Operation successful
+       const PERM_DENIED = 1;          // Permission denied
+       const BLOCKED = 2;                      // User has been blocked
+       const READONLY = 3;                     // Wiki is in read-only mode
+       const BAD_TOKEN = 4;            // Invalid token specified
+       const BAD_TITLE = 5;            // $this is not a valid Article
+       const ALREADY_ROLLED = 6;       // Someone else already rolled this back. $from and $summary will be set
+       const ONLY_AUTHOR = 7;          // User is the only author of the page
        /**
         * Constructor and clear the article
         * @param $title Reference to a Title object.
         * @param $oldId Integer revision ID, null to fetch from request, zero for current
         */
-       function Article( &$title, $oldId = null ) {
+       function __construct( &$title, $oldId = null ) {
                $this->mTitle =& $title;
                $this->mOldId = $oldId;
                $this->clear();
@@ -57,14 +67,14 @@ class Article {
        function setRedirectedFrom( $from ) {
                $this->mRedirectedFrom = $from;
        }
-       
+
        /**
         * @return mixed false, Title of in-wiki target, or string with URL
         */
        function followRedirect() {
                $text = $this->getContent();
                $rt = Title::newFromRedirect( $text );
-               
+
                # process if title object is valid and not special:userlogout
                if( $rt ) {
                        if( $rt->getInterwiki() != '' ) {
@@ -73,7 +83,7 @@ class Article {
                                        //
                                        // This can be hard to reverse and may produce loops,
                                        // so they may be disabled in the site configuration.
-                                       
+
                                        $source = $this->mTitle->getFullURL( 'redirect=no' );
                                        return $rt->getFullURL( 'rdfrom=' . urlencode( $source ) );
                                }
@@ -84,7 +94,7 @@ class Article {
                                        // the rest of the page we're on.
                                        //
                                        // This can be hard to reverse, so they may be disabled.
-                                       
+
                                        if( $rt->isSpecial( 'Userlogout' ) ) {
                                                // rolleyes
                                        } else {
@@ -94,7 +104,7 @@ class Article {
                                return $rt;
                        }
                }
-               
+
                // No or invalid redirect
                return false;
        }
@@ -247,7 +257,7 @@ class Article {
         * @param array    $conditions
         * @private
         */
-       function pageData( &$dbr, $conditions ) {
+       function pageData( $dbr, $conditions ) {
                $fields = array(
                                'page_id',
                                'page_namespace',
@@ -273,7 +283,7 @@ class Article {
         * @param Database $dbr
         * @param Title $title
         */
-       function pageDataFromTitle( &$dbr, $title ) {
+       function pageDataFromTitle( $dbr, $title ) {
                return $this->pageData( $dbr, array(
                        'page_namespace' => $title->getNamespace(),
                        'page_title'     => $title->getDBkey() ) );
@@ -283,7 +293,7 @@ class Article {
         * @param Database $dbr
         * @param int $id
         */
-       function pageDataFromId( &$dbr, $id ) {
+       function pageDataFromId( $dbr, $id ) {
                return $this->pageData( $dbr, array( 'page_id' => $id ) );
        }
 
@@ -296,17 +306,18 @@ class Article {
         */
        function loadPageData( $data = 'fromdb' ) {
                if ( $data === 'fromdb' ) {
-                       $dbr =& $this->getDB();
+                       $dbr = $this->getDB();
                        $data = $this->pageDataFromId( $dbr, $this->getId() );
                }
-                       
+
                $lc =& LinkCache::singleton();
                if ( $data ) {
                        $lc->addGoodLinkObj( $data->page_id, $this->mTitle );
 
                        $this->mTitle->mArticleID = $data->page_id;
+
+                       # Old-fashioned restrictions.
                        $this->mTitle->loadRestrictions( $data->page_restrictions );
-                       $this->mTitle->mRestrictionsLoaded = true;
 
                        $this->mCounter     = $data->page_counter;
                        $this->mTouched     = wfTimestamp( TS_MW, $data->page_touched );
@@ -333,7 +344,7 @@ class Article {
                        return $this->mContent;
                }
 
-               $dbr =& $this->getDB();
+               $dbr = $this->getDB();
 
                # Pre-fill content with error message so that if something
                # fails we'll have something telling us what we intended.
@@ -405,9 +416,8 @@ class Article {
         *
         * @return Database
         */
-       function &getDB() {
-               $ret =& wfGetDB( DB_MASTER );
-               return $ret;
+       function getDB() {
+               return wfGetDB( DB_MASTER );
        }
 
        /**
@@ -455,7 +465,7 @@ class Article {
                        if ( $id == 0 ) {
                                $this->mCounter = 0;
                        } else {
-                               $dbr =& wfGetDB( DB_SLAVE );
+                               $dbr = wfGetDB( DB_SLAVE );
                                $this->mCounter = $dbr->selectField( 'page', 'page_counter', array( 'page_id' => $id ),
                                        'Article::getCount', $this->getSelectOptions() );
                        }
@@ -471,12 +481,12 @@ class Article {
         * @return bool
         */
        function isCountable( $text ) {
-               global $wgUseCommaCount, $wgContentNamespaces;
+               global $wgUseCommaCount;
 
                $token = $wgUseCommaCount ? ',' : '[[';
                return
-                       array_search( $this->mTitle->getNamespace(), $wgContentNamespaces ) !== false
-                       && ! $this->isRedirect( $text )
+                       $this->mTitle->isContentPage()
+                       && !$this->isRedirect( $text )
                        && in_string( $token, $text );
        }
 
@@ -502,6 +512,10 @@ class Article {
         * @return bool
         */
        function isCurrent() {
+               # If no oldid, this is the current version.
+               if ($this->getOldID() == 0)
+                       return true;
+
                return $this->exists() &&
                        isset( $this->mRevision ) &&
                        $this->mRevision->isCurrent();
@@ -573,7 +587,7 @@ class Article {
                # XXX: this is expensive; cache this info somewhere.
 
                $contribs = array();
-               $dbr =& wfGetDB( DB_SLAVE );
+               $dbr = wfGetDB( DB_SLAVE );
                $revTable = $dbr->tableName( 'revision' );
                $userTable = $dbr->tableName( 'user' );
                $user = $this->getUser();
@@ -606,14 +620,14 @@ class Article {
        function view() {
                global $wgUser, $wgOut, $wgRequest, $wgContLang;
                global $wgEnableParserCache, $wgStylePath, $wgUseRCPatrol, $wgParser;
-               global $wgUseTrackbacks, $wgNamespaceRobotPolicies;
+               global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
                $sk = $wgUser->getSkin();
 
                wfProfileIn( __METHOD__ );
 
                $parserCache =& ParserCache::singleton();
                $ns = $this->mTitle->getNamespace(); # shortcut
-               
+
                # Get variables from query string
                $oldid = $this->getOldID();
 
@@ -627,14 +641,23 @@ class Article {
                $diff = $wgRequest->getVal( 'diff' );
                $rcid = $wgRequest->getVal( 'rcid' );
                $rdfrom = $wgRequest->getVal( 'rdfrom' );
+               $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
 
                $wgOut->setArticleFlag( true );
-               if ( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
+
+               # Discourage indexing of printable versions, but encourage following
+               if( $wgOut->isPrintable() ) {
+                       $policy = 'noindex,follow';
+               } elseif ( isset( $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()] ) ) {
+                       $policy = $wgArticleRobotPolicies[$this->mTitle->getPrefixedText()];
+               } elseif( isset( $wgNamespaceRobotPolicies[$ns] ) ) {
+                       # Honour customised robot policies for this namespace
                        $policy = $wgNamespaceRobotPolicies[$ns];
                } else {
+                       # Default to encourage indexing and following links
                        $policy = 'index,follow';
                }
-               $wgOut->setRobotpolicy( $policy );
+               $wgOut->setRobotPolicy( $policy );
 
                # If we got diff and oldid in the query, we want to see a
                # diff page instead of the article.
@@ -645,8 +668,8 @@ class Article {
                        $de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid );
                        // DifferenceEngine directly fetched the revision:
                        $this->mRevIdFetched = $de->mNewid;
-                       $de->showDiffPage();
-                       
+                       $de->showDiffPage( $diffOnly );
+
                        // Needed to get the page's current revision
                        $this->loadPageData();
                        if( $diff == 0 || $diff == $this->mLatest ) {
@@ -656,7 +679,7 @@ class Article {
                        wfProfileOut( __METHOD__ );
                        return;
                }
-               
+
                if ( empty( $oldid ) && $this->checkTouched() ) {
                        $wgOut->setETag($parserCache->getETag($this, $wgUser));
 
@@ -673,10 +696,12 @@ class Article {
                }
 
                # Should the parser cache be used?
-               $pcache = $wgEnableParserCache &&
-                       intval( $wgUser->getOption( 'stubthreshold' ) ) == 0 &&
-                       $this->exists() &&
-                       empty( $oldid );
+               $pcache = $wgEnableParserCache
+                       && intval( $wgUser->getOption( 'stubthreshold' ) ) == 0
+                       && $this->exists()
+                       && empty( $oldid )
+                       && !$this->mTitle->isCssOrJsPage()
+                       && !$this->mTitle->isCssJsSubpage();
                wfDebug( 'Article::view using parser cache: ' . ($pcache ? 'yes' : 'no' ) . "\n" );
                if ( $wgUser->getOption( 'stubthreshold' ) ) {
                        wfIncrStats( 'pcache_miss_stub' );
@@ -691,6 +716,12 @@ class Article {
                                $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom, '', 'redirect=no' );
                                $s = wfMsg( 'redirectedfrom', $redir );
                                $wgOut->setSubtitle( $s );
+
+                               // Set the fragment if one was specified in the redirect
+                               if ( strval( $this->mTitle->getFragment() ) != '' ) {
+                                       $fragment = Xml::escapeJsString( $this->mTitle->getFragmentForURL() );
+                                       $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
+                               }
                                $wasRedirected = true;
                        }
                } elseif ( !empty( $rdfrom ) ) {
@@ -705,11 +736,14 @@ class Article {
                                $wasRedirected = true;
                        }
                }
-               
+
                $outputDone = false;
+               wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
                if ( $pcache ) {
                        if ( $wgOut->tryParserCache( $this, $wgUser ) ) {
-                               wfRunHooks( 'ArticleViewHeader', array( &$this ) );
+                               // Ensure that UI elements requiring revision ID have
+                               // the correct version information.
+                               $wgOut->setRevisionId( $this->mLatest );
                                $outputDone = true;
                        }
                }
@@ -756,21 +790,24 @@ class Article {
                        }
                }
                if( !$outputDone ) {
-                       /**
-                        * @fixme: this hook doesn't work most of the time, as it doesn't
-                        * trigger when the parser cache is used.
-                        */
-                       wfRunHooks( 'ArticleViewHeader', array( &$this ) ) ;
                        $wgOut->setRevisionId( $this->getRevIdFetched() );
-                       # wrap user css and user js in pre and don't parse
-                       # XXX: use $this->mTitle->usCssJsSubpage() when php is fixed/ a workaround is found
-                       if (
-                               $ns == NS_USER &&
-                               preg_match('/\\/[\\w]+\\.(css|js)$/', $this->mTitle->getDBkey())
-                       ) {
-                               $wgOut->addWikiText( wfMsg('clearyourcache'));
-                               $wgOut->addHTML( '<pre>'.htmlspecialchars($this->mContent)."\n</pre>" );
-                       } else if ( $rt = Title::newFromRedirect( $text ) ) {
+                       
+                        // Pages containing custom CSS or JavaScript get special treatment
+                       if( $this->mTitle->isCssOrJsPage() || $this->mTitle->isCssJsSubpage() ) {
+                               $wgOut->addHtml( wfMsgExt( 'clearyourcache', 'parse' ) );
+
+                               // Give hooks a chance to customise the output
+                               if( wfRunHooks( 'ShowRawCssJs', array( $this->mContent, $this->mTitle, $wgOut ) ) ) {
+                                       // Wrap the whole lot in a <pre> and don't parse
+                                       preg_match( '!\.(css|js)$!u', $this->mTitle->getText(), $m );
+                                       $wgOut->addHtml( "<pre class=\"mw-code mw-{$m[1]}\" dir=\"ltr\">\n" );
+                                       $wgOut->addHtml( htmlspecialchars( $this->mContent ) );
+                                       $wgOut->addHtml( "\n</pre>\n" );
+                               }
+                       
+                       }
+                       
+                       elseif ( $rt = Title::newFromRedirect( $text ) ) {
                                # Display redirect
                                $imageDir = $wgContLang->isRTL() ? 'rtl' : 'ltr';
                                $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
@@ -778,16 +815,16 @@ class Article {
                                if( !$wasRedirected && $this->isCurrent() ) {
                                        $wgOut->setSubtitle( wfMsgHtml( 'redirectpagesub' ) );
                                }
-                               $link = $sk->makeLinkObj( $rt );
+                               $link = $sk->makeLinkObj( $rt, $rt->getFullText() );
 
-                               $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT" />' .
+                               $wgOut->addHTML( '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
                                  '<span class="redirectText">'.$link.'</span>' );
 
                                $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser));
                                $wgOut->addParserOutputNoText( $parseout );
                        } else if ( $pcache ) {
                                # Display content and save to parser cache
-                               $wgOut->addPrimaryWikiText( $text, $this );
+                               $this->outputWikiText( $text );
                        } else {
                                # Display content, don't attempt to save to parser cache
                                # Don't show section-edit links on old revisions... this way lies madness.
@@ -795,11 +832,21 @@ class Article {
                                        $oldEditSectionSetting = $wgOut->parserOptions()->setEditSection( false );
                                }
                                # Display content and don't save to parser cache
-                               $wgOut->addPrimaryWikiText( $text, $this, false );
+                               # With timing hack -- TS 2006-07-26
+                               $time = -wfTime();
+                               $this->outputWikiText( $text, false );
+                               $time += wfTime();
+
+                               # Timing hack
+                               if ( $time > 3 ) {
+                                       wfDebugLog( 'slow-parse', sprintf( "%-5.2f %s", $time,
+                                               $this->mTitle->getPrefixedDBkey()));
+                               }
 
                                if( !$this->isCurrent() ) {
                                        $wgOut->parserOptions()->setEditSection( $oldEditSectionSetting );
                                }
+
                        }
                }
                /* title may have been set from the cache */
@@ -819,8 +866,9 @@ class Article {
                if ( $wgUseRCPatrol && !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) ) {
                        $wgOut->addHTML(
                                "<div class='patrollink'>" .
-                                       wfMsg ( 'markaspatrolledlink',
-                                       $sk->makeKnownLinkObj( $this->mTitle, wfMsg('markaspatrolledtext'), "action=markpatrolled&rcid=$rcid" )
+                                       wfMsgHtml( 'markaspatrolledlink',
+                                       $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml('markaspatrolledtext'),
+                                               "action=markpatrolled&rcid=$rcid" )
                                        ) .
                                '</div>'
                         );
@@ -837,7 +885,7 @@ class Article {
        function addTrackbacks() {
                global $wgOut, $wgUser;
 
-               $dbr =& wfGetDB(DB_SLAVE);
+               $dbr = wfGetDB(DB_SLAVE);
                $tbs = $dbr->select(
                                /* FROM   */ 'trackbacks',
                                /* SELECT */ array('tb_id', 'tb_title', 'tb_url', 'tb_ex', 'tb_name'),
@@ -852,8 +900,8 @@ class Article {
                        $rmvtxt = "";
                        if ($wgUser->isAllowed( 'trackback' )) {
                                $delurl = $this->mTitle->getFullURL("action=deletetrackback&tbid="
-                                               . $o->tb_id . "&token=" . $wgUser->editToken());
-                               $rmvtxt = wfMsg('trackbackremove', $delurl);
+                                               . $o->tb_id . "&token=" . urlencode( $wgUser->editToken() ) );
+                               $rmvtxt = wfMsg( 'trackbackremove', htmlspecialchars( $delurl ) );
                        }
                        $tbtext .= wfMsg(strlen($o->tb_ex) ? 'trackbackexcerpt' : 'trackback',
                                        $o->tb_title,
@@ -883,7 +931,7 @@ class Article {
                        return;
                }
 
-               $db =& wfGetDB(DB_MASTER);
+               $db = wfGetDB(DB_MASTER);
                $db->delete('trackbacks', array('tb_id' => $wgRequest->getInt('tbid')));
                $wgTitle->invalidateCache();
                $wgOut->addWikiText(wfMsg('trackbackdeleteok'));
@@ -902,7 +950,7 @@ class Article {
        function purge() {
                global $wgUser, $wgRequest, $wgOut;
 
-               if ( $wgUser->isLoggedIn() || $wgRequest->wasPosted() ) {
+               if ( $wgUser->isAllowed( 'purge' ) || $wgRequest->wasPosted() ) {
                        if( wfRunHooks( 'ArticlePurge', array( &$this ) ) ) {
                                $this->doPurge();
                        }
@@ -920,7 +968,7 @@ class Article {
                        $wgOut->addHTML( $msg );
                }
        }
-       
+
        /**
         * Perform the actions of a page purging
         */
@@ -949,11 +997,10 @@ class Article {
         * Best if all done inside a transaction.
         *
         * @param Database $dbw
-        * @param string   $restrictions
         * @return int     The newly created page_id key
         * @private
         */
-       function insertOn( &$dbw, $restrictions = '' ) {
+       function insertOn( $dbw ) {
                wfProfileIn( __METHOD__ );
 
                $page_id = $dbw->nextSequenceValue( 'page_page_id_seq' );
@@ -962,7 +1009,7 @@ class Article {
                        'page_namespace'    => $this->mTitle->getNamespace(),
                        'page_title'        => $this->mTitle->getDBkey(),
                        'page_counter'      => 0,
-                       'page_restrictions' => $restrictions,
+                       'page_restrictions' => '',
                        'page_is_redirect'  => 0, # Will set this shortly...
                        'page_is_new'       => 1,
                        'page_random'       => wfRandom(),
@@ -988,7 +1035,7 @@ class Article {
         *                          when different from the currently set value.
         *                          Giving 0 indicates the new page flag should
         *                          be set on.
-        * @param bool $lastRevIsRedirect If given, will optimize adding and 
+        * @param bool $lastRevIsRedirect If given, will optimize adding and
         *                                                      removing rows in redirect table.
         * @return bool true on success, false on failure
         * @private
@@ -998,7 +1045,7 @@ class Article {
 
                $text = $revision->getText();
                $rt = Title::newFromRedirect( $text );
-               
+
                $conditions = array( 'page_id' => $this->getId() );
                if( !is_null( $lastRevision ) ) {
                        # An extra check against threads stepping on each other
@@ -1020,20 +1067,20 @@ class Article {
 
                if ($result) {
                        // FIXME: Should the result from updateRedirectOn() be returned instead?
-                       $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect ); 
+                       $this->updateRedirectOn( $dbw, $rt, $lastRevIsRedirect );
                }
-               
+
                wfProfileOut( __METHOD__ );
                return $result;
        }
 
        /**
-        * Add row to the redirect table if this is a redirect, remove otherwise. 
+        * Add row to the redirect table if this is a redirect, remove otherwise.
         *
         * @param Database $dbw
         * @param $redirectTitle a title object pointing to the redirect target,
-        *                                                      or NULL if this is not a redirect  
-        * @param bool $lastRevIsRedirect If given, will optimize adding and 
+        *                                                      or NULL if this is not a redirect
+        * @param bool $lastRevIsRedirect If given, will optimize adding and
         *                                                      removing rows in redirect table.
         * @return bool true on success, false on failure
         * @private
@@ -1059,7 +1106,7 @@ class Article {
 
                                $dbw->replace( 'redirect', array( 'rd_from' ), $set, __METHOD__ );
                        } else {
-                               // This is not a redirect, remove row from redirect table 
+                               // This is not a redirect, remove row from redirect table
                                $where = array( 'rd_from' => $this->getId() );
                                $dbw->delete( 'redirect', $where, __METHOD__);
                        }
@@ -1067,7 +1114,7 @@ class Article {
                        wfProfileOut( __METHOD__ );
                        return ( $dbw->affectedRows() != 0 );
                }
-               
+
                return true;
        }
 
@@ -1111,14 +1158,14 @@ class Article {
         */
        function replaceSection($section, $text, $summary = '', $edittime = NULL) {
                wfProfileIn( __METHOD__ );
-               
+
                if( $section == '' ) {
                        // Whole-page edit; let the text through unmolested.
                } else {
                        if( is_null( $edittime ) ) {
                                $rev = Revision::newFromTitle( $this->mTitle );
                        } else {
-                               $dbw =& wfGetDB( DB_MASTER );
+                               $dbw = wfGetDB( DB_MASTER );
                                $rev = Revision::loadFromTimestamp( $dbw, $this->mTitle, $edittime );
                        }
                        if( is_null( $rev ) ) {
@@ -1128,13 +1175,18 @@ class Article {
                        }
                        $oldtext = $rev->getText();
 
-                       if($section=='new') {
-                               if($summary) $subject="== {$summary} ==\n\n";
-                               $text=$oldtext."\n\n".$subject.$text;
+                       if( $section == 'new' ) {
+                               # Inserting a new section
+                               $subject = $summary ? "== {$summary} ==\n\n" : '';
+                               $text = strlen( trim( $oldtext ) ) > 0
+                                               ? "{$oldtext}\n\n{$subject}{$text}"
+                                               : "{$subject}{$text}";
                        } else {
+                               # Replacing an existing section; roll out the big guns
                                global $wgParser;
                                $text = $wgParser->replaceSection( $oldtext, $section, $text );
                        }
+
                }
 
                wfProfileOut( __METHOD__ );
@@ -1153,10 +1205,10 @@ class Article {
                if ( $comment && $summary != "" ) {
                        $text = "== {$summary} ==\n\n".$text;
                }
-               
+
                $this->doEdit( $text, $summary, $flags );
 
-               $dbw =& wfGetDB( DB_MASTER );
+               $dbw = wfGetDB( DB_MASTER );
                if ($watchthis) {
                        if (!$this->mTitle->userIsWatching()) {
                                $dbw->begin();
@@ -1183,7 +1235,7 @@ class Article {
 
                $good = $this->doEdit( $text, $summary, $flags );
                if ( $good ) {
-                       $dbw =& wfGetDB( DB_MASTER );
+                       $dbw = wfGetDB( DB_MASTER );
                        if ($watchthis) {
                                if (!$this->mTitle->userIsWatching()) {
                                        $dbw->begin();
@@ -1206,7 +1258,7 @@ class Article {
        /**
         * Article::doEdit()
         *
-        * Change an existing article or create a new article. Updates RC and all necessary caches, 
+        * Change an existing article or create a new article. Updates RC and all necessary caches,
         * optionally via the deferred update array.
         *
         * $wgUser must be set before calling this function.
@@ -1228,9 +1280,9 @@ class Article {
         *          Defer some of the updates until the end of index.php
         *      EDIT_AUTOSUMMARY
         *          Fill in blank summaries with generated text where possible
-        * 
-        * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected. 
-        * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If 
+        *
+        * If neither EDIT_NEW nor EDIT_UPDATE is specified, the status of the article will be detected.
+        * If EDIT_UPDATE is specified and the article doesn't exist, the function will return false. If
         * EDIT_NEW is specified and the article does exist, a duplicate key error will cause an exception
         * to be thrown from the Database. These two conditions are also possible with auto-detection due
         * to MediaWiki's performance-optimised locking strategy.
@@ -1254,7 +1306,7 @@ class Article {
 
                if( !wfRunHooks( 'ArticleSave', array( &$this, &$wgUser, &$text,
                        &$summary, $flags & EDIT_MINOR,
-                       null, null, &$flags ) ) ) 
+                       null, null, &$flags ) ) )
                {
                        wfDebug( __METHOD__ . ": ArticleSave hook aborted save!\n" );
                        wfProfileOut( __METHOD__ );
@@ -1267,17 +1319,17 @@ class Article {
 
                $oldtext = $this->getContent();
                $oldsize = strlen( $oldtext );
-               $newsize = strlen( $text );
 
                # Provide autosummaries if one is not provided.
                if ($flags & EDIT_AUTOSUMMARY && $summary == '')
                        $summary = $this->getAutosummary( $oldtext, $text, $flags );
 
                $text = $this->preSaveTransform( $text );
+               $newsize = strlen( $text );
 
-               $dbw =& wfGetDB( DB_MASTER );
+               $dbw = wfGetDB( DB_MASTER );
                $now = wfTimestampNow();
-               
+
                if ( $flags & EDIT_UPDATE ) {
                        # Update article, but only if changed.
 
@@ -1303,7 +1355,7 @@ class Article {
                                        wfProfileOut( __METHOD__ );
                                        return false;
                                }
-                               
+
                                $revision = new Revision( array(
                                        'page'       => $this->getId(),
                                        'comment'    => $summary,
@@ -1327,12 +1379,14 @@ class Article {
                                                $rcid = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $wgUser, $summary,
                                                        $lastRevision, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
                                                        $revisionId );
-                                                       
-                                               # Mark as patrolled if the user can do so and has it set in their options
-                                               if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
+
+                                               # Mark as patrolled if the user can do so
+                                               if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
                                                        RecentChange::markPatrolled( $rcid );
+                                                       PatrolLog::record( $rcid, true );
                                                }
                                        }
+                                       $wgUser->incEditCount();
                                        $dbw->commit();
                                }
                        } else {
@@ -1348,19 +1402,19 @@ class Article {
                        }
 
                        if ( $good ) {
-                               # Invalidate cache of this article and all pages using this article 
+                               # Invalidate cache of this article and all pages using this article
                                # as a template. Partly deferred.
                                Article::onArticleEdit( $this->mTitle );
-                               
+
                                # Update links tables, site stats, etc.
                                $changed = ( strcmp( $oldtext, $text ) != 0 );
                                $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
                        }
                } else {
                        # Create new article
-                       
+
                        # Set statistics members
-                       # We work out if it's countable after PST to avoid counter drift 
+                       # We work out if it's countable after PST to avoid counter drift
                        # when articles are created with {{subst:}}
                        $this->mGoodAdjustment = (int)$this->isCountable( $text );
                        $this->mTotalAdjustment = 1;
@@ -1388,11 +1442,13 @@ class Article {
                        if( !( $flags & EDIT_SUPPRESS_RC ) ) {
                                $rcid = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $wgUser, $summary, $bot,
                                  '', strlen( $text ), $revisionId );
-                               # Mark as patrolled if the user can and has the option set
-                               if( $wgUser->isAllowed( 'patrol' ) && $wgUser->getOption( 'autopatrol' ) ) {
+                               # Mark as patrolled if the user can
+                               if( $GLOBALS['wgUseRCPatrol'] && $wgUser->isAllowed( 'autopatrol' ) ) {
                                        RecentChange::markPatrolled( $rcid );
+                                       PatrolLog::record( $rcid, true );
                                }
                        }
+                       $wgUser->incEditCount();
                        $dbw->commit();
 
                        # Update links, etc.
@@ -1414,7 +1470,7 @@ class Article {
                        array( &$this, &$wgUser, $text,
                        $summary, $flags & EDIT_MINOR,
                        null, null, &$flags ) );
-               
+
                wfProfileOut( __METHOD__ );
                return $good;
        }
@@ -1442,40 +1498,66 @@ class Article {
                }
                $wgOut->redirect( $this->mTitle->getFullURL( $query ) . $sectionAnchor );
        }
-               
+
        /**
         * Mark this particular edit as patrolled
         */
        function markpatrolled() {
                global $wgOut, $wgRequest, $wgUseRCPatrol, $wgUser;
-               $wgOut->setRobotpolicy( 'noindex,nofollow' );
+               $wgOut->setRobotPolicy( 'noindex,nofollow' );
 
                # Check RC patrol config. option
                if( !$wgUseRCPatrol ) {
                        $wgOut->errorPage( 'rcpatroldisabled', 'rcpatroldisabledtext' );
                        return;
                }
-               
+
                # Check permissions
                if( !$wgUser->isAllowed( 'patrol' ) ) {
                        $wgOut->permissionRequired( 'patrol' );
                        return;
                }
-               
+
+               # If we haven't been given an rc_id value, we can't do anything
                $rcid = $wgRequest->getVal( 'rcid' );
-               if ( !is_null ( $rcid ) ) {
-                       if( wfRunHooks( 'MarkPatrolled', array( &$rcid, &$wgUser, false ) ) ) {
-                               RecentChange::markPatrolled( $rcid );
-                               wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
-                               $wgOut->setPagetitle( wfMsg( 'markedaspatrolled' ) );
-                               $wgOut->addWikiText( wfMsg( 'markedaspatrolledtext' ) );
-                       }
-                       $rcTitle = SpecialPage::getTitleFor( 'Recentchanges' );
-                       $wgOut->returnToMain( false, $rcTitle->getPrefixedText() );
+               if( !$rcid ) {
+                       $wgOut->errorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
+                       return;
                }
-               else {
-                       $wgOut->showErrorPage( 'markedaspatrollederror', 'markedaspatrollederrortext' );
+
+               # Handle the 'MarkPatrolled' hook
+               if( !wfRunHooks( 'MarkPatrolled', array( $rcid, &$wgUser, false ) ) ) {
+                       return;
                }
+
+               $return = SpecialPage::getTitleFor( 'Recentchanges' );
+               # If it's left up to us, check that the user is allowed to patrol this edit
+               # If the user has the "autopatrol" right, then we'll assume there are no
+               # other conditions stopping them doing so
+               if( !$wgUser->isAllowed( 'autopatrol' ) ) {
+                       $rc = RecentChange::newFromId( $rcid );
+                       # Graceful error handling, as we've done before here...
+                       # (If the recent change doesn't exist, then it doesn't matter whether
+                       # the user is allowed to patrol it or not; nothing is going to happen
+                       if( is_object( $rc ) && $wgUser->getName() == $rc->getAttribute( 'rc_user_text' ) ) {
+                               # The user made this edit, and can't patrol it
+                               # Tell them so, and then back off
+                               $wgOut->setPageTitle( wfMsg( 'markedaspatrollederror' ) );
+                               $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrollederror-noautopatrol' ) );
+                               $wgOut->returnToMain( false, $return );
+                               return;
+                       }
+               }
+
+               # Mark the edit as patrolled
+               RecentChange::markPatrolled( $rcid );
+               PatrolLog::record( $rcid );
+               wfRunHooks( 'MarkPatrolledComplete', array( &$rcid, &$wgUser, false ) );
+
+               # Inform the user
+               $wgOut->setPageTitle( wfMsg( 'markedaspatrolled' ) );
+               $wgOut->addWikiText( wfMsgNoTrans( 'markedaspatrolledtext' ) );
+               $wgOut->returnToMain( false, $return );
        }
 
        /**
@@ -1494,7 +1576,7 @@ class Article {
                        $wgOut->readOnlyPage();
                        return;
                }
-               
+
                if( $this->doWatch() ) {
                        $wgOut->setPagetitle( wfMsg( 'addedwatch' ) );
                        $wgOut->setRobotpolicy( 'noindex,nofollow' );
@@ -1506,7 +1588,7 @@ class Article {
 
                $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
        }
-       
+
        /**
         * Add this page to $wgUser's watchlist
         * @return bool true on successful watch operation
@@ -1516,13 +1598,13 @@ class Article {
                if( $wgUser->isAnon() ) {
                        return false;
                }
-               
+
                if (wfRunHooks('WatchArticle', array(&$wgUser, &$this))) {
                        $wgUser->addWatch( $this->mTitle );
 
                        return wfRunHooks('WatchArticleComplete', array(&$wgUser, &$this));
                }
-               
+
                return false;
        }
 
@@ -1541,7 +1623,7 @@ class Article {
                        $wgOut->readOnlyPage();
                        return;
                }
-               
+
                if( $this->doUnwatch() ) {
                        $wgOut->setPagetitle( wfMsg( 'removedwatch' ) );
                        $wgOut->setRobotpolicy( 'noindex,nofollow' );
@@ -1553,7 +1635,7 @@ class Article {
 
                $wgOut->returnToMain( true, $this->mTitle->getPrefixedText() );
        }
-       
+
        /**
         * Stop watching a page
         * @return bool true on successful unwatch
@@ -1569,7 +1651,7 @@ class Article {
 
                        return wfRunHooks('UnwatchArticleComplete', array(&$wgUser, &$this));
                }
-               
+
                return false;
        }
 
@@ -1578,7 +1660,7 @@ class Article {
         */
        function protect() {
                $form = new ProtectionForm( $this );
-               $form->show();
+               $form->execute();
        }
 
        /**
@@ -1595,14 +1677,21 @@ class Article {
         * @param string $reason
         * @return bool true on success
         */
-       function updateRestrictions( $limit = array(), $reason = '' ) {
+       function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = null ) {
                global $wgUser, $wgRestrictionTypes, $wgContLang;
-               
+
                $id = $this->mTitle->getArticleID();
                if( !$wgUser->isAllowed( 'protect' ) || wfReadOnly() || $id == 0 ) {
                        return false;
                }
 
+               if (!$cascade) {
+                       $cascade = false;
+               }
+
+               // Take this opportunity to purge out expired restrictions
+               Title::purgeExpiredRestrictions();
+
                # FIXME: Same limitations as described in ProtectionForm.php (line 37);
                # we expect a single selection, but the schema allows otherwise.
                $current = array();
@@ -1611,48 +1700,95 @@ class Article {
 
                $current = Article::flattenRestrictions( $current );
                $updated = Article::flattenRestrictions( $limit );
-               
+
                $changed = ( $current != $updated );
+               $changed = $changed || ($this->mTitle->areRestrictionsCascading() != $cascade);
+               $changed = $changed || ($this->mTitle->mRestrictionsExpiry != $expiry);
                $protect = ( $updated != '' );
-               
+
                # If nothing's changed, do nothing
                if( $changed ) {
+                       global $wgGroupPermissions;
                        if( wfRunHooks( 'ArticleProtect', array( &$this, &$wgUser, $limit, $reason ) ) ) {
 
-                               $dbw =& wfGetDB( DB_MASTER );
-                               
+                               $dbw = wfGetDB( DB_MASTER );
+
+                               $encodedExpiry = Block::encodeExpiry($expiry, $dbw );
+
+                               $expiry_description = '';
+                               if ( $encodedExpiry != 'infinity' ) {
+                                       $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
+                               }
+
                                # Prepare a null revision to be added to the history
-                               $comment = $wgContLang->ucfirst( wfMsgForContent( $protect ? 'protectedarticle' : 'unprotectedarticle', $this->mTitle->getPrefixedText() ) );
+                               $modified = $current != '' && $protect;
+                               if ( $protect ) {
+                                       $comment_type = $modified ? 'modifiedarticleprotection' : 'protectedarticle';
+                               } else {
+                                       $comment_type = 'unprotectedarticle';
+                               }
+                               $comment = $wgContLang->ucfirst( wfMsgForContent( $comment_type, $this->mTitle->getPrefixedText() ) );
+
+                               foreach( $limit as $action => $restrictions ) {
+                                       # Check if the group level required to edit also can protect pages
+                                       # Otherwise, people who cannot normally protect can "protect" pages via transclusion
+                                       $cascade = ( $cascade && isset($wgGroupPermissions[$restrictions]['protect']) && $wgGroupPermissions[$restrictions]['protect'] );       
+                               }
+                               
+                               $cascade_description = '';
+                               if ($cascade) {
+                                       $cascade_description = ' ['.wfMsg('protect-summary-cascade').']';
+                               }
+
                                if( $reason )
                                        $comment .= ": $reason";
                                if( $protect )
                                        $comment .= " [$updated]";
+                               if ( $expiry_description && $protect )
+                                       $comment .= "$expiry_description";
+                               if ( $cascade )
+                                       $comment .= "$cascade_description";
+
                                $nullRevision = Revision::newNullRevision( $dbw, $id, $comment, true );
                                $nullRevId = $nullRevision->insertOn( $dbw );
-                       
+
+                               # Update restrictions table
+                               foreach( $limit as $action => $restrictions ) {
+                                       if ($restrictions != '' ) {
+                                               $dbw->replace( 'page_restrictions', array(array('pr_page', 'pr_type')),
+                                                       array( 'pr_page' => $id, 'pr_type' => $action
+                                                               , 'pr_level' => $restrictions, 'pr_cascade' => $cascade ? 1 : 0
+                                                               , 'pr_expiry' => $encodedExpiry ), __METHOD__  );
+                                       } else {
+                                               $dbw->delete( 'page_restrictions', array( 'pr_page' => $id,
+                                                       'pr_type' => $action ), __METHOD__ );
+                                       }
+                               }
+
                                # Update page record
                                $dbw->update( 'page',
                                        array( /* SET */
                                                'page_touched' => $dbw->timestamp(),
-                                               'page_restrictions' => $updated,
+                                               'page_restrictions' => '',
                                                'page_latest' => $nullRevId
                                        ), array( /* WHERE */
                                                'page_id' => $id
                                        ), 'Article::protect'
                                );
                                wfRunHooks( 'ArticleProtectComplete', array( &$this, &$wgUser, $limit, $reason ) );
-       
+
                                # Update the protection log
                                $log = new LogPage( 'protect' );
+
                                if( $protect ) {
-                                       $log->addEntry( 'protect', $this->mTitle, trim( $reason . " [$updated]" ) );
+                                       $log->addEntry( $modified ? 'modify' : 'protect', $this->mTitle, trim( $reason . " [$updated]$cascade_description$expiry_description" ) );
                                } else {
                                        $log->addEntry( 'unprotect', $this->mTitle, $reason );
                                }
-                               
+
                        } # End hook
                } # End "changed" check
-               
+
                return true;
        }
 
@@ -1705,9 +1841,9 @@ class Article {
                }
 
                $wgOut->setPagetitle( wfMsg( 'confirmdelete' ) );
-               
+
                # Better double-check that it hasn't been deleted yet!
-               $dbw =& wfGetDB( DB_MASTER );
+               $dbw = wfGetDB( DB_MASTER );
                $conds = $this->mTitle->pageCond();
                $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
                if ( $latest === false ) {
@@ -1717,6 +1853,11 @@ class Article {
 
                if( $confirm ) {
                        $this->doDelete( $reason );
+                       if( $wgRequest->getCheck( 'wpWatch' ) ) {
+                               $this->doWatch();
+                       } elseif( $this->mTitle->userIsWatching() ) {
+                               $this->doUnwatch();
+                       }
                        return;
                }
 
@@ -1724,7 +1865,7 @@ class Article {
                # and insert a warning if it does
                $maxRevisions = 20;
                $authors = $this->getLastNAuthors( $maxRevisions, $latest );
-               
+
                if( count( $authors ) > 1 && !$confirm ) {
                        $skin=$wgUser->getSkin();
                        $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
@@ -1768,7 +1909,7 @@ class Article {
                                $reason = wfMsgForContent( 'exblank' );
                        }
 
-                       if( $length < 500 && $reason === '' ) {
+                       if( $reason === '' ) {
                                # comment field=255, let's grep the first 150 to have some user
                                # space left
                                global $wgContLang;
@@ -1804,7 +1945,7 @@ class Article {
                // First try the slave
                // If that doesn't have the latest revision, try the master
                $continue = 2;
-               $db =& wfGetDB( DB_SLAVE );
+               $db = wfGetDB( DB_SLAVE );
                do {
                        $res = $db->select( array( 'page', 'revision' ),
                                array( 'rev_id', 'rev_user_text' ),
@@ -1823,7 +1964,7 @@ class Article {
                        }
                        $row = $db->fetchObject( $res );
                        if ( $continue == 2 && $revLatest && $row->rev_id != $revLatest ) {
-                               $db =& wfGetDB( DB_MASTER );
+                               $db = wfGetDB( DB_MASTER );
                                $continue--;
                        } else {
                                $continue = 0;
@@ -1837,7 +1978,7 @@ class Article {
                wfProfileOut( __METHOD__ );
                return $authors;
        }
-       
+
        /**
         * Output deletion confirmation dialog
         */
@@ -1856,6 +1997,7 @@ class Article {
                $confirm = htmlspecialchars( wfMsg( 'deletepage' ) );
                $delcom = htmlspecialchars( wfMsg( 'deletecomment' ) );
                $token = htmlspecialchars( $wgUser->editToken() );
+               $watch = Xml::checkLabel( wfMsg( 'watchthis' ), 'wpWatch', 'wpWatch', $wgUser->getBoolOption( 'watchdeletion' ) || $this->mTitle->userIsWatching(), array( 'tabindex' => '2' ) );
 
                $wgOut->addHTML( "
 <form id='deleteconfirm' method='post' action=\"{$formaction}\">
@@ -1865,13 +2007,17 @@ class Article {
                                <label for='wpReason'>{$delcom}:</label>
                        </td>
                        <td align='left'>
-                               <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" />
+                               <input type='text' size='60' name='wpReason' id='wpReason' value=\"" . htmlspecialchars( $reason ) . "\" tabindex=\"1\" />
                        </td>
                </tr>
+               <tr>
+                       <td>&nbsp;</td>
+                       <td>$watch</td>
+               </tr>
                <tr>
                        <td>&nbsp;</td>
                        <td>
-                               <input type='submit' name='wpConfirmB' id='wpConfirmB' value=\"{$confirm}\" />
+                               <input type='submit' name='wpConfirmB' id='wpConfirmB' value=\"{$confirm}\" tabindex=\"3\" />
                        </td>
                </tr>
        </table>
@@ -1879,6 +2025,22 @@ class Article {
 </form>\n" );
 
                $wgOut->returnToMain( false );
+
+               $this->showLogExtract( $wgOut );
+       }
+
+
+       /**
+        * Show relevant lines from the deletion log
+        */
+       function showLogExtract( $out ) {
+               $out->addHtml( '<h2>' . htmlspecialchars( LogPage::logName( 'delete' ) ) . '</h2>' );
+               $logViewer = new LogViewer(
+                       new LogReader(
+                               new FauxRequest(
+                                       array( 'page' => $this->mTitle->getPrefixedText(),
+                                              'type' => 'delete' ) ) ) );
+               $logViewer->showList( $out );
        }
 
 
@@ -1919,7 +2081,7 @@ class Article {
 
                wfDebug( __METHOD__."\n" );
 
-               $dbw =& wfGetDB( DB_MASTER );
+               $dbw = wfGetDB( DB_MASTER );
                $ns = $this->mTitle->getNamespace();
                $t = $this->mTitle->getDBkey();
                $id = $this->mTitle->getArticleID();
@@ -1952,12 +2114,18 @@ class Article {
                                'ar_minor_edit' => 'rev_minor_edit',
                                'ar_rev_id'     => 'rev_id',
                                'ar_text_id'    => 'rev_text_id',
+                               'ar_text'       => '\'\'', // Be explicit to appease
+                               'ar_flags'      => '\'\'', // MySQL's "strict mode"...
+                               'ar_len'                => 'rev_len'
                        ), array(
                                'page_id' => $id,
                                'page_id = rev_page'
                        ), __METHOD__
                );
 
+               # Delete restrictions for it
+               $dbw->delete( 'page_restrictions', array ( 'pr_page' => $id ), __METHOD__ );
+
                # Now that it's safely backed up, delete it
                $dbw->delete( 'page', array( 'page_id' => $id ), __METHOD__);
 
@@ -2000,60 +2168,52 @@ class Article {
        }
 
        /**
-        * Revert a modification
+        * Roll back the most recent consecutive set of edits to a page
+        * from the same user; fails if there are no eligible edits to
+        * roll back to, e.g. user is the sole contributor
+        *
+        * @param string $fromP - Name of the user whose edits to rollback. 
+        * @param string $summary - Custom summary. Set to default summary if empty.
+        * @param string $token - Rollback token.
+        * @param bool $bot - If true, mark all reverted edits as bot.
+        * 
+        * @param array $resultDetails contains result-specific dict of additional values
+        *    ALREADY_ROLLED : 'current' (rev)
+        *    SUCCESS        : 'summary' (str), 'current' (rev), 'target' (rev)
+        * 
+        * @return self::SUCCESS on succes, self::* on failure
         */
-       function rollback() {
-               global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
-
+       public function doRollback( $fromP, $summary, $token, $bot, &$resultDetails ) {
+               global $wgUser, $wgUseRCPatrol;
+               $resultDetails = null;
+               
                if( $wgUser->isAllowed( 'rollback' ) ) {
                        if( $wgUser->isBlocked() ) {
-                               $wgOut->blockedPage();
-                               return;
+                               return self::BLOCKED;
                        }
                } else {
-                       $wgOut->permissionRequired( 'rollback' );
-                       return;
+                       return self::PERM_DENIED;
                }
-
+                       
                if ( wfReadOnly() ) {
-                       $wgOut->readOnlyPage( $this->getContent() );
-                       return;
+                       return self::READONLY;
                }
-               if( !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ),
-                       array( $this->mTitle->getPrefixedText(),
-                               $wgRequest->getVal( 'from' ) )  ) ) {
-                       $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
-                       $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
-                       return;
-               }
-               $dbw =& wfGetDB( DB_MASTER );
+               if( !$wgUser->matchEditToken( $token, array( $this->mTitle->getPrefixedText(), $fromP ) ) )
+                       return self::BAD_TOKEN;
 
-               # Enhanced rollback, marks edits rc_bot=1
-               $bot = $wgRequest->getBool( 'bot' );
-
-               # Replace all this user's current edits with the next one down
+               $dbw = wfGetDB( DB_MASTER );
 
                # Get the last editor
                $current = Revision::newFromTitle( $this->mTitle );
                if( is_null( $current ) ) {
                        # Something wrong... no page?
-                       $wgOut->addHTML( wfMsg( 'notanarticle' ) );
-                       return;
+                       return self::BAD_TITLE;
                }
 
-               $from = str_replace( '_', ' ', $wgRequest->getVal( 'from' ) );
+               $from = str_replace( '_', ' ', $fromP );
                if( $from != $current->getUserText() ) {
-                       $wgOut->setPageTitle( wfMsg('rollbackfailed') );
-                       $wgOut->addWikiText( wfMsg( 'alreadyrolled',
-                               htmlspecialchars( $this->mTitle->getPrefixedText()),
-                               htmlspecialchars( $from ),
-                               htmlspecialchars( $current->getUserText() ) ) );
-                       if( $current->getComment() != '') {
-                               $wgOut->addHTML(
-                                       wfMsg( 'editcomment',
-                                       htmlspecialchars( $current->getComment() ) ) );
-                       }
-                       return;
+                       $resultDetails = array( 'current' => $current );
+                       return self::ALREADY_ROLLED;
                }
 
                # Get the last edit not by this guy
@@ -2071,11 +2231,9 @@ class Article {
                        );
                if( $s === false ) {
                        # Something wrong
-                       $wgOut->setPageTitle(wfMsg('rollbackfailed'));
-                       $wgOut->addHTML( wfMsg( 'cantrollback' ) );
-                       return;
+                       return self::ONLY_AUTHOR;
                }
-
+       
                $set = array();
                if ( $bot ) {
                        # Mark all reverted edits as bot
@@ -2088,27 +2246,100 @@ class Article {
 
                if ( $set ) {
                        $dbw->update( 'recentchanges', $set,
-                               array( /* WHERE */
-                                       'rc_cur_id'    => $current->getPage(),
-                                       'rc_user_text' => $current->getUserText(),
-                                       "rc_timestamp > '{$s->rev_timestamp}'",
-                               ), __METHOD__
-                       );
+                                       array( /* WHERE */
+                                               'rc_cur_id' => $current->getPage(),
+                                               'rc_user_text' => $current->getUserText(),
+                                               "rc_timestamp > '{$s->rev_timestamp}'",
+                                       ), __METHOD__
+                               );
                }
 
                # Get the edit summary
                $target = Revision::newFromId( $s->rev_id );
-               $newComment = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
-               $newComment = $wgRequest->getText( 'summary', $newComment );
+               if( empty( $summary ) )
+                       $summary = wfMsgForContent( 'revertpage', $target->getUserText(), $from );
+
+               # Save
+               $flags = EDIT_UPDATE | EDIT_MINOR;
+               if( $bot )
+                       $flags |= EDIT_FORCE_BOT;
+               $this->doEdit( $target->getText(), $summary, $flags );
+
+               $resultDetails = array(
+                       'summary' => $summary,
+                       'current' => $current,
+                       'target' => $target,
+               );
+               return self::SUCCESS;
+       }
 
-               # Save it!
-               $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
-               $wgOut->setRobotpolicy( 'noindex,nofollow' );
-               $wgOut->addHTML( '<h2>' . htmlspecialchars( $newComment ) . "</h2>\n<hr />\n" );
+       /**
+        * User interface for rollback operations
+        */
+       function rollback() {
+               global $wgUser, $wgOut, $wgRequest, $wgUseRCPatrol;
 
-               $this->updateArticle( $target->getText(), $newComment, 1, $this->mTitle->userIsWatching(), $bot );
+               $details = null;
+               $result = $this->doRollback(
+                       $wgRequest->getVal( 'from' ),
+                       $wgRequest->getText( 'summary' ),
+                       $wgRequest->getVal( 'token' ),
+                       $wgRequest->getBool( 'bot' ),
+                       $details
+               );
+
+               switch( $result ) {
+                       case self::BLOCKED:
+                               $wgOut->blockedPage();
+                               break;
+                       case self::PERM_DENIED:
+                               $wgOut->permissionRequired( 'rollback' );
+                               break;
+                       case self::READONLY:
+                               $wgOut->readOnlyPage( $this->getContent() );
+                               break;
+                       case self::BAD_TOKEN:
+                               $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
+                               $wgOut->addWikiText( wfMsg( 'sessionfailure' ) );
+                               break;
+                       case self::BAD_TITLE:
+                               $wgOut->addHtml( wfMsg( 'notanarticle' ) );
+                               break;
+                       case self::ALREADY_ROLLED:
+                               $current = $details['current'];
+                               $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
+                               $wgOut->addWikiText(
+                                       wfMsg( 'alreadyrolled',
+                                               htmlspecialchars( $this->mTitle->getPrefixedText() ),
+                                               htmlspecialchars( $wgRequest->getVal( 'from' ) ),
+                                               htmlspecialchars( $current->getUserText() )
+                                       )
+                               );
+                               if( $current->getComment() != '' ) {
+                                       $wgOut->addHtml( wfMsg( 'editcomment',
+                                               $wgUser->getSkin()->formatComment( $current->getComment() ) ) );
+                               }
+                               break;
+                       case self::ONLY_AUTHOR:
+                               $wgOut->setPageTitle( wfMsg( 'rollbackfailed' ) );
+                               $wgOut->addHtml( wfMsg( 'cantrollback' ) );
+                               break;
+                       case self::SUCCESS:
+                               $current = $details['current'];
+                               $target = $details['target'];
+                               $wgOut->setPageTitle( wfMsg( 'actioncomplete' ) );
+                               $wgOut->setRobotPolicy( 'noindex,nofollow' );
+                               $old = $wgUser->getSkin()->userLink( $current->getUser(), $current->getUserText() )
+                                       . $wgUser->getSkin()->userToolLinks( $current->getUser(), $current->getUserText() );
+                               $new = $wgUser->getSkin()->userLink( $target->getUser(), $target->getUserText() )
+                                       . $wgUser->getSkin()->userToolLinks( $target->getUser(), $target->getUserText() );
+                               $wgOut->addHtml( wfMsgExt( 'rollback-success', array( 'parse', 'replaceafter' ), $old, $new ) );
+                               $wgOut->returnToMain( false, $this->mTitle );
+                               break;
+                       default:
+                               throw new MWException( __METHOD__ . ": Unknown return value `{$retval}`" );
+               }
 
-               $wgOut->returnToMain( false );
        }
 
 
@@ -2137,7 +2368,7 @@ class Article {
         * Do standard deferred updates after page edit.
         * Update links tables, site stats, search index and message cache.
         * Every 1000th edit, prune the recent changes table.
-        * 
+        *
         * @private
         * @param $text New text of the article
         * @param $summary Edit summary
@@ -2166,11 +2397,11 @@ class Article {
 
                if ( wfRunHooks( 'ArticleEditUpdatesDeleteFromRecentchanges', array( &$this ) ) ) {
                        wfSeedRandom();
-                       if ( 0 == mt_rand( 0, 999 ) ) {
+                       if ( 0 == mt_rand( 0, 99 ) ) {
                                # Periodically flush old entries from the recentchanges table.
                                global $wgRCMaxAge;
 
-                               $dbw =& wfGetDB( DB_MASTER );
+                               $dbw = wfGetDB( DB_MASTER );
                                $cutoff = $dbw->timestamp( time() - $wgRCMaxAge );
                                $recentchanges = $dbw->tableName( 'recentchanges' );
                                $sql = "DELETE FROM $recentchanges WHERE rc_timestamp < '{$cutoff}'";
@@ -2217,13 +2448,13 @@ class Article {
 
                wfProfileOut( __METHOD__ );
        }
-       
+
        /**
         * Perform article updates on a special page creation.
         *
         * @param Revision $rev
         *
-        * @fixme This is a shitty interface function. Kill it and replace the
+        * @todo This is a shitty interface function. Kill it and replace the
         * other shitty functions like editUpdates and such so it's not needed
         * anymore.
         */
@@ -2247,8 +2478,8 @@ class Article {
                global $wgLang, $wgOut, $wgUser;
 
                if ( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
-                               return; 
-               }       
+                               return;
+               }
 
                $revision = Revision::newFromId( $oldid );
 
@@ -2274,11 +2505,16 @@ class Article {
                $nextdiff = $current
                        ? wfMsg( 'diff' )
                        : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
-               
+
                $userlinks = $sk->userLink( $revision->getUser(), $revision->getUserText() )
                                                . $sk->userToolLinks( $revision->getUser(), $revision->getUserText() );
-               
-               $r = "\n\t\t\t\t<div id=\"mw-revision-info\">" . wfMsg( 'revision-info', $td, $userlinks ) . "</div>\n" .
+
+               $m = wfMsg( 'revision-info-current' );
+               $infomsg = $current && !wfEmptyMsg( 'revision-info-current', $m ) && $m != '-'
+                       ? 'revision-info-current'
+                       : 'revision-info';
+                       
+               $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsg( $infomsg, $td, $userlinks ) . "</div>\n" .
                     "\n\t\t\t\t<div id=\"mw-revision-nav\">" . wfMsg( 'revision-nav', $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
                $wgOut->setSubtitle( $r );
        }
@@ -2329,21 +2565,40 @@ class Article {
         * @return bool
         */
        function isFileCacheable() {
-               global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest;
-               extract( $wgRequest->getValues( 'action', 'oldid', 'diff', 'redirect', 'printable' ) );
-
-               return $wgUseFileCache
-                       and (!$wgShowIPinHeader)
-                       and ($this->getID() != 0)
-                       and ($wgUser->isAnon())
-                       and (!$wgUser->getNewtalk())
-                       and ($this->mTitle->getNamespace() != NS_SPECIAL )
-                       and (empty( $action ) || $action == 'view')
-                       and (!isset($oldid))
-                       and (!isset($diff))
-                       and (!isset($redirect))
-                       and (!isset($printable))
-                       and (!$this->mRedirectedFrom);
+               global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
+               $action    = $wgRequest->getVal( 'action'    );
+               $oldid     = $wgRequest->getVal( 'oldid'     );
+               $diff      = $wgRequest->getVal( 'diff'      );
+               $redirect  = $wgRequest->getVal( 'redirect'  );
+               $printable = $wgRequest->getVal( 'printable' );
+               $page      = $wgRequest->getVal( 'page' );
+
+               //check for non-standard user language; this covers uselang, 
+               //and extensions for auto-detecting user language.
+               $ulang     = $wgLang->getCode(); 
+               $clang     = $wgContLang->getCode();
+
+               $cacheable = $wgUseFileCache
+                       && (!$wgShowIPinHeader)
+                       && ($this->getID() != 0)
+                       && ($wgUser->isAnon())
+                       && (!$wgUser->getNewtalk())
+                       && ($this->mTitle->getNamespace() != NS_SPECIAL )
+                       && (empty( $action ) || $action == 'view')
+                       && (!isset($oldid))
+                       && (!isset($diff))
+                       && (!isset($redirect))
+                       && (!isset($printable))
+                       && !isset($page)
+                       && (!$this->mRedirectedFrom)
+                       && ($ulang === $clang);
+
+               if ( $cacheable ) {
+                       //extension may have reason to disable file caching on some pages.
+                       $cacheable = wfRunHooks( 'IsFileCacheable', array( $this ) );
+               }
+
+               return $cacheable;
        }
 
        /**
@@ -2390,7 +2645,7 @@ class Article {
        function quickEdit( $text, $comment = '', $minor = 0 ) {
                wfProfileIn( __METHOD__ );
 
-               $dbw =& wfGetDB( DB_MASTER );
+               $dbw = wfGetDB( DB_MASTER );
                $dbw->begin();
                $revision = new Revision( array(
                        'page'       => $this->getId(),
@@ -2415,7 +2670,7 @@ class Article {
                $id = intval( $id );
                global $wgHitcounterUpdateFreq, $wgDBtype;
 
-               $dbw =& wfGetDB( DB_MASTER );
+               $dbw = wfGetDB( DB_MASTER );
                $pageTable = $dbw->tableName( 'page' );
                $hitcounterTable = $dbw->tableName( 'hitcounter' );
                $acchitsTable = $dbw->tableName( 'acchits' );
@@ -2447,7 +2702,7 @@ class Article {
                        if ($wgDBtype == 'mysql')
                                $dbw->query("LOCK TABLES $hitcounterTable WRITE");
                        $tabletype = $wgDBtype == 'mysql' ? "ENGINE=HEAP " : '';
-                       $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS".
+                       $dbw->query("CREATE TEMPORARY TABLE $acchitsTable $tabletype AS ".
                                "SELECT hc_id,COUNT(*) AS hc_n FROM $hitcounterTable ".
                                'GROUP BY hc_id');
                        $dbw->query("DELETE FROM $hitcounterTable");
@@ -2499,7 +2754,7 @@ class Article {
 
                $title->touchLinks();
                $title->purgeSquid();
-               
+
                # File cache
                if ( $wgUseFileCache ) {
                        $cm = new HTMLFileCache( $title );
@@ -2561,7 +2816,7 @@ class Article {
                                $wgOut->addHTML(wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' ) );
                        }
                } else {
-                       $dbr =& wfGetDB( DB_SLAVE );
+                       $dbr = wfGetDB( DB_SLAVE );
                        $wl_clause = array(
                                'wl_title'     => $page->getDBkey(),
                                'wl_namespace' => $page->getNamespace() );
@@ -2603,7 +2858,7 @@ class Article {
                        return false;
                }
 
-               $dbr =& wfGetDB( DB_SLAVE );
+               $dbr = wfGetDB( DB_SLAVE );
 
                $rev_clause = array( 'rev_page' => $id );
 
@@ -2637,7 +2892,7 @@ class Article {
                        return array();
                }
 
-               $dbr =& wfGetDB( DB_SLAVE );
+               $dbr = wfGetDB( DB_SLAVE );
                $res = $dbr->select( array( 'templatelinks' ),
                        array( 'tl_namespace', 'tl_title' ),
                        array( 'tl_from' => $id ),
@@ -2652,7 +2907,7 @@ class Article {
                $dbr->freeResult( $res );
                return $result;
        }
-       
+
        /**
         * Return an auto-generated summary if the text provided is a redirect.
         *
@@ -2662,7 +2917,7 @@ class Article {
        public static function getRedirectAutosummary( $text ) {
                $rt = Title::newFromRedirect( $text );
                if( is_object( $rt ) )
-                       return wfMsgForContent( 'autoredircomment', $rt->getPrefixedText() );
+                       return wfMsgForContent( 'autoredircomment', $rt->getFullText() );
                else
                        return '';
        }
@@ -2700,8 +2955,6 @@ class Article {
                # This code is UGLY UGLY UGLY.
                # Somebody PLEASE come up with a more elegant way to do it.
 
-               $summary = '';
-
                #Redirect autosummaries
                $summary = self::getRedirectAutosummary( $newtext );
 
@@ -2719,8 +2972,10 @@ class Article {
                if ($flags & EDIT_NEW && strlen($newtext)) {
                        #If they're making a new article, give its text, truncated, in the summary.
                        global $wgContLang;
-                       $truncatedtext = $wgContLang->truncate( $newtext, max( 0, 200 - 
-                               strlen( wfMsgForContent( 'autosumm-new') ) ), '...' );
+                       $truncatedtext = $wgContLang->truncate(
+                               str_replace("\n", ' ', $newtext),
+                               max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new') ) ),
+                               '...' );
                        $summary = wfMsgForContent( 'autosumm-new', $truncatedtext );
                }
 
@@ -2729,6 +2984,82 @@ class Article {
 
                return $summary;
        }
-}
 
-?>
+       /**
+        * Add the primary page-view wikitext to the output buffer
+        * Saves the text into the parser cache if possible.
+        * Updates templatelinks if it is out of date.
+        *
+        * @param string  $text
+        * @param bool    $cache
+        */
+       public function outputWikiText( $text, $cache = true ) {
+               global $wgParser, $wgUser, $wgOut;
+
+               $popts = $wgOut->parserOptions();
+               $popts->setTidy(true);
+               $parserOutput = $wgParser->parse( $text, $this->mTitle,
+                       $popts, true, true, $this->getRevIdFetched() );
+               $popts->setTidy(false);
+               if ( $cache && $this && $parserOutput->getCacheTime() != -1 ) {
+                       $parserCache =& ParserCache::singleton();
+                       $parserCache->save( $parserOutput, $this, $wgUser );
+               }
+
+               if ( !wfReadOnly() && $this->mTitle->areRestrictionsCascading() ) {
+                       // templatelinks table may have become out of sync,
+                       // especially if using variable-based transclusions.
+                       // For paranoia, check if things have changed and if
+                       // so apply updates to the database. This will ensure
+                       // that cascaded protections apply as soon as the changes
+                       // are visible.
+
+                       # Get templates from templatelinks
+                       $id = $this->mTitle->getArticleID();
+
+                       $tlTemplates = array();
+
+                       $dbr = wfGetDB( DB_SLAVE );
+                       $res = $dbr->select( array( 'templatelinks' ),
+                               array( 'tl_namespace', 'tl_title' ),
+                               array( 'tl_from' => $id ),
+                               'Article:getUsedTemplates' );
+
+                       global $wgContLang;
+
+                       if ( false !== $res ) {
+                               if ( $dbr->numRows( $res ) ) {
+                                       while ( $row = $dbr->fetchObject( $res ) ) {
+                                               $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace ) . ':' . $row->tl_title ;
+                                       }
+                               }
+                       }
+
+                       # Get templates from parser output.
+                       $poTemplates_allns = $parserOutput->getTemplates();
+
+                       $poTemplates = array ();
+                       foreach ( $poTemplates_allns as $ns_templates ) {
+                               $poTemplates = array_merge( $poTemplates, $ns_templates );
+                       }
+
+                       # Get the diff
+                       $templates_diff = array_diff( $poTemplates, $tlTemplates );
+
+                       if ( count( $templates_diff ) > 0 ) {
+                               # Whee, link updates time.
+                               $u = new LinksUpdate( $this->mTitle, $parserOutput );
+
+                               $dbw = wfGetDb( DB_MASTER );
+                               $dbw->begin();
+
+                               $u->doUpdate();
+
+                               $dbw->commit();
+                       }
+               }
+
+               $wgOut->addParserOutput( $parserOutput );
+       }
+
+}
\ No newline at end of file