extract djvu text (bug 18046); escape possible script with htmlspecialchars instead...
[lhc/web/wiklou.git] / includes / Article.php
index bb1d7a0..1f30e87 100644 (file)
@@ -84,12 +84,12 @@ class Article {
                        return $this->mRedirectTarget;
                # Query the redirect table
                $dbr = wfGetDB( DB_SLAVE );
-               $res = $dbr->select( 'redirect',
+               $row = $dbr->selectRow( 'redirect',
                        array('rd_namespace', 'rd_title'),
-                       array('rd_from' => $this->getID()),
+                       array('rd_from' => $this->getID() ),
                        __METHOD__
                );
-               if( $row = $dbr->fetchObject($res) ) {
+               if( $row ) {
                        return $this->mRedirectTarget = Title::makeTitle($row->rd_namespace, $row->rd_title);
                }
                # This page doesn't have an entry in the redirect table
@@ -135,7 +135,7 @@ class Article {
         * @return mixed false, Title of in-wiki target, or string with URL
         */
        public function followRedirectText( $text ) {
-               $rt = Title::newFromRedirect( $text );
+               $rt = Title::newFromRedirectRecurse( $text ); // recurse through to only get the final target
                # process if title object is valid and not special:userlogout
                if( $rt ) {
                        if( $rt->getInterwiki() != '' ) {
@@ -218,7 +218,7 @@ class Article {
                                if( wfEmptyMsg( $message, $text ) )
                                        $text = '';
                        } else {
-                               $text = wfMsg( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon' );
+                               $text = wfMsgExt( $wgUser->isLoggedIn() ? 'noarticletext' : 'noarticletextanon', 'parsemag' );
                        }
                        wfProfileOut( __METHOD__ );
                        return $text;
@@ -228,6 +228,21 @@ class Article {
                        return $this->mContent;
                }
        }
+       
+       /**
+        * Get the text of the current revision. No side-effects...
+        *
+        * @return Return the text of the current revision
+       */
+       public function getRawText() {
+               // Check process cache for current revision
+               if( $this->mContentLoaded && $this->mOldId == 0 ) {
+                       return $this->mContent;
+               }
+               $rev = Revision::newFromTitle( $this->mTitle );
+               $text = $rev ? $rev->getRawText() : false;
+               return $text;
+       }
 
        /**
         * This function returns the text of a section, specified by a number ($section).
@@ -245,6 +260,28 @@ class Article {
                global $wgParser;
                return $wgParser->getSection( $text, $section );
        }
+       
+       /**
+        * Get the text that needs to be saved in order to undo all revisions
+        * between $undo and $undoafter. Revisions must belong to the same page,
+        * must exist and must not be deleted
+        * @param $undo Revision 
+        * @param $undoafter Revision Must be an earlier revision than $undo
+        * @return mixed string on success, false on failure
+        */
+       public function getUndoText( Revision $undo, Revision $undoafter = null ) {
+               $undo_text = $undo->getText();
+               $undoafter_text = $undoafter->getText();
+               $cur_text = $this->getContent();
+               if ( $cur_text == $undo_text ) {
+                       # No use doing a merge if it's just a straight revert.
+                       return $undoafter_text;
+               }
+               $undone_text = '';
+               if ( !wfMerge( $undo_text, $undoafter_text, $cur_text, $undone_text ) )
+                       return false;
+               return $undone_text;
+       }
 
        /**
         * @return int The oldid of the article that is to be shown, 0 for the
@@ -369,9 +406,8 @@ class Article {
                        $lc->addGoodLinkObj( $data->page_id, $this->mTitle, $data->page_len, $data->page_is_redirect );
 
                        $this->mTitle->mArticleID = $data->page_id;
-                       $this->mTitle->mTouched = wfTimestamp( TS_MW, $data->page_touched );
 
-                       # Old-fashioned restrictions.
+                       # Old-fashioned restrictions
                        $this->mTitle->loadRestrictions( $data->page_restrictions );
 
                        $this->mCounter     = $data->page_counter;
@@ -509,6 +545,18 @@ class Article {
        public function exists() {
                return $this->getId() > 0;
        }
+       
+       /**
+        * Check if this page is something we're going to be showing
+        * some sort of sensible content for. If we return false, page
+        * views (plain action=view) will return an HTTP 404 response,
+        * so spiders and robots can know they're following a bad link.
+        *
+        * @return bool
+        */
+       public function hasViewableContent() {
+               return $this->exists() || $this->mTitle->isAlwaysKnown();
+       }
 
        /**
         * @return int The view count for the page
@@ -558,7 +606,7 @@ class Article {
                        }
                        // Apparently loadPageData was never called
                        $this->loadContent();
-                       $titleObj = Title::newFromRedirect( $this->fetchContent() );
+                       $titleObj = Title::newFromRedirectRecurse( $this->fetchContent() );
                } else {
                        $titleObj = Title::newFromRedirect( $text );
                }
@@ -649,10 +697,13 @@ class Article {
                $user = $this->getUser();
                $pageId = $this->getId();
 
+               $hideBit = Revision::DELETED_USER; // username hidden?
+
                $sql = "SELECT {$userTable}.*, MAX(rev_timestamp) as timestamp
                        FROM $revTable LEFT JOIN $userTable ON rev_user = user_id
                        WHERE rev_page = $pageId
                        AND rev_user != $user
+                       AND rev_deleted & $hideBit = 0
                        GROUP BY rev_user, rev_user_text, user_real_name
                        ORDER BY timestamp DESC";
 
@@ -676,20 +727,28 @@ class Article {
                global $wgUseTrackbacks, $wgNamespaceRobotPolicies, $wgArticleRobotPolicies;
                global $wgDefaultRobotPolicy;
 
+               # Let the parser know if this is the printable version
+               if( $wgOut->isPrintable() ) {
+                       $wgOut->parserOptions()->setIsPrintable( true );
+               }
+               
                wfProfileIn( __METHOD__ );
 
-               $parserCache = ParserCache::singleton();
-               $ns = $this->mTitle->getNamespace(); # shortcut
-
                # Get variables from query string
                $oldid = $this->getOldID();
 
-               # Try file cache
+               # Try client and file cache
                if( $oldid === 0 && $this->checkTouched() ) {
-                       $wgOut->setETag($parserCache->getETag($this, $wgUser));
-                       if( $wgOut->checkLastModified( $this->getTouched() ) ){
+                       global $wgUseETag;
+                       if( $wgUseETag ) {
+                               $parserCache = ParserCache::singleton();
+                               $wgOut->setETag( $parserCache->getETag($this, $wgOut->parserOptions()) );
+                       }
+                       # Is is client cached?
+                       if( $wgOut->checkLastModified( $this->getTouched() ) ) {
                                wfProfileOut( __METHOD__ );
                                return;
+                       # Try file cache
                        } else if( $this->tryFileCache() ) {
                                # tell wgOut that output is taken care of
                                $wgOut->disable();
@@ -699,6 +758,7 @@ class Article {
                        }
                }
 
+               $ns = $this->mTitle->getNamespace(); # shortcut
                $sk = $wgUser->getSkin();
 
                # getOldID may want us to redirect somewhere else
@@ -713,6 +773,7 @@ class Article {
                $rdfrom = $wgRequest->getVal( 'rdfrom' );
                $diffOnly = $wgRequest->getBool( 'diffonly', $wgUser->getOption( 'diffonly' ) );
                $purge = $wgRequest->getVal( 'action' ) == 'purge';
+               $return404 = false;
 
                $wgOut->setArticleFlag( true );
 
@@ -729,15 +790,17 @@ class Article {
                }
                $wgOut->setRobotPolicy( $policy );
 
+               # Allow admins to see deleted content if explicitly requested
+               $delId = $diff ? $diff : $oldid;
+               $unhide = $wgRequest->getInt('unhide') == 1
+                       && $wgUser->matchEditToken( $wgRequest->getVal('token'), $delId );
                # If we got diff and oldid in the query, we want to see a
                # diff page instead of the article.
-
                if( !is_null( $diff ) ) {
                        $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
 
-                       $diff = $wgRequest->getVal( 'diff' );
                        $htmldiff = $wgRequest->getVal( 'htmldiff' , false);
-                       $de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid, $purge, $htmldiff);
+                       $de = new DifferenceEngine( $this->mTitle, $oldid, $diff, $rcid, $purge, $htmldiff, $unhide );
                        // DifferenceEngine directly fetched the revision:
                        $this->mRevIdFetched = $de->mNewid;
                        $de->showDiffPage( $diffOnly );
@@ -751,6 +814,16 @@ class Article {
                        wfProfileOut( __METHOD__ );
                        return;
                }
+               
+               if( $ns == NS_USER || $ns == NS_USER_TALK ) {
+                       # User/User_talk subpages are not modified. (bug 11443)
+                       if( !$this->mTitle->isSubpage() ) {
+                               $block = new Block();
+                               if( $block->load( $this->mTitle->getBaseText() ) ) {
+                                       $wgOut->setRobotpolicy( 'noindex,nofollow' );
+                               }
+                       }
+               }
 
                # Should the parser cache be used?
                $pcache = $this->useParserCache( $oldid );
@@ -765,7 +838,7 @@ class Article {
                        // We'll need a backlink to the source page for navigation.
                        if( wfRunHooks( 'ArticleViewRedirect', array( &$this ) ) ) {
                                $redir = $sk->makeKnownLinkObj( $this->mRedirectedFrom, '', 'redirect=no' );
-                               $s = wfMsg( 'redirectedfrom', $redir );
+                               $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
                                $wgOut->setSubtitle( $s );
 
                                // Set the fragment if one was specified in the redirect
@@ -773,6 +846,11 @@ class Article {
                                        $fragment = Xml::escapeJsString( $this->mTitle->getFragmentForURL() );
                                        $wgOut->addInlineScript( "redirectToFragment(\"$fragment\");" );
                                }
+
+                               // Add a <link rel="canonical"> tag
+                               $wgOut->addLink( array( 'rel' => 'canonical',
+                                       'href' => $this->mTitle->getLocalURL() )
+                               );
                                $wasRedirected = true;
                        }
                } elseif( !empty( $rdfrom ) ) {
@@ -781,15 +859,23 @@ class Article {
                        global $wgRedirectSources;
                        if( $wgRedirectSources && preg_match( $wgRedirectSources, $rdfrom ) ) {
                                $redir = $sk->makeExternalLink( $rdfrom, $rdfrom );
-                               $s = wfMsg( 'redirectedfrom', $redir );
+                               $s = wfMsgExt( 'redirectedfrom', array( 'parseinline', 'replaceafter' ), $redir );
                                $wgOut->setSubtitle( $s );
                                $wasRedirected = true;
                        }
                }
 
+               # Allow a specific header on talk pages, like [[MediaWiki:Talkpagetext]]
+               if( $this->mTitle->isTalkPage() ) {
+                       $msg = wfMsgNoTrans( 'talkpageheader' );
+                       if ( $msg !== '-' && !wfEmptyMsg( 'talkpageheader', $msg ) ) {
+                               $wgOut->wrapWikiMsg( "<div class=\"mw-talkpageheader\">\n$1</div>", array( 'talkpageheader' ) );
+                       }
+               }
+
                $outputDone = false;
                wfRunHooks( 'ArticleViewHeader', array( &$this, &$outputDone, &$pcache ) );
-               if( $pcache && $wgOut->tryParserCache( $this, $wgUser ) ) {
+               if( $pcache && $wgOut->tryParserCache( $this ) ) {
                        // Ensure that UI elements requiring revision ID have
                        // the correct version information.
                        $wgOut->setRevisionId( $this->mLatest );
@@ -797,34 +883,53 @@ class Article {
                }
                # Fetch content and check for errors
                if( !$outputDone ) {
-                       # If the article does not exist and was deleted, show the log
+                       # If the article does not exist and was deleted/moved, show the log
                        if( $this->getID() == 0 ) {
-                               $this->showDeletionLog();
+                               $this->showLogs();
                        }
                        $text = $this->getContent();
-                       if( $text === false ) {
+                       // For now, check also for ID until getContent actually returns
+                       // false for pages that do not exists
+                       if( $text === false || $this->getID() === 0 ) {
                                # Failed to load, replace text with error message
                                $t = $this->mTitle->getPrefixedText();
                                if( $oldid ) {
-                                       $d = wfMsgExt( 'missingarticle-rev', array( 'escape' ), $oldid );
-                                       $text = wfMsg( 'missing-article', $t, $d );
-                               } else {
-                                       $text = wfMsg( 'noarticletext' );
+                                       $d = wfMsgExt( 'missingarticle-rev', 'escape', $oldid );
+                                       $text = wfMsgExt( 'missing-article', 'parsemag', $t, $d );
+                               // Always use page content for pages in the MediaWiki namespace
+                               // since it contains the default message
+                               } elseif ( $this->mTitle->getNamespace() != NS_MEDIAWIKI ) {
+                                       $text = wfMsgExt( 'noarticletext', 'parsemag' );
                                }
                        }
+                       
                        # Non-existent pages
                        if( $this->getID() === 0 ) {
                                $wgOut->setRobotPolicy( 'noindex,nofollow' );
                                $text = "<div class='noarticletext'>\n$text\n</div>";
-                       } 
+                               if( !$this->hasViewableContent() ) {
+                                       // If there's no backing content, send a 404 Not Found
+                                       // for better machine handling of broken links.
+                                       $return404 = true;
+                               }
+                       }
+
+                       if( $return404 ) {
+                               $wgRequest->response()->header( "HTTP/1.x 404 Not Found" );
+                       }
 
                        # Another whitelist check in case oldid is altering the title
                        if( !$this->mTitle->userCanRead() ) {
                                $wgOut->loginToUse();
                                $wgOut->output();
+                               $wgOut->disable();
                                wfProfileOut( __METHOD__ );
-                               exit;
+                               return;
                        }
+                       
+                       # For ?curid=x urls, disallow indexing
+                       if( $wgRequest->getInt('curid') )
+                               $wgOut->setRobotPolicy( 'noindex,follow' );
 
                        # We're looking at an old revision
                        if( !empty( $oldid ) ) {
@@ -832,25 +937,49 @@ class Article {
                                if( is_null( $this->mRevision ) ) {
                                        // FIXME: This would be a nice place to load the 'no such page' text.
                                } else {
-                                       $this->setOldSubtitle( isset($this->mOldId) ? $this->mOldId : $oldid );
+                                       $this->setOldSubtitle( $oldid );
+                                       # Allow admins to see deleted content if explicitly requested
                                        if( $this->mRevision->isDeleted( Revision::DELETED_TEXT ) ) {
-                                               if( !$this->mRevision->userCan( Revision::DELETED_TEXT ) ) {
-                                                       $wgOut->addWikiMsg( 'rev-deleted-text-permission' );
+                                               // If the user is not allowed to see it...
+                                               if( !$this->mRevision->userCan(Revision::DELETED_TEXT) ) {
+                                                       $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
+                                                               'rev-deleted-text-permission' );
                                                        $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
                                                        wfProfileOut( __METHOD__ );
                                                        return;
+                                               // If the user needs to confirm that they want to see it...
+                                               } else if( !$unhide ) {
+                                                       # Give explanation and add a link to view the revision...
+                                                       $link = $this->mTitle->getFullUrl( "oldid={$oldid}".
+                                                               '&unhide=1&token='.urlencode( $wgUser->editToken($oldid) ) );
+                                                       $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
+                                                               array('rev-deleted-text-unhide',$link) );
+                                                       $wgOut->setPageTitle( $this->mTitle->getPrefixedText() );
+                                                       wfProfileOut( __METHOD__ );
+                                                       return;
+                                               // We are allowed to see...
                                                } else {
-                                                       $wgOut->addWikiMsg( 'rev-deleted-text-view' );
-                                                       // and we are allowed to see...
+                                                       $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1</div>\n",
+                                                               'rev-deleted-text-view' );
                                                }
                                        }
+                                       // Is this the current revision and otherwise cacheable? Try the parser cache...
+                                       if( $oldid === $this->getLatest() && $this->useParserCache( false )
+                                               && $wgOut->tryParserCache( $this ) )
+                                       {
+                                               $outputDone = true;
+                                       }
                                }
                        }
 
+                       // Ensure that UI elements requiring revision ID have
+                       // the correct version information.
                        $wgOut->setRevisionId( $this->getRevIdFetched() );
 
-                        // Pages containing custom CSS or JavaScript get special treatment
-                       if( $this->mTitle->isCssOrJsPage() || $this->mTitle->isCssJsSubpage() ) {
+                       if( $outputDone ) {
+                               // do nothing...
+                       // Pages containing custom CSS or JavaScript get special treatment
+                       } else 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 ) ) ) {
@@ -861,7 +990,7 @@ class Article {
                                        $wgOut->addHTML( htmlspecialchars( $this->mContent ) );
                                        $wgOut->addHTML( "\n</pre>\n" );
                                }
-                       } else if( $rt = Title::newFromRedirect( $text ) ) {
+                       } else if( $rt = Title::newFromRedirectArray( $text ) ) { # get an array of redirect targets
                                # Don't append the subtitle if this was an old revision
                                $wgOut->addHTML( $this->viewRedirect( $rt, !$wasRedirected && $this->isCurrent() ) );
                                $parseout = $wgParser->parse($text, $this->mTitle, ParserOptions::newFromUser($wgUser));
@@ -913,7 +1042,7 @@ class Article {
 
                # If we have been passed an &rcid= parameter, we want to give the user a
                # chance to mark this new article as patrolled.
-               if( !is_null( $rcid ) && $rcid != 0 && $wgUser->isAllowed( 'patrol' ) && $this->mTitle->exists() ) {
+               if( !empty($rcid) && $this->mTitle->exists() && $this->mTitle->quickUserCan('patrol') ) {
                        $wgOut->addHTML(
                                "<div class='patrollink'>" .
                                        wfMsgHtml( 'markaspatrolledlink',
@@ -933,14 +1062,14 @@ class Article {
                wfProfileOut( __METHOD__ );
        }
        
-       protected function showDeletionLog() {
+       protected function showLogs() {
                global $wgUser, $wgOut;
                $loglist = new LogEventsList( $wgUser->getSkin(), $wgOut );
-               $pager = new LogPager( $loglist, 'delete', false, $this->mTitle->getPrefixedText() );
+               $pager = new LogPager( $loglist, array('move', 'delete'), false, $this->mTitle->getPrefixedText() );
                if( $pager->getNumRows() > 0 ) {
                        $pager->mLimit = 10;
                        $wgOut->addHTML( '<div class="mw-warning-with-logexcerpt">' );
-                       $wgOut->addWikiMsg( 'deleted-notice' );
+                       $wgOut->addWikiMsg( 'moveddeleted-notice' );
                        $wgOut->addHTML(
                                $loglist->beginLogEventsList() .
                                $pager->getBody() .
@@ -949,9 +1078,9 @@ class Article {
                        if( $pager->getNumRows() > 10 ) {
                                $wgOut->addHTML( $wgUser->getSkin()->link(
                                        SpecialPage::getTitleFor( 'Log' ),
-                                       wfMsgHtml( 'deletelog-fulllog' ),
+                                       wfMsgHtml( 'log-fulllog' ),
                                        array(),
-                                       array( 'type' => 'delete', 'page' => $this->mTitle->getPrefixedText() ) 
+                                       array( 'page' => $this->mTitle->getPrefixedText() ) 
                                ) );
                        }
                        $wgOut->addHTML( '</div>' );
@@ -974,24 +1103,41 @@ class Article {
 
        /**
         * View redirect
-        * @param $target Title object of destination to redirect
+        * @param $target Title object or Array of destination(s) to redirect
         * @param $appendSubtitle Boolean [optional]
         * @param $forceKnown Boolean: should the image be shown as a bluelink regardless of existence?
         */
        public function viewRedirect( $target, $appendSubtitle = true, $forceKnown = false ) {
                global $wgParser, $wgOut, $wgContLang, $wgStylePath, $wgUser;
                # Display redirect
+               if( !is_array( $target ) ) {
+                       $target = array( $target );
+               }
                $imageDir = $wgContLang->isRTL() ? 'rtl' : 'ltr';
-               $imageUrl = $wgStylePath.'/common/images/redirect' . $imageDir . '.png';
-
+               $imageUrl = $wgStylePath . '/common/images/redirect' . $imageDir . '.png';
+               $imageUrl2 = $wgStylePath . '/common/images/nextredirect' . $imageDir . '.png';
+               $alt2 = $wgContLang->isRTL() ? '&larr;' : '&rarr;'; // should -> and <- be used instead of entities?
+               
                if( $appendSubtitle ) {
                        $wgOut->appendSubtitle( wfMsgHtml( 'redirectpagesub' ) );
                }
                $sk = $wgUser->getSkin();
+               // the loop prepends the arrow image before the link, so the first case needs to be outside
+               $title = array_shift( $target );
                if( $forceKnown ) {
-                       $link = $sk->makeKnownLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
+                       $link = $sk->makeKnownLinkObj( $title, htmlspecialchars( $title->getFullText() ) );
                } else {
-                       $link = $sk->makeLinkObj( $target, htmlspecialchars( $target->getFullText() ) );
+                       $link = $sk->makeLinkObj( $title, htmlspecialchars( $title->getFullText() ) );
+               }
+               // automatically append redirect=no to each link, since most of them are redirect pages themselves
+               foreach( $target as $rt ) {
+                       if( $forceKnown ) {
+                               $link .= '<img src="'.$imageUrl2.'" alt="'.$alt2.' " />'
+                                       . $sk->makeKnownLinkObj( $rt, htmlspecialchars( $rt->getFullText() ) );
+                       } else {
+                               $link .= '<img src="'.$imageUrl2.'" alt="'.$alt2.' " />'
+                                       . $sk->makeLinkObj( $rt, htmlspecialchars( $rt->getFullText() ) );
+                       }
                }
                return '<img src="'.$imageUrl.'" alt="#REDIRECT " />' .
                        '<span class="redirectText">'.$link.'</span>';
@@ -1023,12 +1169,12 @@ class Article {
                                        $o->tb_name,
                                        $rmvtxt);
                }
-               $wgOut->addWikiMsg( 'trackbackbox', $tbtext );
+               $wgOut->wrapWikiMsg( "<div id='mw_trackbacks'>$1</div>\n", array( 'trackbackbox', $tbtext ) );
                $this->mTitle->invalidateCache();
        }
 
        public function deletetrackback() {
-               global $wgUser, $wgRequest, $wgOut, $wgTitle;
+               global $wgUser, $wgRequest, $wgOut;
                if( !$wgUser->matchEditToken($wgRequest->getVal('token')) ) {
                        $wgOut->addWikiMsg( 'sessionfailure' );
                        return;
@@ -1099,7 +1245,7 @@ class Article {
                        if( $this->getID() == 0 ) {
                                $text = false;
                        } else {
-                               $text = $this->getContent();
+                               $text = $this->getRawText();
                        }
                        $wgMessageCache->replace( $this->mTitle->getDBkey(), $text );
                }
@@ -1264,11 +1410,12 @@ class Article {
        }
 
        /**
+        * @param $section empty/null/false or a section number (0, 1, 2, T1, T2...)
         * @return string Complete article text, or null if error
         */
        public function replaceSection( $section, $text, $summary = '', $edittime = NULL ) {
                wfProfileIn( __METHOD__ );
-               if( $section === '' ) {
+               if( strval( $section ) == '' ) {
                        // Whole-page edit; let the whole text through
                } else {
                        if( is_null($edittime) ) {
@@ -1460,7 +1607,7 @@ class Article {
                $isminor = ( $flags & EDIT_MINOR ) && $user->isAllowed('minoredit');
                $bot = $flags & EDIT_FORCE_BOT;
 
-               $oldtext = $this->getContent();
+               $oldtext = $this->getRawText(); // current revision
                $oldsize = strlen( $oldtext );
 
                # Provide autosummaries if one is not provided and autosummaries are enabled.
@@ -1533,11 +1680,10 @@ class Article {
                                        $dbw->rollback();
                                } else {
                                        global $wgUseRCPatrol;
-                                       wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, $baseRevId, $user) );
                                        # Update recentchanges
                                        if( !( $flags & EDIT_SUPPRESS_RC ) ) {
                                                # Mark as patrolled if the user can do so
-                                               $patrolled = $wgUseRCPatrol && $user->isAllowed('autopatrol');
+                                               $patrolled = $wgUseRCPatrol && $this->mTitle->userCan('autopatrol');
                                                # Add RC row to the DB
                                                $rc = RecentChange::notifyEdit( $now, $this->mTitle, $isminor, $user, $summary,
                                                        $this->mLatest, $this->getTimestamp(), $bot, '', $oldsize, $newsize,
@@ -1548,6 +1694,8 @@ class Article {
                                                        PatrolLog::record( $rc, true );
                                                }
                                        }
+                                       # Notify extensions of a new edit
+                                       wfRunHooks( 'NewRevisionFromEditComplete', array(&$this, $revision, $baseRevId, $user) );
                                        $user->incEditCount();
                                        $dbw->commit();
                                }
@@ -1571,8 +1719,8 @@ class Article {
                        }
 
                        # Invalidate cache of this article and all pages using this article
-                       # as a template. Partly deferred. Leave templatelinks for editUpdates().
-                       Article::onArticleEdit( $this->mTitle, 'skiptransclusions' );
+                       # as a template. Partly deferred.
+                       Article::onArticleEdit( $this->mTitle );
                        # Update links tables, site stats, etc.
                        $this->editUpdates( $text, $summary, $isminor, $now, $revisionId, $changed );
                } else {
@@ -1614,12 +1762,11 @@ class Article {
                        # Update the page record with revision data
                        $this->updateRevisionOn( $dbw, $revision, 0 );
 
-                       wfRunHooks( 'NewRevisionFromEditComplete', array($this, $revision, false, $user) );
                        # Update recentchanges
                        if( !( $flags & EDIT_SUPPRESS_RC ) ) {
                                global $wgUseRCPatrol, $wgUseNPPatrol;
                                # Mark as patrolled if the user can do so
-                               $patrolled = ($wgUseRCPatrol || $wgUseNPPatrol) && $user->isAllowed('autopatrol');
+                               $patrolled = ($wgUseRCPatrol || $wgUseNPPatrol) && $this->mTitle->userCan('autopatrol');
                                # Add RC row to the DB
                                $rc = RecentChange::notifyNew( $now, $this->mTitle, $isminor, $user, $summary, $bot,
                                        '', strlen($text), $revisionId, $patrolled );
@@ -1628,6 +1775,8 @@ class Article {
                                        PatrolLog::record( $rc, true );
                                }
                        }
+                       # Notify extensions of a new page edit
+                       wfRunHooks( 'NewRevisionFromEditComplete', array(&$this, $revision, false, $user) );
                        $user->incEditCount();
                        $dbw->commit();
 
@@ -1650,7 +1799,7 @@ class Article {
                $status->value['revision'] = $revision;
 
                wfRunHooks( 'ArticleSaveComplete', array( &$this, &$user, $text, $summary,
-                       $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status ) );
+                       $flags & EDIT_MINOR, null, null, &$flags, $revision, &$status, $baseRevId ) );
 
                wfProfileOut( __METHOD__ );
                return $status;
@@ -1701,7 +1850,7 @@ class Article {
 
                #It would be nice to see where the user had actually come from, but for now just guess
                $returnto = $rc->getAttribute( 'rc_type' ) == RC_NEW ? 'Newpages' : 'Recentchanges';
-               $return = Title::makeTitle( NS_SPECIAL, $returnto );
+               $return = SpecialPage::getTitleFor( $returnto );
 
                $dbw = wfGetDB( DB_MASTER );
                $errors = $rc->doMarkPatrolled();
@@ -1829,15 +1978,26 @@ class Article {
         *
         * @param $limit Array: set of restriction keys
         * @param $reason String
-        * @param $cascade Integer
+        * @param &$cascade Integer. Set to false if cascading protection isn't allowed.
         * @param $expiry Array: per restriction type expiration
         * @return bool true on success
         */
-       public function updateRestrictions( $limit = array(), $reason = '', $cascade = 0, $expiry = array() ) {
+       public function updateRestrictions( $limit = array(), $reason = '', &$cascade = 0, $expiry = array() ) {
                global $wgUser, $wgRestrictionTypes, $wgContLang;
 
                $id = $this->mTitle->getArticleID();
-               if( array() != $this->mTitle->getUserPermissionsErrors( 'protect', $wgUser ) || wfReadOnly() || $id == 0 ) {
+               if ( $id <= 0 ) {
+                       wfDebug( "updateRestrictions failed: $id <= 0\n" );
+                       return false;
+               }
+               
+               if ( wfReadOnly() ) {
+                       wfDebug( "updateRestrictions failed: read-only\n" );
+                       return false;
+               }
+               
+               if ( !$this->mTitle->userCan( 'protect' ) ) {
+                       wfDebug( "updateRestrictions failed: insufficient permissions\n" );
                        return false;
                }
 
@@ -1854,13 +2014,24 @@ class Article {
                $updated = Article::flattenRestrictions( $limit );
                $changed = false;
                foreach( $wgRestrictionTypes as $action ) {
-                       $current[$action] = implode( '', $this->mTitle->getRestrictions( $action ) );
-                       $changed = ($changed || ($this->mTitle->mRestrictionsExpiry[$action] != $expiry[$action]) );
+                       if( isset( $expiry[$action] ) ) {
+                               # Get current restrictions on $action
+                               $aLimits = $this->mTitle->getRestrictions( $action );
+                               $current[$action] = implode( '', $aLimits );
+                               # Are any actual restrictions being dealt with here?
+                               $aRChanged = count($aLimits) || !empty($limit[$action]);
+                               # If something changed, we need to log it. Checking $aRChanged
+                               # assures that "unprotecting" a page that is not protected does
+                               # not log just because the expiry was "changed".
+                               if( $aRChanged && $this->mTitle->mRestrictionsExpiry[$action] != $expiry[$action] ) {
+                                       $changed = true;
+                               }
+                       }
                }
 
                $current = Article::flattenRestrictions( $current );
 
-               $changed = ($changed || ( $current != $updated ) );
+               $changed = ($changed || $current != $updated );
                $changed = $changed || ($updated && $this->mTitle->areRestrictionsCascading() != $cascade);
                $protect = ( $updated != '' );
 
@@ -1881,13 +2052,10 @@ class Article {
 
                                # Only restrictions with the 'protect' right can cascade...
                                # Otherwise, people who cannot normally protect can "protect" pages via transclusion
-                               foreach( $limit as $action => $restriction ) {
-                                       # FIXME: can $restriction be an array or what? (same as fixme above)
-                                       if( $restriction != 'protect' && $restriction != 'sysop' ) {
-                                               $cascade = false;
-                                               break;
-                                       }
-                               }
+                               $editrestriction = isset( $limit['edit'] ) ? array( $limit['edit'] ) : $this->mTitle->getRestrictions( 'edit' );
+                               # The schema allows multiple restrictions
+                               if(!in_array('protect', $editrestriction) && !in_array('sysop', $editrestriction))
+                                       $cascade = false;
                                $cascade_description = '';       
                                if( $cascade ) {
                                        $cascade_description = ' ['.wfMsgForContent('protect-summary-cascade').']';      
@@ -1900,12 +2068,17 @@ class Article {
                                $encodedExpiry = array();
                                $protect_description = '';
                                foreach( $limit as $action => $restrictions  ) {
+                                       if ( !isset($expiry[$action]) )
+                                               $expiry[$action] = 'infinite';
+                                       
                                        $encodedExpiry[$action] = Block::encodeExpiry($expiry[$action], $dbw );
                                        if( $restrictions != '' ) {
                                                $protect_description .= "[$action=$restrictions] (";
                                                if( $encodedExpiry[$action] != 'infinity' ) {
                                                        $protect_description .= wfMsgForContent( 'protect-expiring', 
-                                                               $wgContLang->timeanddate( $expiry[$action], false, false ) );    
+                                                               $wgContLang->timeanddate( $expiry[$action], false, false ) ,
+                                                               $wgContLang->date( $expiry[$action], false, false ) ,
+                                                               $wgContLang->time( $expiry[$action], false, false ) );   
                                                } else {
                                                        $protect_description .= wfMsgForContent( 'protect-expiry-indefinite' );
                                                }
@@ -2014,18 +2187,16 @@ class Article {
 
                // Find out if there was only one contributor
                // Only scan the last 20 revisions
-               $limit = 20;
                $res = $dbw->select( 'revision', 'rev_user_text',
-                       array( 'rev_page' => $this->getID() ), __METHOD__,
-                       array( 'LIMIT' => $limit )
+                       array( 'rev_page' => $this->getID(), 'rev_deleted & '.Revision::DELETED_USER.'=0' ),
+                       __METHOD__,
+                       array( 'LIMIT' => 20 )
                );
                if( $res === false )
                        // This page has no revisions, which is very weird
                        return false;
-               if( $res->numRows() > 1 )
-                               $hasHistory = true;
-               else
-                               $hasHistory = false;
+                       
+               $hasHistory = ( $res->numRows() > 1 );
                $row = $dbw->fetchObject( $res );
                $onlyAuthor = $row->rev_user_text;
                // Try to find a second contributor
@@ -2059,7 +2230,7 @@ class Article {
                // Calculate the maximum amount of chars to get
                // Max content length = max comment length - length of the comment (excl. $1) - '...'
                $maxLength = 255 - (strlen( $reason ) - 2) - 3;
-               $contents = $wgContLang->truncate( $contents, $maxLength, '...' );
+               $contents = $wgContLang->truncate( $contents, $maxLength );
                // Remove possible unfinished links
                $contents = preg_replace( '/\[\[([^\]]*)\]?$/', '$1', $contents );
                // Now replace the '$1' placeholder
@@ -2082,14 +2253,14 @@ class Article {
 
                $reason = $this->DeleteReasonList;
 
-               if( $reason != 'other' && $this->DeleteReason != '') {
+               if( $reason != 'other' && $this->DeleteReason != '' ) {
                        // Entry from drop down menu + additional comment
-                       $reason .= ': ' . $this->DeleteReason;
+                       $reason .= wfMsgForContent( 'colon-separator' ) . $this->DeleteReason;
                } elseif( $reason == 'other' ) {
                        $reason = $this->DeleteReason;
                }
                # Flag to hide all contents of the archived revisions
-               $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed('suppressrevision');
+               $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
 
                # This code desperately needs to be totally rewritten
 
@@ -2102,7 +2273,7 @@ class Article {
                # Check permissions
                $permission_errors = $this->mTitle->getUserPermissionsErrors( 'delete', $wgUser );
 
-               if(count($permission_errors)>0) {
+               if( count( $permission_errors ) > 0 ) {
                        $wgOut->showPermissionsErrorPage( $permission_errors );
                        return;
                }
@@ -2114,7 +2285,9 @@ class Article {
                $conds = $this->mTitle->pageCond();
                $latest = $dbw->selectField( 'page', 'page_latest', $conds, __METHOD__ );
                if( $latest === false ) {
-                       $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
+                       $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
+                       $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
+                       LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() );
                        return;
                }
 
@@ -2143,8 +2316,8 @@ class Article {
 
                // If the page has a history, insert a warning
                if( $hasHistory && !$confirm ) {
-                       $skin=$wgUser->getSkin();
-                       $wgOut->addHTML( '<strong>' . wfMsg( 'historywarning' ) . ' ' . $skin->historyLink() . '</strong>' );
+                       $skin = $wgUser->getSkin();
+                       $wgOut->addHTML( '<strong>' . wfMsgExt( 'historywarning', array( 'parseinline' ) ) . ' ' . $skin->historyLink() . '</strong>' );
                        if( $bigHistory ) {
                                global $wgLang, $wgDeleteRevisionsLimit;
                                $wgOut->wrapWikiMsg( "<div class='error'>\n$1</div>\n",
@@ -2233,17 +2406,17 @@ class Article {
 
                wfDebug( "Article::confirmDelete\n" );
 
-               $wgOut->setSubtitle( wfMsg( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle ) ) );
+               $wgOut->setSubtitle( wfMsgHtml( 'delete-backlink', $wgUser->getSkin()->makeKnownLinkObj( $this->mTitle ) ) );
                $wgOut->setRobotPolicy( 'noindex,nofollow' );
                $wgOut->addWikiMsg( 'confirmdeletetext' );
 
                if( $wgUser->isAllowed( 'suppressrevision' ) ) {
                        $suppress = "<tr id=\"wpDeleteSuppressRow\" name=\"wpDeleteSuppressRow\">
                                        <td></td>
-                                       <td class='mw-input'>" .
+                                       <td class='mw-input'><strong>" .
                                                Xml::checkLabel( wfMsg( 'revdelete-suppress' ),
                                                        'wpSuppress', 'wpSuppress', false, array( 'tabindex' => '4' ) ) .
-                                       "</td>
+                                       "</strong></td>
                                </tr>";
                } else {
                        $suppress = '';
@@ -2325,10 +2498,13 @@ class Article {
                                $wgOut->returnToMain( false );
                                wfRunHooks('ArticleDeleteComplete', array(&$this, &$wgUser, $reason, $id));
                        } else {
-                               if( $error == '' )
-                                       $wgOut->showFatalError( wfMsg( 'cannotdelete' ) );
-                               else
+                               if( $error == '' ) {
+                                       $wgOut->showFatalError( wfMsgExt( 'cannotdelete', array( 'parse' ) ) );
+                                       $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) );
+                                       LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTitle->getPrefixedText() );
+                               } else {
                                        $wgOut->showFatalError( $error );
+                               }
                        }
                }
        }
@@ -2353,7 +2529,7 @@ class Article {
                        return false;
                }
 
-               $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getContent() ), -1 );
+               $u = new SiteStatsUpdate( 0, 1, -(int)$this->isCountable( $this->getRawText() ), -1 );
                array_push( $wgDeferredUpdateList, $u );
 
                // Bitfields to further suppress the content
@@ -2411,6 +2587,14 @@ class Article {
                        $dbw->rollback();
                        return false;
                }
+               
+               # Fix category table counts
+               $cats = array();
+               $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ );
+               foreach( $res as $row ) {
+                       $cats []= $row->cl_to;
+               }
+               $this->updateCategoryCounts( array(), $cats );
 
                # If using cascading deletes, we can skip some explicit deletes
                if( !$dbw->cascadingDeletes() ) {
@@ -2444,18 +2628,9 @@ class Article {
 
                # Clear caches
                Article::onArticleDelete( $this->mTitle );
-               
-               # Fix category table counts
-               $cats = array();
-               $res = $dbw->select( 'categorylinks', 'cl_to', array( 'cl_from' => $id ), __METHOD__ );
-               foreach( $res as $row ) {
-                       $cats []= $row->cl_to;
-               }
-               $this->updateCategoryCounts( array(), $cats );
 
                # Clear the cached article id so the interface doesn't act like we exist
                $this->mTitle->resetArticleID( 0 );
-               $this->mTitle->mArticleID = 0;
 
                # Log the deletion, if the page was suppressed, log it at Oversight instead
                $logtype = $suppress ? 'suppress' : 'delete';
@@ -2463,7 +2638,7 @@ class Article {
 
                # Make sure logging got through
                $log->addEntry( 'delete', $this->mTitle, $reason, array() );
-               
+
                $dbw->commit();
 
                return true;
@@ -2615,7 +2790,7 @@ class Article {
                        $revId = false;
                }
 
-               wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target ) );
+               wfRunHooks( 'ArticleRollbackComplete', array( $this, $wgUser, $target, $current ) );
 
                $resultDetails = array(
                        'summary' => $summary,
@@ -2701,16 +2876,13 @@ class Article {
        /**
         * Do standard deferred updates after page view
         */
-       protected function viewUpdates() {
-               global $wgDeferredUpdateList, $wgUser;
-               if( 0 != $this->getID() ) {
-                       # Don't update page view counters on views from bot users (bug 14044)
-                       global $wgDisableCounters;
-                       if( !$wgDisableCounters && !$wgUser->isAllowed( 'bot' ) ) {
-                               Article::incViewCount( $this->getID() );
-                               $u = new SiteStatsUpdate( 1, 0, 0 );
-                               array_push( $wgDeferredUpdateList, $u );
-                       }
+       public function viewUpdates() {
+               global $wgDeferredUpdateList, $wgDisableCounters, $wgUser;
+               # Don't update page view counters on views from bot users (bug 14044)
+               if( !$wgDisableCounters && !$wgUser->isAllowed('bot') && $this->getID() ) {
+                       Article::incViewCount( $this->getID() );
+                       $u = new SiteStatsUpdate( 1, 0, 0 );
+                       array_push( $wgDeferredUpdateList, $u );
                }
                # Update newtalk / watchlist notification status
                $wgUser->clearNotification( $this->mTitle );
@@ -2770,13 +2942,15 @@ class Article {
 
                # Save it to the parser cache
                if( $wgEnableParserCache ) {
+                       $popts = new ParserOptions;
+                       $popts->setTidy( true );
+                       $popts->enableLimitReport();
                        $parserCache = ParserCache::singleton();
-                       $parserCache->save( $editInfo->output, $this, $wgUser );
+                       $parserCache->save( $editInfo->output, $this, $popts );
                }
 
                # Update the links tables
-               $u = new LinksUpdate( $this->mTitle, $editInfo->output, false );
-               $u->setRecursiveTouch( $changed ); // refresh/invalidate including pages too
+               $u = new LinksUpdate( $this->mTitle, $editInfo->output );
                $u->doUpdate();
                
                wfRunHooks( 'ArticleEditUpdates', array( &$this, &$editInfo, $changed ) );
@@ -2860,10 +3034,10 @@ class Article {
         *
         * @param $oldid String: revision ID of this article revision
         */
-       public function setOldSubtitle( $oldid=0 ) {
-               global $wgLang, $wgOut, $wgUser;
+       public function setOldSubtitle( $oldid = 0 ) {
+               global $wgLang, $wgOut, $wgUser, $wgRequest;
 
-               if( !wfRunHooks( 'DisplayOldSubtitle', array(&$this, &$oldid) ) ) {
+               if( !wfRunHooks( 'DisplayOldSubtitle', array( &$this, &$oldid ) ) ) {
                        return;
                }
 
@@ -2873,34 +3047,34 @@ class Article {
                $td = $wgLang->timeanddate( $this->mTimestamp, true );
                $sk = $wgUser->getSkin();
                $lnk = $current
-                       ? wfMsg( 'currentrevisionlink' )
-                       : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'currentrevisionlink' ) );
+                       ? wfMsgHtml( 'currentrevisionlink' )
+                       : $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'currentrevisionlink' ) );
                $curdiff = $current
-                       ? wfMsg( 'diff' )
-                       : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=cur&oldid='.$oldid );
+                       ? wfMsgHtml( 'diff' )
+                       : $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'diff' ), 'diff=cur&oldid='.$oldid );
                $prev = $this->mTitle->getPreviousRevisionID( $oldid ) ;
                $prevlink = $prev
-                       ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
-                       : wfMsg( 'previousrevision' );
+                       ? $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'previousrevision' ), 'direction=prev&oldid='.$oldid )
+                       : wfMsgHtml( 'previousrevision' );
                $prevdiff = $prev
-                       ? $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=prev&oldid='.$oldid )
-                       : wfMsg( 'diff' );
+                       ? $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'diff' ), 'diff=prev&oldid='.$oldid )
+                       : wfMsgHtml( 'diff' );
                $nextlink = $current
-                       ? wfMsg( 'nextrevision' )
-                       : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'nextrevision' ), 'direction=next&oldid='.$oldid );
+                       ? wfMsgHtml( 'nextrevision' )
+                       : $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'nextrevision' ), 'direction=next&oldid='.$oldid );
                $nextdiff = $current
-                       ? wfMsg( 'diff' )
-                       : $sk->makeKnownLinkObj( $this->mTitle, wfMsg( 'diff' ), 'diff=next&oldid='.$oldid );
+                       ? wfMsgHtml( 'diff' )
+                       : $sk->makeKnownLinkObj( $this->mTitle, wfMsgHtml( 'diff' ), 'diff=next&oldid='.$oldid );
 
                $cdel='';
                if( $wgUser->isAllowed( 'deleterevision' ) ) {
                        $revdel = SpecialPage::getTitleFor( 'Revisiondelete' );
                        if( $revision->isCurrent() ) {
                        // We don't handle top deleted edits too well
-                               $cdel = wfMsgHtml('rev-delundel');
+                               $cdel = wfMsgHtml( 'rev-delundel' );
                        } else if( !$revision->userCan( Revision::DELETED_RESTRICTED ) ) {
                        // If revision was hidden from sysops
-                               $cdel = wfMsgHtml('rev-delundel');
+                               $cdel = wfMsgHtml( 'rev-delundel' );
                        } else {
                                $cdel = $sk->makeKnownLinkObj( $revdel,
                                        wfMsgHtml('rev-delundel'),
@@ -2912,19 +3086,20 @@ class Article {
                        }
                        $cdel = "(<small>$cdel</small>) ";
                }
-               # Show user links if allowed to see them. Normally they
-               # are hidden regardless, but since we can already see the text here...
-               $userlinks = $sk->revUserTools( $revision, false );
+               $unhide = $wgRequest->getInt('unhide') == 1 && $wgUser->matchEditToken( $wgRequest->getVal('token'), $oldid );
+               # Show user links if allowed to see them. If hidden, then show them only if requested...
+               $userlinks = $sk->revUserTools( $revision, !$unhide );
 
                $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, $revision->getID() ) . "</div>\n" .
+               $r = "\n\t\t\t\t<div id=\"mw-{$infomsg}\">" . wfMsgExt( $infomsg, array( 'parseinline', 'replaceafter' ), 
+                       $td, $userlinks, $revision->getID() ) . "</div>\n" .
 
-                    "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsg( 'revision-nav', $prevdiff, 
-                               $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
+                    "\n\t\t\t\t<div id=\"mw-revision-nav\">" . $cdel . wfMsgExt( 'revision-nav', array( 'escapenoentities', 'parsemag', 'replaceafter' ),
+                       $prevdiff, $prevlink, $lnk, $curdiff, $nextlink, $nextdiff ) . "</div>\n\t\t\t";
                $wgOut->setSubtitle( $r );
        }
 
@@ -2974,31 +3149,14 @@ class Article {
         * @return bool
         */
        public function isFileCacheable() {
-               global $wgUser, $wgUseFileCache, $wgShowIPinHeader, $wgRequest, $wgLang, $wgContLang;
-               // Get all query values
-               $queryVals = $wgRequest->getValues();
-               foreach( $queryVals as $query => $val ) {
-                       // Normal page view in query form can have action=view
-                       if( $query !== 'title' && $query !== 'curid' && !($query == 'action' && $val == 'view') ) {
-                               return false;
+               $cacheable = false;
+               if( HTMLFileCache::useFileCache() ) {
+                       $cacheable = $this->getID() && !$this->mRedirectedFrom;
+                       // Extension may have reason to disable file caching on some pages.
+                       if( $cacheable ) {
+                               $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
                        }
                }
-               // 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->mRedirectedFrom
-                       && $ulang === $clang;
-               // Extension may have reason to disable file caching on some pages.
-               if( $cacheable ) {
-                       $cacheable = wfRunHooks( 'IsFileCacheable', array( &$this ) );
-               }
                return $cacheable;
        }
 
@@ -3031,7 +3189,7 @@ class Article {
                if( !$this->mDataLoaded ) {
                        $this->loadPageData();
                }
-               return $this->mLatest;
+               return (int)$this->mLatest;
        }
 
        /**
@@ -3151,7 +3309,7 @@ class Article {
        }
 
        public static function onArticleDelete( $title ) {
-               global $wgUseFileCache, $wgMessageCache;
+               global $wgMessageCache;
                # Update existence markers on article/talk tabs...
                if( $title->isTalkPage() ) {
                        $other = $title->getSubjectPage();
@@ -3165,10 +3323,7 @@ class Article {
                $title->purgeSquid();
 
                # File cache
-               if( $wgUseFileCache ) {
-                       $cm = new HTMLFileCache( $title );
-                       @unlink( $cm->fileCacheName() );
-               }
+               HTMLFileCache::clearFileCache( $title );
 
                # Messages
                if( $title->getNamespace() == NS_MEDIAWIKI ) {
@@ -3184,17 +3339,18 @@ class Article {
                        $user = User::newFromName( $title->getText(), false );
                        $user->setNewtalk( false );
                }
+               # Image redirects
+               RepoGroup::singleton()->getLocalRepo()->invalidateImageRedirect( $title );
        }
 
        /**
         * Purge caches on page update etc
         */
-       public static function onArticleEdit( $title, $transclusions = 'transclusions' ) {
-               global $wgDeferredUpdateList, $wgUseFileCache;
+       public static function onArticleEdit( $title, $flags = '' ) {
+               global $wgDeferredUpdateList;
 
                // Invalidate caches of articles which include this page
-               if( $transclusions !== 'skiptransclusions' )
-                       $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
+               $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'templatelinks' );
 
                // Invalidate the caches of all pages which redirect here
                $wgDeferredUpdateList[] = new HTMLCacheUpdate( $title, 'redirect' );
@@ -3203,10 +3359,7 @@ class Article {
                $title->purgeSquid();
 
                # Clear file cache for this page only
-               if( $wgUseFileCache ) {
-                       $cm = new HTMLFileCache( $title );
-                       @unlink( $cm->fileCacheName() );
-               }
+               HTMLFileCache::clearFileCache( $title );
        }
 
        /**#@-*/
@@ -3236,7 +3389,7 @@ class Article {
 
                $wgOut->setPagetitle( $page->getPrefixedText() );
                $wgOut->setPageTitleActionText( wfMsg( 'info_short' ) );
-               $wgOut->setSubtitle( wfMsg( 'infosubtitle' ) );
+               $wgOut->setSubtitle( wfMsgHtml( 'infosubtitle' ) );
 
                if( !$this->mTitle->exists() ) {
                        $wgOut->addHTML( '<div class="noarticletext">' );
@@ -3286,7 +3439,7 @@ class Article {
         * @param $title Title object
         * @return array
         */
-       protected function pageCountInfo( $title ) {
+       public function pageCountInfo( $title ) {
                $id = $title->getArticleId();
                if( $id == 0 ) {
                        return false;
@@ -3386,8 +3539,7 @@ class Article {
                        global $wgContLang;
                        $truncatedtext = $wgContLang->truncate(
                                str_replace("\n", ' ', $newtext),
-                               max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ),
-                               '...' );
+                               max( 0, 200 - strlen( wfMsgForContent( 'autosumm-new' ) ) ) );
                        return wfMsgForContent( 'autosumm-new', $truncatedtext );
                }
 
@@ -3399,9 +3551,7 @@ class Article {
                        global $wgContLang;
                        $truncatedtext = $wgContLang->truncate(
                                $newtext,
-                               max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ),
-                               '...'
-                       );
+                               max( 0, 200 - strlen( wfMsgForContent( 'autosumm-replace' ) ) ) );
                        return wfMsgForContent( 'autosumm-replace', $truncatedtext );
                }
 
@@ -3419,7 +3569,7 @@ class Article {
         * @param $cache Boolean
         */
        public function outputWikiText( $text, $cache = true ) {
-               global $wgParser, $wgUser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
+               global $wgParser, $wgOut, $wgEnableParserCache, $wgUseFileCache;
 
                $popts = $wgOut->parserOptions();
                $popts->setTidy(true);
@@ -3430,7 +3580,7 @@ class Article {
                $popts->enableLimitReport( false );
                if( $wgEnableParserCache && $cache && $this && $parserOutput->getCacheTime() != -1 ) {
                        $parserCache = ParserCache::singleton();
-                       $parserCache->save( $parserOutput, $this, $wgUser );
+                       $parserCache->save( $parserOutput, $this, $popts );
                }
                // Make sure file cache is not used on uncacheable content.
                // Output that has magic words in it can still use the parser cache
@@ -3459,27 +3609,26 @@ class Article {
                                __METHOD__ );
 
                        global $wgContLang;
-
-                       if( $res !== false ) {
-                               foreach( $res as $row ) {
-                                       $tlTemplates[] = $wgContLang->getNsText( $row->tl_namespace ) . ':' . $row->tl_title ;
-                               }
+                       foreach( $res as $row ) {
+                               $tlTemplates["{$row->tl_namespace}:{$row->tl_title}"] = true;
                        }
 
                        # Get templates from parser output.
-                       $poTemplates_allns = $parserOutput->getTemplates();
-
-                       $poTemplates = array ();
-                       foreach ( $poTemplates_allns as $ns_templates ) {
-                               $poTemplates = array_merge( $poTemplates, $ns_templates );
+                       $poTemplates = array();
+                       foreach ( $parserOutput->getTemplates() as $ns => $templates ) {
+                               foreach ( $templates as $dbk => $id ) {
+                                       $key = $row->tl_namespace . ':'. $row->tl_title;
+                                       $poTemplates["$ns:$dbk"] = true;
+                               }
                        }
 
                        # Get the diff
-                       $templates_diff = array_diff( $poTemplates, $tlTemplates );
+                       # Note that we simulate array_diff_key in PHP <5.0.x
+                       $templates_diff = array_diff_key( $poTemplates, $tlTemplates );
 
                        if( count( $templates_diff ) > 0 ) {
                                # Whee, link updates time.
-                               $u = new LinksUpdate( $this->mTitle, $parserOutput );
+                               $u = new LinksUpdate( $this->mTitle, $parserOutput, false );
                                $u->doUpdate();
                        }
                }