Missing out call
[lhc/web/wiklou.git] / includes / Title.php
index 63ec737..d08a2c4 100644 (file)
@@ -33,8 +33,8 @@ class Title {
         */
        static private $titleCache=array();
        static private $interwikiCache=array();
-       
-       
+
+
        /**
         * All member variables should be considered private
         * Please use the accessor functions
@@ -63,6 +63,8 @@ class Title {
        var $mDefaultNamespace;         # Namespace index when there is no namespace
                                        # Zero except in {{transclusion}} tags
        var $mWatched;                  # Is $wgUser watching this page? NULL if unfilled, accessed through userIsWatching()
+       var $mLength;              # The page length, 0 for special pages
+       var $mRedirect;            # Is the article at this title a redirect?
        /**#@-*/
 
 
@@ -83,6 +85,8 @@ class Title {
                $this->mWatched = NULL;
                $this->mLatestID = false;
                $this->mOldRestrictions = false;
+               $this->mLength = -1;
+               $this->mRedirect = NULL;
        }
 
        /**
@@ -204,9 +208,12 @@ class Title {
        }
 
        /**
-        * Make an array of titles from an array of IDs 
+        * Make an array of titles from an array of IDs
         */
        public static function newFromIDs( $ids ) {
+               if ( !count( $ids ) ) {
+                       return array();
+               }
                $dbr = wfGetDB( DB_SLAVE );
                $res = $dbr->select( 'page', array( 'page_namespace', 'page_title' ),
                        'page_id IN (' . $dbr->makeList( $ids ) . ')', __METHOD__ );
@@ -218,6 +225,21 @@ class Title {
                return $titles;
        }
 
+       /**
+        * Make a Title object from a DB row
+        * @param Row $row (needs at least page_title,page_namespace)
+        */
+       public static function newFromRow( $row ) {
+               $t = self::makeTitle( $row->page_namespace, $row->page_title );
+
+               $t->mArticleID = isset($row->page_id) ? intval($row->page_id) : -1;
+               $t->mLength = isset($row->page_len) ? intval($row->page_len) : -1;
+               $t->mRedirect = isset($row->page_is_redirect) ? (bool)$row->page_is_redirect : NULL;
+               $t->mLatestID = isset($row->page_latest) ? $row->page_latest : false;
+
+               return $t;
+       }
+
        /**
         * Create a new Title from a namespace index and a DB key.
         * It's assumed that $ns and $title are *valid*, for instance when
@@ -265,7 +287,12 @@ class Title {
         * @return Title the new object
         */
        public static function newMainPage() {
-               return Title::newFromText( wfMsgForContent( 'mainpage' ) );
+               $title = Title::newFromText( wfMsgForContent( 'mainpage' ) );
+               // Don't give fatal errors if the message is broken
+               if ( !$title ) {
+                       $title = Title::newFromText( 'Main Page' );
+               }
+               return $title;
        }
 
        /**
@@ -277,10 +304,10 @@ class Title {
         */
        public static function newFromRedirect( $text ) {
                $redir = MagicWord::get( 'redirect' );
-               if( $redir->matchStart( $text ) ) {
+               if( $redir->matchStart( trim($text) ) ) {
                        // Extract the first link and see if it's usable
                        $m = array();
-                       if( preg_match( '!\[{2}(.*?)(?:\||\]{2})!', $text, $m ) ) {
+                       if( preg_match( '!\[{2}(.*?)(?:\|.*?)?\]{2}!', $text, $m ) ) {
                                // Strip preceding colon used to "escape" categories, etc.
                                // and URL-decode links
                                if( strpos( $m[1], '%' ) !== false ) {
@@ -423,7 +450,7 @@ class Title {
 
                return $s->iw_url;
        }
-       
+
        /**
         * Fetch interwiki prefix data from local cache in constant database
         *
@@ -569,7 +596,7 @@ class Title {
         */
        public function getSubjectNsText() {
                global $wgContLang;
-               return $wgContLang->getNsText( Namespace::getSubject( $this->mNamespace ) );
+               return $wgContLang->getNsText( MWNamespace::getSubject( $this->mNamespace ) );
        }
 
        /**
@@ -578,7 +605,7 @@ class Title {
         */
        public function getTalkNsText() {
                global $wgContLang;
-               return( $wgContLang->getNsText( Namespace::getTalk( $this->mNamespace ) ) );
+               return( $wgContLang->getNsText( MWNamespace::getTalk( $this->mNamespace ) ) );
        }
 
        /**
@@ -586,7 +613,7 @@ class Title {
         * @return bool
         */
        public function canTalk() {
-               return( Namespace::canTalk( $this->mNamespace ) );
+               return( MWNamespace::canTalk( $this->mNamespace ) );
        }
 
        /**
@@ -670,7 +697,7 @@ class Title {
         */
        public function getBaseText() {
                global $wgNamespacesWithSubpages;
-               if( isset( $wgNamespacesWithSubpages[ $this->mNamespace ] ) && $wgNamespacesWithSubpages[ $this->mNamespace ] ) {
+               if( !empty( $wgNamespacesWithSubpages[$this->mNamespace] ) ) {
                        $parts = explode( '/', $this->getText() );
                        # Don't discard the real title if there's no subpage involved
                        if( count( $parts ) > 1 )
@@ -794,16 +821,15 @@ class Title {
                } else {
                        $dbkey = wfUrlencode( $this->getPrefixedDBkey() );
                        if ( $query == '' ) {
-                               if($variant!=false && $wgContLang->hasVariants()){
-                                       if($wgVariantArticlePath==false) {
+                               if( $variant != false && $wgContLang->hasVariants() ) {
+                                       if( $wgVariantArticlePath == false ) {
                                                $variantArticlePath =  "$wgScript?title=$1&variant=$2"; // default
                                        } else {
                                                $variantArticlePath = $wgVariantArticlePath;
                                        }
                                        $url = str_replace( '$2', urlencode( $variant ), $variantArticlePath );
                                        $url = str_replace( '$1', $dbkey, $url  );
-                               }
-                               else {
+                               } else {
                                        $url = str_replace( '$1', $dbkey, $wgArticlePath );
                                }
                        } else {
@@ -828,7 +854,7 @@ class Title {
                                        $url = "{$wgScript}?title={$dbkey}&{$query}";
                                }
                        }
-                       
+
                        // FIXME: this causes breakage in various places when we
                        // actually expected a local URL and end up with dupe prefixes.
                        if ($wgRequest->getVal('action') == 'render') {
@@ -931,31 +957,24 @@ class Title {
        /**
         * Does the title correspond to a protected article?
         * @param string $what the action the page is protected from,
-        *      by default checks move and edit
+        * by default checks move and edit
         * @return boolean
         */
        public function isProtected( $action = '' ) {
-               global $wgRestrictionLevels;
+               global $wgRestrictionLevels, $wgRestrictionTypes;
 
                # Special pages have inherent protection
                if( $this->getNamespace() == NS_SPECIAL )
                        return true;
 
-               # Check regular protection levels                               
-               if( $action == 'edit' || $action == '' ) {
-                       $r = $this->getRestrictions( 'edit' );
-                       foreach( $wgRestrictionLevels as $level ) {
-                               if( in_array( $level, $r ) && $level != '' ) {
-                                       return( true );
-                               }
-                       }
-               }
-               
-               if( $action == 'move' || $action == '' ) {
-                       $r = $this->getRestrictions( 'move' );
-                       foreach( $wgRestrictionLevels as $level ) {
-                               if( in_array( $level, $r ) && $level != '' ) {
-                                       return( true );
+               # Check regular protection levels
+               foreach( $wgRestrictionTypes as $type ){
+                       if( $action == $type || $action == '' ) {
+                               $r = $this->getRestrictions( $type );
+                               foreach( $wgRestrictionLevels as $level ) {
+                                       if( in_array( $level, $r ) && $level != '' ) {
+                                               return true;
+                                       }
                                }
                        }
                }
@@ -964,7 +983,7 @@ class Title {
        }
 
        /**
-        * Is $wgUser is watching this page?
+        * Is $wgUser watching this page?
         * @return boolean
         */
        public function userIsWatching() {
@@ -980,7 +999,7 @@ class Title {
                return $this->mWatched;
        }
 
-       /**
+       /**
         * Can $wgUser perform $action on this page?
         * This skips potentially expensive cascading permission checks.
         *
@@ -999,7 +1018,7 @@ class Title {
        /**
         * Determines if $wgUser is unable to edit this page because it has been protected
         * by $wgNamespaceProtection.
-        * 
+        *
         * @return boolean
         */
        public function isNamespaceProtected() {
@@ -1013,7 +1032,7 @@ class Title {
                return false;
        }
 
-       /**
+       /**
         * Can $wgUser perform $action on this page?
         * @param string $action action that permission needs to be checked for
         * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
@@ -1024,27 +1043,24 @@ class Title {
                return ( $this->getUserPermissionsErrorsInternal( $action, $wgUser, $doExpensiveQueries ) === array());
        }
 
-        /**
+       /**
         * Can $user perform $action on this page?
+        *
+        * FIXME: This *does not* check throttles (User::pingLimiter()).
+        *
         * @param string $action action that permission needs to be checked for
+        * @param User $user user to check
         * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
         * @return array Array of arrays of the arguments to wfMsg to explain permissions problems.
-       */
+        */
        public function getUserPermissionsErrors( $action, $user, $doExpensiveQueries = true ) {
                $errors = $this->getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries );
 
                global $wgContLang;
                global $wgLang;
+               global $wgEmailConfirmToEdit;
 
-               if ( wfReadOnly() && $action != 'read' ) {
-                       global $wgReadOnly;
-                       $errors[] = array( 'readonlytext', $wgReadOnly );
-               }
-
-               global $wgEmailConfirmToEdit, $wgUser;
-
-               if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() )
-               {
+               if ( $wgEmailConfirmToEdit && !$user->isEmailConfirmed() ) {
                        $errors[] = array( 'confirmedittext' );
                }
 
@@ -1056,6 +1072,9 @@ class Title {
 
                        $id = $user->blockedBy();
                        $reason = $user->blockedFor();
+                       if( $reason == '' ) {
+                               $reason = wfMsg( 'blockednoreason' );
+                       }
                        $ip = wfGetIP();
 
                        if ( is_numeric( $id ) ) {
@@ -1090,39 +1109,65 @@ class Title {
 
                        $intended = $user->mBlock->mAddress;
 
-                       $errors[] = array ( ($block->mAuto ? 'autoblockedtext' : 'blockedtext'), $link, $reason, $ip, $name, $blockid, $blockExpiry, $intended, $blockTimestamp );
+                       $errors[] = array( ($block->mAuto ? 'autoblockedtext' : 'blockedtext'), $link, $reason, $ip, $name, 
+                               $blockid, $blockExpiry, $intended, $blockTimestamp );
                }
 
                return $errors;
        }
 
        /**
-        * Can $user perform $action on this page?
-        * This is an internal function, which checks ONLY that previously checked by userCan (i.e. it leaves out checks on wfReadOnly() and blocks)
+        * Can $user perform $action on this page? This is an internal function,
+        * which checks ONLY that previously checked by userCan (i.e. it leaves out
+        * checks on wfReadOnly() and blocks)
+        *
         * @param string $action action that permission needs to be checked for
+        * @param User $user user to check
         * @param bool $doExpensiveQueries Set this to false to avoid doing unnecessary queries.
         * @return array Array of arrays of the arguments to wfMsg to explain permissions problems.
         */
        private function getUserPermissionsErrorsInternal( $action, $user, $doExpensiveQueries = true ) {
-               $fname = 'Title::userCan';
-               wfProfileIn( $fname );
+               wfProfileIn( __METHOD__ );
 
                $errors = array();
 
+               // Use getUserPermissionsErrors instead
                if ( !wfRunHooks( 'userCan', array( &$this, &$user, $action, &$result ) ) ) {
+                       wfProfileOut( __METHOD__ );
                        return $result ? array() : array( array( 'badaccess-group0' ) );
                }
 
+               if (!wfRunHooks( 'getUserPermissionsErrors', array( &$this, &$user, $action, &$result ) ) ) {
+                       if ($result != array() && is_array($result) && !is_array($result[0]))
+                               $errors[] = $result; # A single array representing an error
+                       else if (is_array($result) && is_array($result[0]))
+                               $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
+                       else if ($result != '' && $result != null && $result !== true && $result !== false)
+                               $errors[] = array($result); # A string representing a message-id
+                       else if ($result === false )
+                               $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
+               }
+               if ($doExpensiveQueries && !wfRunHooks( 'getUserPermissionsErrorsExpensive', array( &$this, &$user, $action, &$result ) ) ) {
+                       if ($result != array() && is_array($result) && !is_array($result[0]))
+                               $errors[] = $result; # A single array representing an error
+                       else if (is_array($result) && is_array($result[0]))
+                               $errors = array_merge( $errors, $result ); # A nested array representing multiple errors
+                       else if ($result != '' && $result != null && $result !== true && $result !== false)
+                               $errors[] = array($result); # A string representing a message-id
+                       else if ($result === false )
+                               $errors[] = array('badaccess-group0'); # a generic "We don't want them to do that"
+               }
+
                if( NS_SPECIAL == $this->mNamespace ) {
                        $errors[] = array('ns-specialprotected');
                }
-               
+
                if ( $this->isNamespaceProtected() ) {
                        $ns = $this->getNamespace() == NS_MAIN
                                ? wfMsg( 'nstab-main' )
                                : $this->getNsText();
-                       $errors[] = (NS_MEDIAWIKI == $this->mNamespace 
-                               ? array('protectedinterface') 
+                       $errors[] = (NS_MEDIAWIKI == $this->mNamespace
+                               ? array('protectedinterface')
                                : array( 'namespaceprotected',  $ns ) );
                }
 
@@ -1135,11 +1180,11 @@ class Title {
                # XXX: this might be better using restrictions
                # XXX: Find a way to work around the php bug that prevents using $this->userCanEditCssJsSubpage() from working
                if( $this->isCssJsSubpage()
-                       && !$user->isAllowed('editinterface')
+                       && !$user->isAllowed('editusercssjs')
                        && !preg_match('/^'.preg_quote($user->getName(), '/').'\//', $this->mTextform) ) {
                        $errors[] = array('customcssjsprotected');
                }
-               
+
                if ( $doExpensiveQueries && !$this->isCssJsSubpage() ) {
                        # We /could/ use the protection level on the source page, but it's fairly ugly
                        #  as we have to establish a precedence hierarchy for pages included by multiple
@@ -1162,58 +1207,163 @@ class Title {
                                }
                        }
                }
-               
+
                foreach( $this->getRestrictions($action) as $right ) {
                        // Backwards compatibility, rewrite sysop -> protect
                        if ( $right == 'sysop' ) {
                                $right = 'protect';
                        }
                        if( '' != $right && !$user->isAllowed( $right ) ) {
-                               $errors[] = array( 'protectedpagetext' );
+                               //Users with 'editprotected' permission can edit protected pages
+                               if( $action=='edit' && $user->isAllowed( 'editprotected' ) ) {
+                                       //Users with 'editprotected' permission cannot edit protected pages
+                                       //with cascading option turned on.
+                                       if($this->mCascadeRestriction) {
+                                               $errors[] = array( 'protectedpagetext', $right );
+                                       } else {
+                                               //Nothing, user can edit!
+                                       }
+                               } else {
+                                       $errors[] = array( 'protectedpagetext', $right );
+                               }
+                       }
+               }
+
+               if ($action == 'protect') {
+                       if ($this->getUserPermissionsErrors('edit', $user) != array()) {
+                               $errors[] = array( 'protect-cantedit' ); // If they can't edit, they shouldn't protect.
                        }
                }
 
-               if( $action == 'create' ) {
+               if ($action == 'create') {
+                       $title_protection = $this->getTitleProtection();
+
+                       if (is_array($title_protection)) {
+                               extract($title_protection);
+
+                               if ($pt_create_perm == 'sysop')
+                                       $pt_create_perm = 'protect';
+
+                               if ($pt_create_perm == '' || !$user->isAllowed($pt_create_perm)) {
+                                       $errors[] = array ( 'titleprotected', User::whoIs($pt_user), $pt_reason );
+                               }
+                       }
+
                        if( (  $this->isTalkPage() && !$user->isAllowed( 'createtalk' ) ) ||
                                ( !$this->isTalkPage() && !$user->isAllowed( 'createpage' ) ) ) {
                                $errors[] = $user->isAnon() ? array ('nocreatetext') : array ('nocreate-loggedin');
                        }
                } elseif( $action == 'move' && !( $this->isMovable() && $user->isAllowed( 'move' ) ) ) {
                        $errors[] = $user->isAnon() ? array ( 'movenologintext' ) : array ('movenotallowed');
-        } else if ( !$user->isAllowed( $action ) ) {
+               } elseif ( !$user->isAllowed( $action ) ) {
                        $return = null;
-                   $groups = array();
+                       $groups = array();
                        global $wgGroupPermissions;
-                       foreach( $wgGroupPermissions as $key => $value ) {
-                           if( isset( $value[$action] ) && $value[$action] == true ) {
-                               $groupName = User::getGroupName( $key );
-                               $groupPage = User::getGroupPage( $key );
-                               if( $groupPage ) {
-                                   $skin = $user->getSkin();
-                                   $groups[] = '[['.$groupPage->getPrefixedText().'|'.$groupName.']]';
-                               } else {
-                                   $groups[] = $groupName;
-                               }
-                           }
-                       }
-                       $n = count( $groups );
-                       $groups = implode( ', ', $groups );
-                       switch( $n ) {
-                           case 0:
-                           case 1:
-                           case 2:
-                               $return = array( "badaccess-group$n", $groups );
-                               break;
-                           default:
-                               $return = array( 'badaccess-groups', $groups );
-                       }
+                       foreach( $wgGroupPermissions as $key => $value ) {
+                               if( isset( $value[$action] ) && $value[$action] == true ) {
+                                       $groupName = User::getGroupName( $key );
+                                       $groupPage = User::getGroupPage( $key );
+                                       if( $groupPage ) {
+                                               $groups[] = '[['.$groupPage->getPrefixedText().'|'.$groupName.']]';
+                                       } else {
+                                               $groups[] = $groupName;
+                                       }
+                               }
+                       }
+                       $n = count( $groups );
+                       $groups = implode( ', ', $groups );
+                       switch( $n ) {
+                               case 0:
+                               case 1:
+                               case 2:
+                                       $return = array( "badaccess-group$n", $groups );
+                                       break;
+                               default:
+                                       $return = array( 'badaccess-groups', $groups );
+                       }
                        $errors[] = $return;
                }
 
-               wfProfileOut( $fname );
+               wfProfileOut( __METHOD__ );
                return $errors;
        }
 
+       /**
+        * Is this title subject to title protection?
+        * @return mixed An associative array representing any existent title
+        *   protection, or false if there's none.
+        */
+       private function getTitleProtection() {
+               // Can't protect pages in special namespaces
+               if ( $this->getNamespace() < 0 ) {
+                       return false;
+               }
+
+               $dbr = wfGetDB( DB_SLAVE );
+               $res = $dbr->select( 'protected_titles', '*',
+                       array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()) );
+
+               if ($row = $dbr->fetchRow( $res )) {
+                       return $row;
+               } else {
+                       return false;
+               }
+       }
+
+       public function updateTitleProtection( $create_perm, $reason, $expiry ) {
+               global $wgGroupPermissions,$wgUser,$wgContLang;
+
+               if ($create_perm == implode(',',$this->getRestrictions('create'))
+                       && $expiry == $this->mRestrictionsExpiry) {
+                       // No change
+                       return true;
+               }
+
+               list ($namespace, $title) = array( $this->getNamespace(), $this->getDBkey() );
+
+               $dbw = wfGetDB( DB_MASTER );
+
+               $encodedExpiry = Block::encodeExpiry($expiry, $dbw );
+
+               $expiry_description = '';
+               if ( $encodedExpiry != 'infinity' ) {
+                       $expiry_description = ' (' . wfMsgForContent( 'protect-expiring', $wgContLang->timeanddate( $expiry ) ).')';
+               }
+
+               # Update protection table
+               if ($create_perm != '' ) {
+                       $dbw->replace( 'protected_titles', array(array('pt_namespace', 'pt_title')),
+                               array( 'pt_namespace' => $namespace, 'pt_title' => $title
+                                       , 'pt_create_perm' => $create_perm
+                                       , 'pt_timestamp' => Block::encodeExpiry(wfTimestampNow(), $dbw)
+                                       , 'pt_expiry' => $encodedExpiry
+                                       , 'pt_user' => $wgUser->getId(), 'pt_reason' => $reason ), __METHOD__  );
+               } else {
+                       $dbw->delete( 'protected_titles', array( 'pt_namespace' => $namespace,
+                               'pt_title' => $title ), __METHOD__ );
+               }
+               # Update the protection log
+               $log = new LogPage( 'protect' );
+
+               if( $create_perm ) {
+                       $log->addEntry( $this->mRestrictions['create'] ? 'modify' : 'protect', $this, trim( $reason . " [create=$create_perm] $expiry_description" ) );
+               } else {
+                       $log->addEntry( 'unprotect', $this, $reason );
+               }
+
+               return true;
+       }
+
+       /**
+        * Remove any title protection (due to page existing
+        */
+       public function deleteTitleProtection() {
+               $dbw = wfGetDB( DB_MASTER );
+
+               $dbw->delete( 'protected_titles',
+                       array ('pt_namespace' => $this->getNamespace(), 'pt_title' => $this->getDBkey()), __METHOD__ );
+       }
+
        /**
         * Can $wgUser edit this page?
         * @return boolean
@@ -1248,7 +1398,7 @@ class Title {
         * @return boolean
         */
        public function isMovable() {
-               return Namespace::isMovable( $this->getNamespace() )
+               return MWNamespace::isMovable( $this->getNamespace() )
                        && $this->getInterwiki() == '';
        }
 
@@ -1258,7 +1408,7 @@ class Title {
         * @todo fold these checks into userCan()
         */
        public function userCanRead() {
-               global $wgUser;
+               global $wgUser, $wgGroupPermissions;
 
                $result = null;
                wfRunHooks( 'userCan', array( &$this, &$wgUser, 'read', &$result ) );
@@ -1266,42 +1416,58 @@ class Title {
                        return $result;
                }
 
+               # Shortcut for public wikis, allows skipping quite a bit of code
+               if ($wgGroupPermissions['*']['read'])
+                       return true;
+
                if( $wgUser->isAllowed( 'read' ) ) {
                        return true;
                } else {
                        global $wgWhitelistRead;
 
-                       /** 
+                       /**
                         * Always grant access to the login page.
                         * Even anons need to be able to log in.
                        */
                        if( $this->isSpecial( 'Userlogin' ) || $this->isSpecial( 'Resetpass' ) ) {
                                return true;
                        }
-                       
+
+                       /**
+                        * Bail out if there isn't whitelist
+                        */
+                       if( !is_array($wgWhitelistRead) ) {
+                               return false;
+                       }
+
                        /**
                         * Check for explicit whitelisting
                         */
                        $name = $this->getPrefixedText();
-                       if( $wgWhitelistRead && in_array( $name, $wgWhitelistRead, true ) )
+                       if( in_array( $name, $wgWhitelistRead, true ) )
                                return true;
-                       
+
                        /**
                         * Old settings might have the title prefixed with
                         * a colon for main-namespace pages
                         */
-                       if( $wgWhitelistRead && $this->getNamespace() == NS_MAIN ) {
+                       if( $this->getNamespace() == NS_MAIN ) {
                                if( in_array( ':' . $name, $wgWhitelistRead ) )
                                        return true;
                        }
-                       
+
                        /**
                         * If it's a special page, ditch the subpage bit
                         * and check again
                         */
                        if( $this->getNamespace() == NS_SPECIAL ) {
-                               $name = $this->getText();
+                               $name = $this->getDBkey();
                                list( $name, /* $subpage */) = SpecialPage::resolveAliasWithSubpage( $name );
+                               if ( $name === false ) {
+                                       # Invalid special page, but we show standard login required message
+                                       return false;
+                               }
+
                                $pure = SpecialPage::getTitleFor( $name )->getPrefixedText();
                                if( in_array( $pure, $wgWhitelistRead, true ) )
                                        return true;
@@ -1316,7 +1482,7 @@ class Title {
         * @return bool
         */
        public function isTalkPage() {
-               return Namespace::isTalk( $this->getNamespace() );
+               return MWNamespace::isTalk( $this->getNamespace() );
        }
 
        /**
@@ -1325,14 +1491,14 @@ class Title {
         */
        public function isSubpage() {
                global $wgNamespacesWithSubpages;
-               
+
                if( isset( $wgNamespacesWithSubpages[ $this->mNamespace ] ) ) {
                        return ( strpos( $this->getText(), '/' ) !== false && $wgNamespacesWithSubpages[ $this->mNamespace ] == true );
                } else {
                        return false;
                }
        }
-       
+
        /**
         * Could this page contain custom CSS or JavaScript, based
         * on the title?
@@ -1376,14 +1542,14 @@ class Title {
         * @return bool
         */
        public function isCssSubpage() {
-               return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.css$/", $this->mTextform ) );
+               return ( NS_USER == $this->mNamespace && preg_match("/\\/.*\\.css$/", $this->mTextform ) );
        }
        /**
         * Is this a .js subpage of a user page?
         * @return bool
         */
        public function isJsSubpage() {
-               return ( NS_USER == $this->mNamespace and preg_match("/\\/.*\\.js$/", $this->mTextform ) );
+               return ( NS_USER == $this->mNamespace && preg_match("/\\/.*\\.js$/", $this->mTextform ) );
        }
        /**
         * Protect css/js subpages of user pages: can $wgUser edit
@@ -1394,7 +1560,7 @@ class Title {
         */
        public function userCanEditCssJsSubpage() {
                global $wgUser;
-               return ( $wgUser->isAllowed('editinterface') or preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
+               return ( $wgUser->isAllowed('editusercssjs') || preg_match('/^'.preg_quote($wgUser->getName(), '/').'\//', $this->mTextform) );
        }
 
        /**
@@ -1464,7 +1630,7 @@ class Title {
                $sources = $get_pages ? array() : false;
                $now = wfTimestampNow();
                $purgeExpired = false;
-               
+
                while( $row = $dbr->fetchObject( $res ) ) {
                        $expiry = Block::decodeExpiry( $row->pr_expiry );
                        if( $expiry > $now ) {
@@ -1515,10 +1681,15 @@ class Title {
         * @param resource $res restrictions as an SQL result.
         */
        private function loadRestrictionsFromRow( $res, $oldFashionedRestrictions = NULL ) {
-               $dbr = wfGetDb( DB_SLAVE );
+               global $wgRestrictionTypes;
+               $dbr = wfGetDB( DB_SLAVE );
+
+               foreach( $wgRestrictionTypes as $type ){
+                       $this->mRestrictions[$type] = array();
+               }
 
-               $this->mRestrictions['edit'] = array();
-               $this->mRestrictions['move'] = array();
+               $this->mCascadeRestriction = false;
+               $this->mRestrictionsExpiry = Block::decodeExpiry('');
 
                # Backwards-compatibility: also load the restrictions from the page record (old format).
 
@@ -1532,16 +1703,14 @@ class Title {
                                $temp = explode( '=', trim( $restrict ) );
                                if(count($temp) == 1) {
                                        // old old format should be treated as edit/move restriction
-                                       $this->mRestrictions["edit"] = explode( ',', trim( $temp[0] ) );
-                                       $this->mRestrictions["move"] = explode( ',', trim( $temp[0] ) );
+                                       $this->mRestrictions['edit'] = explode( ',', trim( $temp[0] ) );
+                                       $this->mRestrictions['move'] = explode( ',', trim( $temp[0] ) );
                                } else {
                                        $this->mRestrictions[$temp[0]] = explode( ',', trim( $temp[1] ) );
                                }
                        }
 
                        $this->mOldRestrictions = true;
-                       $this->mCascadeRestriction = false;
-                       $this->mRestrictionsExpiry = Block::decodeExpiry('');
 
                }
 
@@ -1553,6 +1722,10 @@ class Title {
                        while ($row = $dbr->fetchObject( $res ) ) {
                                # Cycle through all the restrictions.
 
+                               // Don't take care of restrictions types that aren't in $wgRestrictionTypes
+                               if( !in_array( $row->pr_type, $wgRestrictionTypes ) )
+                                       continue;
+
                                // This code should be refactored, now that it's being used more generally,
                                // But I don't really see any harm in leaving it in Block for now -werdna
                                $expiry = Block::decodeExpiry( $row->pr_expiry );
@@ -1579,12 +1752,32 @@ class Title {
 
        public function loadRestrictions( $oldFashionedRestrictions = NULL ) {
                if( !$this->mRestrictionsLoaded ) {
-                       $dbr = wfGetDB( DB_SLAVE );
+                       if ($this->exists()) {
+                               $dbr = wfGetDB( DB_SLAVE );
+
+                               $res = $dbr->select( 'page_restrictions', '*',
+                                       array ( 'pr_page' => $this->getArticleId() ), __METHOD__ );
+
+                               $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
+                       } else {
+                               $title_protection = $this->getTitleProtection();
 
-                       $res = $dbr->select( 'page_restrictions', '*',
-                               array ( 'pr_page' => $this->getArticleId() ), __METHOD__ );
+                               if (is_array($title_protection)) {
+                                       extract($title_protection);
 
-                       $this->loadRestrictionsFromRow( $res, $oldFashionedRestrictions );
+                                       $now = wfTimestampNow();
+                                       $expiry = Block::decodeExpiry($pt_expiry);
+
+                                       if (!$expiry || $expiry > $now) {
+                                               // Apply the restrictions
+                                               $this->mRestrictionsExpiry = $expiry;
+                                               $this->mRestrictions['create'] = explode(',', trim($pt_create_perm) );
+                                       } else { // Get rid of the old restrictions
+                                               Title::purgeExpiredRestrictions();
+                                       }
+                               }
+                               $this->mRestrictionsLoaded = true;
+                       }
                }
        }
 
@@ -1596,6 +1789,10 @@ class Title {
                $dbw->delete( 'page_restrictions',
                        array( 'pr_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
                        __METHOD__ );
+
+               $dbw->delete( 'protected_titles',
+                       array( 'pt_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ),
+                       __METHOD__ );
        }
 
        /**
@@ -1605,16 +1802,12 @@ class Title {
         * @return array the array of groups allowed to edit this article
         */
        public function getRestrictions( $action ) {
-               if( $this->exists() ) {
-                       if( !$this->mRestrictionsLoaded ) {
-                               $this->loadRestrictions();
-                       }
-                       return isset( $this->mRestrictions[$action] )
-                                       ? $this->mRestrictions[$action]
-                                       : array();
-               } else {
-                       return array();
+               if( !$this->mRestrictionsLoaded ) {
+                       $this->loadRestrictions();
                }
+               return isset( $this->mRestrictions[$action] )
+                               ? $this->mRestrictions[$action]
+                               : array();
        }
 
        /**
@@ -1645,7 +1838,7 @@ class Title {
         * @return int the ID
         */
        public function getArticleID( $flags = 0 ) {
-               $linkCache =& LinkCache::singleton();
+               $linkCache = LinkCache::singleton();
                if ( $flags & GAID_FOR_UPDATE ) {
                        $oldUpdate = $linkCache->forUpdate( true );
                        $this->mArticleID = $linkCache->addLinkObj( $this );
@@ -1658,6 +1851,46 @@ class Title {
                return $this->mArticleID;
        }
 
+       /**
+        * Is this an article that is a redirect page?
+        * Uses link cache, adding it if necessary
+        * @param int $flags a bit field; may be GAID_FOR_UPDATE to select for update
+        * @return bool
+        */
+       public function isRedirect( $flags = 0 ) {
+               if( !is_null($this->mRedirect) )
+                       return $this->mRedirect;
+               # Zero for special pages.
+               # Also, calling getArticleID() loads the field from cache!
+               if( !$this->getArticleID($flags) || $this->getNamespace() == NS_SPECIAL ) {
+                       return false;
+               }
+               $linkCache = LinkCache::singleton();
+               $this->mRedirect = (bool)$linkCache->getGoodLinkFieldObj( $this, 'redirect' );
+
+               return $this->mRedirect;
+       }
+
+       /**
+        * What is the length of this page?
+        * Uses link cache, adding it if necessary
+        * @param int $flags a bit field; may be GAID_FOR_UPDATE to select for update
+        * @return bool
+        */
+       public function getLength( $flags = 0 ) {
+               if( $this->mLength != -1 )
+                       return $this->mLength;
+               # Zero for special pages.
+               # Also, calling getArticleID() loads the field from cache!
+               if( !$this->getArticleID($flags) || $this->getNamespace() == NS_SPECIAL ) {
+                       return 0;
+               }
+               $linkCache = LinkCache::singleton();
+               $this->mLength = intval( $linkCache->getGoodLinkFieldObj( $this, 'length' ) );
+
+               return $this->mLength;
+       }
+
        public function getLatestRevID() {
                if ($this->mLatestID !== false)
                        return $this->mLatestID;
@@ -1680,7 +1913,7 @@ class Title {
         * @param int $newid the new Article ID
         */
        public function resetArticleID( $newid ) {
-               $linkCache =& LinkCache::singleton();
+               $linkCache = LinkCache::singleton();
                $linkCache->clearBadLink( $this->getPrefixedDBkey() );
 
                if ( 0 == $newid ) { $this->mArticleID = -1; }
@@ -1753,13 +1986,23 @@ class Title {
                # Initialisation
                static $rxTc = false;
                if( !$rxTc ) {
-                       # % is needed as well
-                       $rxTc = '/[^' . Title::legalChars() . ']|%[0-9A-Fa-f]{2}/S';
+                       # Matching titles will be held as illegal.
+                       $rxTc = '/' .
+                               # Any character not allowed is forbidden...
+                               '[^' . Title::legalChars() . ']' .
+                               # URL percent encoding sequences interfere with the ability
+                               # to round-trip titles -- you can't link to them consistently.
+                               '|%[0-9A-Fa-f]{2}' .
+                               # XML/HTML character references produce similar issues.
+                               '|&[A-Za-z0-9\x80-\xff]+;' .
+                               '|&#[0-9]+;' .
+                               '|&#x[0-9A-Fa-f]+;' .
+                               '/S';
                }
 
                $this->mInterwiki = $this->mFragment = '';
                $this->mNamespace = $this->mDefaultNamespace; # Usually NS_MAIN
-               
+
                $dbkey = $this->mDbkeyform;
 
                # Strip Unicode bidi override characters.
@@ -1767,7 +2010,7 @@ class Title {
                # override chars get included in list displays.
                $dbkey = str_replace( "\xE2\x80\x8E", '', $dbkey ); // 200E LEFT-TO-RIGHT MARK
                $dbkey = str_replace( "\xE2\x80\x8F", '', $dbkey ); // 200F RIGHT-TO-LEFT MARK
-               
+
                # Clean up whitespace
                #
                $dbkey = preg_replace( '/[ _]+/', '_', $dbkey );
@@ -1868,11 +2111,13 @@ class Title {
                       strpos( $dbkey, './' ) === 0  ||
                       strpos( $dbkey, '../' ) === 0 ||
                       strpos( $dbkey, '/./' ) !== false ||
-                      strpos( $dbkey, '/../' ) !== false ) )
+                      strpos( $dbkey, '/../' ) !== false  ||
+                      substr( $dbkey, -2 ) == '/.' ||
+                      substr( $dbkey, -3 ) == '/..' ) )
                {
                        return false;
                }
-               
+
                /**
                 * Magic tilde sequences? Nu-uh!
                 */
@@ -1884,11 +2129,11 @@ class Title {
                 * Limit the size of titles to 255 bytes.
                 * This is typically the size of the underlying database field.
                 * We make an exception for special pages, which don't need to be stored
-                * in the database, and may edge over 255 bytes due to subpage syntax 
+                * in the database, and may edge over 255 bytes due to subpage syntax
                 * for long titles, e.g. [[Special:Block/Long name]]
                 */
                if ( ( $this->mNamespace != NS_SPECIAL && strlen( $dbkey ) > 255 ) ||
-                 strlen( $dbkey ) > 512 ) 
+                 strlen( $dbkey ) > 512 )
                {
                        return false;
                }
@@ -1917,18 +2162,18 @@ class Title {
                        return false;
                }
                // Allow IPv6 usernames to start with '::' by canonicalizing IPv6 titles.
-               // IP names are not allowed for accounts, and can only be referring to 
-               // edits from the IP. Given '::' abbreviations and caps/lowercaps, 
-               // there are numerous ways to present the same IP. Having sp:contribs scan 
-               // them all is silly and having some show the edits and others not is 
+               // IP names are not allowed for accounts, and can only be referring to
+               // edits from the IP. Given '::' abbreviations and caps/lowercaps,
+               // there are numerous ways to present the same IP. Having sp:contribs scan
+               // them all is silly and having some show the edits and others not is
                // inconsistent. Same for talk/userpages. Keep them normalized instead.
-               $dbkey = ($this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK) ? 
+               $dbkey = ($this->mNamespace == NS_USER || $this->mNamespace == NS_USER_TALK) ?
                        IP::sanitizeIP( $dbkey ) : $dbkey;
                // Any remaining initial :s are illegal.
                if ( $dbkey !== '' && ':' == $dbkey{0} ) {
                        return false;
                }
-               
+
                # Fill fields
                $this->mDbkeyform = $dbkey;
                $this->mUrlform = wfUrlencode( $dbkey );
@@ -1941,7 +2186,7 @@ class Title {
        /**
         * Set the fragment for this title
         * This is kind of bad, since except for this rarely-used function, Title objects
-        * are immutable. The reason this is here is because it's better than setting the 
+        * are immutable. The reason this is here is because it's better than setting the
         * members directly, which is what Linker::formatComment was doing previously.
         *
         * @param string $fragment text
@@ -1956,7 +2201,7 @@ class Title {
         * @return Title the object for the talk page
         */
        public function getTalkPage() {
-               return Title::makeTitle( Namespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
+               return Title::makeTitle( MWNamespace::getTalk( $this->getNamespace() ), $this->getDBkey() );
        }
 
        /**
@@ -1966,7 +2211,7 @@ class Title {
         * @return Title the object for the subject page
         */
        public function getSubjectPage() {
-               return Title::makeTitle( Namespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
+               return Title::makeTitle( MWNamespace::getSubject( $this->getNamespace() ), $this->getDBkey() );
        }
 
        /**
@@ -1980,7 +2225,7 @@ class Title {
         * @return array the Title objects linking here
         */
        public function getLinksTo( $options = '', $table = 'pagelinks', $prefix = 'pl' ) {
-               $linkCache =& LinkCache::singleton();
+               $linkCache = LinkCache::singleton();
 
                if ( $options ) {
                        $db = wfGetDB( DB_MASTER );
@@ -1989,11 +2234,11 @@ class Title {
                }
 
                $res = $db->select( array( 'page', $table ),
-                       array( 'page_namespace', 'page_title', 'page_id' ),
+                       array( 'page_namespace', 'page_title', 'page_id', 'page_len', 'page_is_redirect' ),
                        array(
                                "{$prefix}_from=page_id",
                                "{$prefix}_namespace" => $this->getNamespace(),
-                               "{$prefix}_title"     => $this->getDbKey() ),
+                               "{$prefix}_title"     => $this->getDBkey() ),
                        'Title::getLinksTo',
                        $options );
 
@@ -2001,7 +2246,7 @@ class Title {
                if ( $db->numRows( $res ) ) {
                        while ( $row = $db->fetchObject( $res ) ) {
                                if ( $titleObj = Title::makeTitle( $row->page_namespace, $row->page_title ) ) {
-                                       $linkCache->addGoodLinkObj( $row->page_id, $titleObj );
+                                       $linkCache->addGoodLinkObj( $row->page_id, $titleObj, $row->page_len, $row->page_is_redirect );
                                        $retVal[] = $titleObj;
                                }
                        }
@@ -2027,10 +2272,16 @@ class Title {
        /**
         * Get an array of Title objects referring to non-existent articles linked from this page
         *
+        * @todo check if needed (used only in SpecialBrokenRedirects.php, and should use redirect table in this case)
         * @param string $options may be FOR UPDATE
         * @return array the Title objects
         */
        public function getBrokenLinksFrom( $options = '' ) {
+               if ( $this->getArticleId() == 0 ) {
+                       # All links from article ID 0 are false positives
+                       return array();
+               }
+
                if ( $options ) {
                        $db = wfGetDB( DB_MASTER );
                } else {
@@ -2137,10 +2388,20 @@ class Title {
                        return 'badarticleerror';
                }
 
-               if ( $auth && (
-                               !$this->userCan( 'edit' ) || !$nt->userCan( 'edit' ) ||
-                               !$this->userCan( 'move' ) || !$nt->userCan( 'move' ) ) ) {
-                       return 'protectedpage';
+               if ( $auth ) {
+                       global $wgUser;
+                       $errors = array_merge($this->getUserPermissionsErrors('move', $wgUser),
+                                       $this->getUserPermissionsErrors('edit', $wgUser),
+                                       $nt->getUserPermissionsErrors('move', $wgUser),
+                                       $nt->getUserPermissionsErrors('edit', $wgUser));
+                       if($errors !== array())
+                               return $errors[0][0];
+               }
+
+               global $wgUser;
+               $err = null;
+               if( !wfRunHooks( 'AbortMove', array( $this, $nt, $wgUser, &$err ) ) ) {
+                       return 'hookaborted';
                }
 
                # The move is allowed only if (1) the target doesn't exist, or
@@ -2151,6 +2412,11 @@ class Title {
                        if ( ! $this->isValidMoveTarget( $nt ) ) {
                                return 'articleexists';
                        }
+               } else {
+                       $tp = $nt->getTitleProtection();
+                       if ( $tp and !$wgUser->isAllowed( $tp['pt_create_perm'] ) ) {
+                               return 'cantmove-titleprotected';
+                       }
                }
                return true;
        }
@@ -2160,9 +2426,12 @@ class Title {
         * @param Title &$nt the new title
         * @param bool $auth indicates whether $wgUser's permissions
         *      should be checked
+        * @param string $reason The reason for the move
+        * @param bool $createRedirect Whether to create a redirect from the old title to the new title.
+        *  Ignored if the user doesn't have the suppressredirect right.
         * @return mixed true on success, message name on failure
         */
-       public function moveTo( &$nt, $auth = true, $reason = '' ) {
+       public function moveTo( &$nt, $auth = true, $reason = '', $createRedirect = true ) {
                $err = $this->isValidMoveOperation( $nt, $auth );
                if( is_string( $err ) ) {
                        return $err;
@@ -2170,21 +2439,34 @@ class Title {
 
                $pageid = $this->getArticleID();
                if( $nt->exists() ) {
-                       $this->moveOverExistingRedirect( $nt, $reason );
-                       $pageCountChange = 0;
+                       $this->moveOverExistingRedirect( $nt, $reason, $createRedirect );
+                       $pageCountChange = ($createRedirect ? 0 : -1);
                } else { # Target didn't exist, do normal move.
-                       $this->moveToNewTitle( $nt, $reason );
-                       $pageCountChange = 1;
+                       $this->moveToNewTitle( $nt, $reason, $createRedirect );
+                       $pageCountChange = ($createRedirect ? 1 : 0);
                }
                $redirid = $this->getArticleID();
 
-               # Fixing category links (those without piped 'alternate' names) to be sorted under the new title
+               // Category memberships include a sort key which may be customized.
+               // If it's left as the default (the page title), we need to update
+               // the sort key to match the new title.
+               //
+               // Be careful to avoid resetting cl_timestamp, which may disturb
+               // time-based lists on some sites.
+               //
+               // Warning -- if the sort key is *explicitly* set to the old title,
+               // we can't actually distinguish it from a default here, and it'll
+               // be set to the new title even though it really shouldn't.
+               // It'll get corrected on the next edit, but resetting cl_timestamp.
                $dbw = wfGetDB( DB_MASTER );
-               $categorylinks = $dbw->tableName( 'categorylinks' );
-               $sql = "UPDATE $categorylinks SET cl_sortkey=" . $dbw->addQuotes( $nt->getPrefixedText() ) .
-                       " WHERE cl_from=" . $dbw->addQuotes( $pageid ) .
-                       " AND cl_sortkey=" . $dbw->addQuotes( $this->getPrefixedText() );
-               $dbw->query( $sql, 'SpecialMovepage::doSubmit' );
+               $dbw->update( 'categorylinks',
+                       array(
+                               'cl_sortkey' => $nt->getPrefixedText(),
+                               'cl_timestamp=cl_timestamp' ),
+                       array(
+                               'cl_from' => $pageid,
+                               'cl_sortkey' => $this->getPrefixedText() ),
+                       __METHOD__ );
 
                # Update watchlists
 
@@ -2221,7 +2503,15 @@ class Title {
                }
                if( $u )
                        $u->doUpdate();
-               
+               # Update message cache for interface messages
+               if( $nt->getNamespace() == NS_MEDIAWIKI ) {
+                       global $wgMessageCache;
+                       $oldarticle = new Article( $this );
+                       $wgMessageCache->replace( $this->getDBkey(), $oldarticle->getContent() );
+                       $newarticle = new Article( $nt );
+                       $wgMessageCache->replace( $nt->getDBkey(), $newarticle->getContent() );
+               }
+
                global $wgUser;
                wfRunHooks( 'TitleMoveComplete', array( &$this, &$nt, &$wgUser, $pageid, $redirid ) );
                return true;
@@ -2233,9 +2523,12 @@ class Title {
         *
         * @param Title &$nt the page to move to, which should currently
         *      be a redirect
+        * @param string $reason The reason for the move
+        * @param bool $createRedirect Whether to leave a redirect at the old title.
+        *  Ignored if the user doesn't have the suppressredirect right
         */
-       private function moveOverExistingRedirect( &$nt, $reason = '' ) {
-               global $wgUseSquid;
+       private function moveOverExistingRedirect( &$nt, $reason = '', $createRedirect = true ) {
+               global $wgUseSquid, $wgUser;
                $fname = 'Title::moveOverExistingRedirect';
                $comment = wfMsgForContent( '1movedto2_redir', $this->getPrefixedText(), $nt->getPrefixedText() );
 
@@ -2247,13 +2540,25 @@ class Title {
                $newid = $nt->getArticleID();
                $oldid = $this->getArticleID();
                $dbw = wfGetDB( DB_MASTER );
-               $linkCache =& LinkCache::singleton();
 
                # Delete the old redirect. We don't save it to history since
                # by definition if we've got here it's rather uninteresting.
                # We have to remove it so that the next step doesn't trigger
                # a conflict on the unique namespace+title index...
                $dbw->delete( 'page', array( 'page_id' => $newid ), $fname );
+               if ( !$dbw->cascadingDeletes() ) {
+                       $dbw->delete( 'revision', array( 'rev_page' => $newid ), __METHOD__ );
+                       global $wgUseTrackbacks;
+                       if ($wgUseTrackbacks)
+                               $dbw->delete( 'trackbacks', array( 'tb_page' => $newid ), __METHOD__ );
+                       $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), __METHOD__ );
+                       $dbw->delete( 'imagelinks', array( 'il_from' => $newid ), __METHOD__ );
+                       $dbw->delete( 'categorylinks', array( 'cl_from' => $newid ), __METHOD__ );
+                       $dbw->delete( 'templatelinks', array( 'tl_from' => $newid ), __METHOD__ );
+                       $dbw->delete( 'externallinks', array( 'el_from' => $newid ), __METHOD__ );
+                       $dbw->delete( 'langlinks', array( 'll_from' => $newid ), __METHOD__ );
+                       $dbw->delete( 'redirect', array( 'rd_from' => $newid ), __METHOD__ );
+               }
 
                # Save a null revision in the page's history notifying of the move
                $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
@@ -2270,35 +2575,39 @@ class Title {
                        /* WHERE */ array( 'page_id' => $oldid ),
                        $fname
                );
-               $linkCache->clearLink( $nt->getPrefixedDBkey() );
+               $nt->resetArticleID( $oldid );
 
                # Recreate the redirect, this time in the other direction.
-               $mwRedir = MagicWord::get( 'redirect' );
-               $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
-               $redirectArticle = new Article( $this );
-               $newid = $redirectArticle->insertOn( $dbw );
-               $redirectRevision = new Revision( array(
-                       'page'    => $newid,
-                       'comment' => $comment,
-                       'text'    => $redirectText ) );
-               $redirectRevision->insertOn( $dbw );
-               $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
-               $linkCache->clearLink( $this->getPrefixedDBkey() );
+               if($createRedirect || !$wgUser->isAllowed('suppressredirect'))
+               {
+                       $mwRedir = MagicWord::get( 'redirect' );
+                       $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
+                       $redirectArticle = new Article( $this );
+                       $newid = $redirectArticle->insertOn( $dbw );
+                       $redirectRevision = new Revision( array(
+                               'page'    => $newid,
+                               'comment' => $comment,
+                               'text'    => $redirectText ) );
+                       $redirectRevision->insertOn( $dbw );
+                       $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
+
+                       # Now, we record the link from the redirect to the new title.
+                       # It should have no other outgoing links...
+                       $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
+                       $dbw->insert( 'pagelinks',
+                               array(
+                                       'pl_from'      => $newid,
+                                       'pl_namespace' => $nt->getNamespace(),
+                                       'pl_title'     => $nt->getDBkey() ),
+                               $fname );
+               } else {
+                       $this->resetArticleID( 0 );
+               }
 
                # Log the move
                $log = new LogPage( 'move' );
                $log->addEntry( 'move_redir', $this, $reason, array( 1 => $nt->getPrefixedText() ) );
 
-               # Now, we record the link from the redirect to the new title.
-               # It should have no other outgoing links...
-               $dbw->delete( 'pagelinks', array( 'pl_from' => $newid ), $fname );
-               $dbw->insert( 'pagelinks',
-                       array(
-                               'pl_from'      => $newid,
-                               'pl_namespace' => $nt->getNamespace(),
-                               'pl_title'     => $nt->getDbKey() ),
-                       $fname );
-
                # Purge squid
                if ( $wgUseSquid ) {
                        $urls = array_merge( $nt->getSquidURLs(), $this->getSquidURLs() );
@@ -2310,9 +2619,12 @@ class Title {
        /**
         * Move page to non-existing title.
         * @param Title &$nt the new Title
+        * @param string $reason The reason for the move
+        * @param bool $createRedirect Whether to create a redirect from the old title to the new title
+        *  Ignored if the user doesn't have the suppressredirect right
         */
-       private function moveToNewTitle( &$nt, $reason = '' ) {
-               global $wgUseSquid;
+       private function moveToNewTitle( &$nt, $reason = '', $createRedirect = true ) {
+               global $wgUseSquid, $wgUser;
                $fname = 'MovePageForm::moveToNewTitle';
                $comment = wfMsgForContent( '1movedto2', $this->getPrefixedText(), $nt->getPrefixedText() );
                if ( $reason ) {
@@ -2323,13 +2635,12 @@ class Title {
                $oldid = $this->getArticleID();
                $dbw = wfGetDB( DB_MASTER );
                $now = $dbw->timestamp();
-               $linkCache =& LinkCache::singleton();
 
                # Save a null revision in the page's history notifying of the move
                $nullRevision = Revision::newNullRevision( $dbw, $oldid, $comment, true );
                $nullRevId = $nullRevision->insertOn( $dbw );
 
-               # Rename cur entry
+               # Rename page entry
                $dbw->update( 'page',
                        /* SET */ array(
                                'page_touched'   => $now,
@@ -2340,21 +2651,32 @@ class Title {
                        /* WHERE */ array( 'page_id' => $oldid ),
                        $fname
                );
+               $nt->resetArticleID( $oldid );
 
-               $linkCache->clearLink( $nt->getPrefixedDBkey() );
-
-               # Insert redirect
-               $mwRedir = MagicWord::get( 'redirect' );
-               $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
-               $redirectArticle = new Article( $this );
-               $newid = $redirectArticle->insertOn( $dbw );
-               $redirectRevision = new Revision( array(
-                       'page'    => $newid,
-                       'comment' => $comment,
-                       'text'    => $redirectText ) );
-               $redirectRevision->insertOn( $dbw );
-               $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
-               $linkCache->clearLink( $this->getPrefixedDBkey() );
+               if($createRedirect || !$wgUser->isAllowed('suppressredirect'))
+               {
+                       # Insert redirect
+                       $mwRedir = MagicWord::get( 'redirect' );
+                       $redirectText = $mwRedir->getSynonym( 0 ) . ' [[' . $nt->getPrefixedText() . "]]\n";
+                       $redirectArticle = new Article( $this );
+                       $newid = $redirectArticle->insertOn( $dbw );
+                       $redirectRevision = new Revision( array(
+                               'page'    => $newid,
+                               'comment' => $comment,
+                               'text'    => $redirectText ) );
+                       $redirectRevision->insertOn( $dbw );
+                       $redirectArticle->updateRevisionOn( $dbw, $redirectRevision, 0 );
+
+                       # Record the just-created redirect's linking to the page
+                       $dbw->insert( 'pagelinks',
+                               array(
+                                       'pl_from'      => $newid,
+                                       'pl_namespace' => $nt->getNamespace(),
+                                       'pl_title'     => $nt->getDBkey() ),
+                               $fname );
+               } else {
+                       $this->resetArticleID( 0 );
+               }
 
                # Log the move
                $log = new LogPage( 'move' );
@@ -2363,14 +2685,6 @@ class Title {
                # Purge caches as per article creation
                Article::onArticleCreate( $nt );
 
-               # Record the just-created redirect's linking to the page
-               $dbw->insert( 'pagelinks',
-                       array(
-                               'pl_from'      => $newid,
-                               'pl_namespace' => $nt->getNamespace(),
-                               'pl_title'     => $nt->getDBkey() ),
-                       $fname );
-
                # Purge old title from squid
                # The new title, and links to the new title, are purged in Article::onArticleCreate()
                $this->purgeSquid();
@@ -2430,7 +2744,7 @@ class Title {
                # Return true if there was no history
                return $row === false;
        }
-       
+
        /**
         * Can this title be added to a user's watchlist?
         *
@@ -2438,7 +2752,7 @@ class Title {
         */
        public function isWatchable() {
                return !$this->isExternal()
-                       && Namespace::isWatchable( $this->getNamespace() );
+                       && MWNamespace::isWatchable( $this->getNamespace() );
        }
 
        /**
@@ -2469,7 +2783,7 @@ class Title {
                                $data[$wgContLang->getNSText ( NS_CATEGORY ).':'.$x->cl_to] = $this->getFullText();
                        $dbr->freeResult ( $res ) ;
                } else {
-                       $data = '';
+                       $data = array();
                }
                return $data;
        }
@@ -2480,6 +2794,7 @@ class Title {
         * @return array
         */
        public function getParentCategoryTree( $children = array() ) {
+               $stack = array();
                $parents = $this->getParentCategories();
 
                if($parents != '') {
@@ -2539,6 +2854,7 @@ class Title {
 
        /**
         * Get the number of revisions between the given revision IDs.
+        * Used for diffs and other things that really need it.
         *
         * @param integer $old  Revision ID.
         * @param integer $new  Revision ID.
@@ -2549,7 +2865,9 @@ class Title {
                return $dbr->selectField( 'revision', 'count(*)',
                        'rev_page = ' . intval( $this->getArticleId() ) .
                        ' AND rev_id > ' . intval( $old ) .
-                       ' AND rev_id < ' . intval( $new ) );
+                       ' AND rev_id < ' . intval( $new ),
+                       __METHOD__,
+                       array( 'USE INDEX' => 'PRIMARY' ) );
        }
 
        /**
@@ -2562,9 +2880,9 @@ class Title {
                // Note: === is necessary for proper matching of number-like titles.
                return $this->getInterwiki() === $title->getInterwiki()
                        && $this->getNamespace() == $title->getNamespace()
-                       && $this->getDbkey() === $title->getDbkey();
+                       && $this->getDBkey() === $title->getDBkey();
        }
-       
+
        /**
         * Return a string representation of this title
         *
@@ -2589,14 +2907,20 @@ class Title {
         * @return bool
         */
        public function isAlwaysKnown() {
+               // If the page is form Mediawiki:message/lang, calling wfMsgWeirdKey causes
+               // the full l10n of that language to be loaded. That takes much memory and
+               // isn't needed. So we strip the language part away.
+               // Also, extension messages which are not loaded, are shown as red, because
+               // we don't call MessageCache::loadAllMessages.
+               list( $basename, /* rest */ ) = explode( '/', $this->mDbkeyform, 2 );
                return $this->isExternal()
                        || ( $this->mNamespace == NS_MAIN && $this->mDbkeyform == '' )
-                       || ( $this->mNamespace == NS_MEDIAWIKI && wfMsgWeirdKey( $this->mDbkeyform ) );
+                       || ( $this->mNamespace == NS_MEDIAWIKI && wfMsgWeirdKey( $basename ) );
        }
 
        /**
         * Update page_touched timestamps and send squid purge messages for
-        * pages linking to this title. May be sent to the job queue depending 
+        * pages linking to this title. May be sent to the job queue depending
         * on the number of links. Typically called on create and delete.
         */
        public function touchLinks() {
@@ -2615,7 +2939,7 @@ class Title {
        public function getTouched() {
                $dbr = wfGetDB( DB_SLAVE );
                $touched = $dbr->selectField( 'page', 'page_touched',
-                       array( 
+                       array(
                                'page_namespace' => $this->getNamespace(),
                                'page_title' => $this->getDBkey()
                        ), __METHOD__
@@ -2635,7 +2959,12 @@ class Title {
                $title = htmlspecialchars($this->getText());
                $tburl = $this->trackbackURL();
 
-               return "
+               // Autodiscovery RDF is placed in comments so HTML validator
+               // won't barf. This is a rather icky workaround, but seems
+               // frequently used by this kind of RDF thingy.
+               //
+               // Spec: http://www.sixapart.com/pronet/docs/trackback_spec
+               return "<!--
 <rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"
          xmlns:dc=\"http://purl.org/dc/elements/1.1/\"
          xmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">
@@ -2644,7 +2973,8 @@ class Title {
    dc:identifier=\"$url\"
    dc:title=\"$title\"
    trackback:ping=\"$tburl\" />
-</rdf:RDF>";
+</rdf:RDF>
+-->";
        }
 
        /**
@@ -2702,7 +3032,7 @@ class Title {
        }
 
        /**
-        * If the Title refers to a special page alias which is not the local default, 
+        * If the Title refers to a special page alias which is not the local default,
         * returns a new Title which points to the local default. Otherwise, returns $this.
         */
        public function fixSpecialName() {
@@ -2726,9 +3056,18 @@ class Title {
         * @return bool
         */
        public function isContentPage() {
-               return Namespace::isContent( $this->getNamespace() );
+               return MWNamespace::isContent( $this->getNamespace() );
        }
-       
-}
-
 
+       public function getRedirectsHere() {
+               $redirs = array();
+               $dbr = wfGetDB( DB_SLAVE );
+               list($page,$redirect) = $dbr->tableNamesN( 'page', 'redirect' );
+               $result = $dbr->query( "SELECT page_title, page_namespace FROM $page JOIN $redirect ON page_id = rd_from WHERE rd_title = "
+                       . $dbr->addQuotes( $this->getDBKey() ) . " AND rd_namespace = " . $this->getNamespace(), __METHOD__ );
+               while( $row = $dbr->fetchObject( $result ) ) {
+                       $redirs[] = self::newFromRow( $row );
+               }
+               return $redirs;
+       }
+}