* Do fewer unnecessary full writes of user rows; only update user_touched
[lhc/web/wiklou.git] / includes / User.php
index 97dd155..7dc4689 100644 (file)
  * @package MediaWiki
  */
 
-/**
- *
- */
-require_once( 'WatchedItem.php' );
-
 # Number of characters in user_token field
 define( 'USER_TOKEN_LENGTH', 32 );
 
 # Serialized record version
-define( 'MW_USER_VERSION', 2 );
+define( 'MW_USER_VERSION', 3 );
 
 /**
  *
  * @package MediaWiki
  */
 class User {
-       /**#@+
-        * @access private
-        */
-       var $mId, $mName, $mPassword, $mEmail, $mNewtalk;
-       var $mEmailAuthenticated;
-       var $mRights, $mOptions;
-       var $mDataLoaded, $mNewpassword;
-       var $mSkin;
-       var $mBlockedby, $mBlockreason;
-       var $mTouched;
-       var $mToken;
-       var $mRealName;
-       var $mHash;
-       var $mGroups;
-       var $mVersion; // serialized version
-
-       /** Construct using User:loadDefaults() */
+       /*
+        * When adding a new private variable, dont forget to add it to __sleep()
+        */
+       /**@{{
+        * @private
+        */
+       var $mBlockedby;        //!<
+       var $mBlockreason;      //!<
+       var $mBlock;        //!<
+       var $mDataLoaded;       //!<
+       var $mEmail;            //!<
+       var $mEmailAuthenticated; //!<
+       var $mGroups;           //!<
+       var $mHash;                     //!<
+       var $mId;                       //!<
+       var $mName;                     //!<
+       var $mNewpassword;      //!<
+       var $mNewtalk;          //!<
+       var $mOptions;          //!<
+       var $mPassword;         //!<
+       var $mRealName;         //!<
+       var $mRegistration;     //!<
+       var $mRights;           //!<
+       var $mSkin;                     //!<
+       var $mToken;            //!<
+       var $mTouched;          //!<
+       var $mDatePreference; // !<
+       var $mVersion;          //!< serialized version
+       /**@}} */
+
+       /**
+        * Default user options
+        * To change this array at runtime, use a UserDefaultOptions hook
+        */
+       static public $mDefaultOptions = array( 
+               'quickbar'              => 1,
+               'underline'             => 2,
+               'cols'                  => 80,
+               'rows'                  => 25,
+               'searchlimit'           => 20,
+               'contextlines'          => 5,
+               'contextchars'          => 50,
+               'skin'                  => false,
+               'math'                  => 1,
+               'rcdays'                => 7,
+               'rclimit'               => 50,
+               'wllimit'               => 250,
+               'highlightbroken'       => 1,
+               'stubthreshold'         => 0,
+               'previewontop'          => 1,
+               'editsection'           => 1,
+               'editsectiononrightclick'=> 0,
+               'showtoc'               => 1,
+               'showtoolbar'           => 1,
+               'date'                  => 'default',
+               'imagesize'             => 2,
+               'thumbsize'             => 2,
+               'rememberpassword'      => 0,
+               'enotifwatchlistpages'  => 0,
+               'enotifusertalkpages'   => 1,
+               'enotifminoredits'      => 0,
+               'enotifrevealaddr'      => 0,
+               'shownumberswatching'   => 1,
+               'fancysig'              => 0,
+               'externaleditor'        => 0,
+               'externaldiff'          => 0,
+               'showjumplinks'         => 1,
+               'numberheadings'        => 0,
+               'uselivepreview'        => 0,
+               'watchlistdays'         => 3.0,
+       );
+
+       static public $mToggles = array(
+               'highlightbroken',
+               'justify',
+               'hideminor',
+               'extendwatchlist',
+               'usenewrc',
+               'numberheadings',
+               'showtoolbar',
+               'editondblclick',
+               'editsection',
+               'editsectiononrightclick',
+               'showtoc',
+               'rememberpassword',
+               'editwidth',
+               'watchcreations',
+               'watchdefault',
+               'minordefault',
+               'previewontop',
+               'previewonfirst',
+               'nocache',
+               'enotifwatchlistpages',
+               'enotifusertalkpages',
+               'enotifminoredits',
+               'enotifrevealaddr',
+               'shownumberswatching',
+               'fancysig',
+               'externaleditor',
+               'externaldiff',
+               'showjumplinks',
+               'uselivepreview',
+               'autopatrol',
+               'forceeditsummary',
+               'watchlisthideown',
+               'watchlisthidebots',
+       );              
+
+       /** Constructor using User:loadDefaults() */
        function User() {
                $this->loadDefaults();
                $this->mVersion = MW_USER_VERSION;
@@ -46,10 +133,11 @@ class User {
        /**
         * Static factory method
         * @param string $name Username, validated by Title:newFromText()
+        * @param bool $validate Validate username
         * @return User
         * @static
         */
-       function newFromName( $name ) {
+       function newFromName( $name, $validate = true ) {
                # Force usernames to capital
                global $wgContLang;
                $name = $wgContLang->ucfirst( $name );
@@ -65,7 +153,7 @@ class User {
                global $wgAuth;
                $canonicalName = $wgAuth->getCanonicalName( $t->getText() );
 
-               if( !User::isValidUserName( $canonicalName ) ) {
+               if( $validate && !User::isValidUserName( $canonicalName ) ) {
                        return null;
                }
 
@@ -101,13 +189,29 @@ class User {
 
        /**
         * Serialze sleep function, for better cache efficiency and avoidance of
-        * silly "incomplete type" errors when skins are cached
+        * silly "incomplete type" errors when skins are cached. The array should
+        * contain names of private variables (see at top of User.php).
         */
        function __sleep() {
-               return array( 'mId', 'mName', 'mPassword', 'mEmail', 'mNewtalk',
-                       'mEmailAuthenticated', 'mRights', 'mOptions', 'mDataLoaded',
-                       'mNewpassword', 'mBlockedby', 'mBlockreason', 'mTouched',
-                       'mToken', 'mRealName', 'mHash', 'mGroups' );
+               return array(
+'mDataLoaded',
+'mEmail',
+'mEmailAuthenticated',
+'mGroups',
+'mHash',
+'mId',
+'mName',
+'mNewpassword',
+'mNewtalk',
+'mOptions',
+'mPassword',
+'mRealName',
+'mRegistration',
+'mRights',
+'mToken',
+'mTouched',
+'mVersion',
+);
        }
 
        /**
@@ -157,9 +261,14 @@ class User {
        }
 
        /**
-        * does the string match an anonymous IPv4 address?
+        * Does the string match an anonymous IPv4 address?
         *
-        * Note: We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
+        * This function exists for username validation, in order to reject
+        * usernames which are similar in form to IP addresses. Strings such
+        * as 300.300.300.300 will return true because it looks like an IP 
+        * address, despite not being strictly valid.
+        * 
+        * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
         * address because the usemod software would "cloak" anonymous IP
         * addresses like this, if we allowed accounts like this to be created
         * new users could get the old edits of these anonymous users.
@@ -201,8 +310,72 @@ class User {
                || strlen( $name ) > $wgMaxNameChars
                || $name != $wgContLang->ucfirst( $name ) )
                        return false;
-               else
-                       return true;
+
+               // Ensure that the name can't be misresolved as a different title,
+               // such as with extra namespace keys at the start.
+               $parsed = Title::newFromText( $name );
+               if( is_null( $parsed )
+                       || $parsed->getNamespace()
+                       || strcmp( $name, $parsed->getPrefixedText() ) )
+                       return false;
+               
+               // Check an additional blacklist of troublemaker characters.
+               // Should these be merged into the title char list?
+               $unicodeBlacklist = '/[' .
+                       '\x{0080}-\x{009f}' . # iso-8859-1 control chars
+                       '\x{00a0}' .          # non-breaking space
+                       '\x{2000}-\x{200f}' . # various whitespace
+                       '\x{2028}-\x{202f}' . # breaks and control chars
+                       '\x{3000}' .          # ideographic space
+                       '\x{e000}-\x{f8ff}' . # private use
+                       ']/u';
+               if( preg_match( $unicodeBlacklist, $name ) ) {
+                       return false;
+               }
+               
+               return true;
+       }
+       
+       /**
+        * Usernames which fail to pass this function will be blocked
+        * from user login and new account registrations, but may be used
+        * internally by batch processes.
+        *
+        * If an account already exists in this form, login will be blocked
+        * by a failure to pass this function.
+        *
+        * @param string $name
+        * @return bool
+        */
+       static function isUsableName( $name ) {
+               global $wgReservedUsernames;
+               return
+                       // Must be a usable username, obviously ;)
+                       self::isValidUserName( $name ) &&
+                       
+                       // Certain names may be reserved for batch processes.
+                       !in_array( $name, $wgReservedUsernames );
+       }
+       
+       /**
+        * Usernames which fail to pass this function will be blocked
+        * from new account registrations, but may be used internally
+        * either by batch processes or by user accounts which have
+        * already been created.
+        *
+        * Additional character blacklisting may be added here
+        * rather than in isValidUserName() to avoid disrupting
+        * existing accounts.
+        *
+        * @param string $name
+        * @return bool
+        */
+       static function isCreatableName( $name ) {
+               return
+                       self::isUsableName( $name ) &&
+                       
+                       // Registration-time character blacklisting...
+                       strpos( $name, '@' ) === false;
        }
 
        /**
@@ -260,13 +433,16 @@ class User {
         * @todo Check what is doing really [AV]
         */
        function randomPassword() {
+               global $wgMinimalPasswordLength;
                $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
                $l = strlen( $pwchars ) - 1;
 
-               $np = $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
-                 $pwchars{mt_rand( 0, $l )} . chr( mt_rand(48, 57) ) .
-                 $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
-                 $pwchars{mt_rand( 0, $l )};
+               $pwlength = max( 7, $wgMinimalPasswordLength );
+               $digit = mt_rand(0, $pwlength - 1);
+               $np = '';
+               for ( $i = 0; $i < $pwlength; $i++ ) {
+                       $np .= $i == $digit ? chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
+               }
                return $np;
        }
 
@@ -281,7 +457,7 @@ class User {
                $fname = 'User::loadDefaults' . $n;
                wfProfileIn( $fname );
 
-               global $wgContLang, $wgDBname;
+               global $wgCookiePrefix;
                global $wgNamespacesToBeSearchedDefault;
 
                $this->mId = 0;
@@ -292,24 +468,24 @@ class User {
                $this->mPassword = $this->mNewpassword = '';
                $this->mRights = array();
                $this->mGroups = array();
-               $this->mOptions = User::getDefaultOptions();
+               $this->mOptions = null;
+               $this->mDatePreference = null;
 
-               foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
-                       $this->mOptions['searchNs'.$nsnum] = $val;
-               }
                unset( $this->mSkin );
                $this->mDataLoaded = false;
                $this->mBlockedby = -1; # Unset
                $this->setToken(); # Random
                $this->mHash = false;
 
-               if ( isset( $_COOKIE[$wgDBname.'LoggedOut'] ) ) {
-                       $this->mTouched = wfTimestamp( TS_MW, $_COOKIE[$wgDBname.'LoggedOut'] );
+               if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
+                       $this->mTouched = wfTimestamp( TS_MW, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
                }
                else {
                        $this->mTouched = '0'; # Allow any pages to be cached
                }
 
+               $this->mRegistration = wfTimestamp( TS_MW );
+
                wfProfileOut( $fname );
        }
 
@@ -319,22 +495,26 @@ class User {
         *
         * @return array
         * @static
-        * @access private
+        * @private
         */
        function getDefaultOptions() {
+               global $wgNamespacesToBeSearchedDefault;
                /**
                 * Site defaults will override the global/language defaults
                 */
-               global $wgContLang, $wgDefaultUserOptions;
-               $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptions();
+               global $wgContLang;
+               $defOpt = self::$mDefaultOptions + $wgContLang->getDefaultUserOptionOverrides();
 
                /**
                 * default language setting
                 */
-               $variant = $wgContLang->getPreferredVariant();
+               $variant = $wgContLang->getPreferredVariant( false );
                $defOpt['variant'] = $variant;
                $defOpt['language'] = $variant;
 
+               foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
+                       $defOpt['searchNs'.$nsnum] = $val;
+               }
                return $defOpt;
        }
 
@@ -344,7 +524,7 @@ class User {
         * @param string $opt
         * @return string
         * @static
-        * @access public
+        * @public
         */
        function getDefaultOption( $opt ) {
                $defOpts = User::getDefaultOptions();
@@ -355,20 +535,27 @@ class User {
                }
        }
 
+       /**
+        * Get a list of user toggle names
+        * @return array
+        */
+       static function getToggles() {
+               global $wgContLang;
+               $extraToggles = array();
+               wfRunHooks( 'UserToggles', array( &$extraToggles ) );
+               return array_merge( self::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
+       }
+
+
        /**
         * Get blocking information
-        * @access private
+        * @private
         * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
         *  non-critical checks are done against slaves. Check when actually saving should be done against
         *  master.
-        *
-        * Note that even if $bFromSlave is false, the check is done first against slave, then master.
-        * The logic is that if blocked on slave, we'll assume it's either blocked on master or
-        * just slightly outta sync and soon corrected - safer to block slightly more that less.
-        * And it's cheaper to check slave first, then master if needed, than master always.
         */
        function getBlockedStatus( $bFromSlave = true ) {
-               global $wgBlockCache, $wgProxyList, $wgEnableSorbs, $wgProxyWhitelist;
+               global $wgEnableSorbs, $wgProxyWhitelist;
 
                if ( -1 != $this->mBlockedby ) {
                        wfDebug( "User::getBlockedStatus: already loaded.\n" );
@@ -383,41 +570,25 @@ class User {
                $ip = wfGetIP();
 
                # User/IP blocking
-               $block = new Block();
-               $block->forUpdate( $bFromSlave );
-               if ( $block->load( $ip , $this->mId ) ) {
+               $this->mBlock = new Block();
+               $this->mBlock->fromMaster( !$bFromSlave );
+               if ( $this->mBlock->load( $ip , $this->mId ) ) {
                        wfDebug( "$fname: Found block.\n" );
-                       $this->mBlockedby = $block->mBy;
-                       $this->mBlockreason = $block->mReason;
+                       $this->mBlockedby = $this->mBlock->mBy;
+                       $this->mBlockreason = $this->mBlock->mReason;
                        if ( $this->isLoggedIn() ) {
                                $this->spreadBlock();
                        }
                } else {
+                       $this->mBlock = null;
                        wfDebug( "$fname: No block.\n" );
                }
 
-               # Range blocking
-               if ( !$this->mBlockedby ) {
-                       # Check first against slave, and optionally from master.
-                       wfDebug( "$fname: Checking range blocks\n" );
-                       $block = $wgBlockCache->get( $ip, true );
-                       if ( !$block && !$bFromSlave )
-                               {
-                               # Not blocked: check against master, to make sure.
-                               $wgBlockCache->clearLocal( );
-                               $block = $wgBlockCache->get( $ip, false );
-                               }
-                       if ( $block !== false ) {
-                               $this->mBlockedby = $block->mBy;
-                               $this->mBlockreason = $block->mReason;
-                       }
-               }
-
                # Proxy blocking
-               if ( !$this->isSysop() && !in_array( $ip, $wgProxyWhitelist ) ) {
+               if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
 
                        # Local list
-                       if ( array_key_exists( $ip, $wgProxyList ) ) {
+                       if ( wfIsLocallyBlockedProxy( $ip ) ) {
                                $this->mBlockedby = wfMsg( 'proxyblocker' );
                                $this->mBlockreason = wfMsg( 'proxyblockreason' );
                        }
@@ -443,12 +614,6 @@ class User {
                        $this->inDnsBlacklist( $ip, 'http.dnsbl.sorbs.net.' );
        }
 
-       function inOpmBlacklist( $ip ) {
-               global $wgEnableOpm;
-               return $wgEnableOpm &&
-                       $this->inDnsBlacklist( $ip, 'opm.blitzed.org.' );
-       }
-
        function inDnsBlacklist( $ip, $base ) {
                $fname = 'User::inDnsBlacklist';
                wfProfileIn( $fname );
@@ -486,18 +651,20 @@ class User {
         * last-hit counters will be shared across wikis.
         *
         * @return bool true if a rate limiter was tripped
-        * @access public
+        * @public
         */
        function pingLimiter( $action='edit' ) {
-               global $wgRateLimits;
+               global $wgRateLimits, $wgRateLimitsExcludedGroups;
                if( !isset( $wgRateLimits[$action] ) ) {
                        return false;
                }
-               if( $this->isAllowed( 'delete' ) ) {
-                       // goddam cabal
-                       return false;
+               
+               # Some groups shouldn't trigger the ping limiter, ever
+               foreach( $this->getGroups() as $group ) {
+                       if( array_search( $group, $wgRateLimitsExcludedGroups ) !== false )
+                               return false;
                }
-
+               
                global $wgMemc, $wgDBname, $wgRateLimitLog;
                $fname = 'User::pingLimiter';
                wfProfileIn( $fname );
@@ -605,19 +772,10 @@ class User {
 
        /**
         * Initialise php session
+        * @deprecated use wfSetupSession()
         */
        function SetupSession() {
-               global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
-               if( $wgSessionsInMemcached ) {
-                       require_once( 'MemcachedSessions.php' );
-               } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
-                       # If it's left on 'user' or another setting from another
-                       # application, it will end up failing. Try to recover.
-                       ini_set ( 'session.save_handler', 'files' );
-               }
-               session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
-               session_cache_limiter( 'private, must-revalidate' );
-               @session_start();
+               wfSetupSession();
        }
 
        /**
@@ -625,7 +783,7 @@ class User {
         * @static
         */
        function loadFromSession() {
-               global $wgMemc, $wgDBname;
+               global $wgMemc, $wgDBname, $wgCookiePrefix;
 
                if ( isset( $_SESSION['wsUserID'] ) ) {
                        if ( 0 != $_SESSION['wsUserID'] ) {
@@ -633,16 +791,16 @@ class User {
                        } else {
                                return new User();
                        }
-               } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
-                       $sId = intval( $_COOKIE["{$wgDBname}UserID"] );
+               } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
+                       $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
                        $_SESSION['wsUserID'] = $sId;
                } else {
                        return new User();
                }
                if ( isset( $_SESSION['wsUserName'] ) ) {
                        $sName = $_SESSION['wsUserName'];
-               } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
-                       $sName = $_COOKIE["{$wgDBname}UserName"];
+               } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
+                       $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
                        $_SESSION['wsUserName'] = $sName;
                } else {
                        return new User();
@@ -661,12 +819,14 @@ class User {
                        $user->loadFromDatabase();
                } else {
                        wfDebug( "User::loadFromSession() got from cache!\n" );
+                       # Set block status to unloaded, that should be loaded every time
+                       $user->mBlockedby = -1;
                }
 
                if ( isset( $_SESSION['wsToken'] ) ) {
                        $passwordCorrect = $_SESSION['wsToken'] == $user->mToken;
-               } else if ( isset( $_COOKIE["{$wgDBname}Token"] ) ) {
-                       $passwordCorrect = $user->mToken == $_COOKIE["{$wgDBname}Token"];
+               } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
+                       $passwordCorrect = $user->mToken == $_COOKIE["{$wgCookiePrefix}Token"];
                } else {
                        return new User(); # Can't log in from session
                }
@@ -687,7 +847,6 @@ class User {
         * Load a user from the database
         */
        function loadFromDatabase() {
-               global $wgCommandLineMode;
                $fname = "User::loadFromDatabase";
 
                # Counter-intuitive, breaks various things, use User::setLoaded() if you want to suppress
@@ -711,7 +870,7 @@ class User {
                $dbr =& wfGetDB( DB_SLAVE );
                $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
                  'user_email_authenticated',
-                 'user_real_name','user_options','user_touched', 'user_token' ),
+                 'user_real_name','user_options','user_touched', 'user_token', 'user_registration' ),
                  array( 'user_id' => $this->mId ), $fname );
 
                if ( $s !== false ) {
@@ -724,6 +883,7 @@ class User {
                        $this->decodeOptions( $s->user_options );
                        $this->mTouched = wfTimestamp(TS_MW,$s->user_touched);
                        $this->mToken = $s->user_token;
+                       $this->mRegistration = wfTimestampOrNull( TS_MW, $s->user_registration );
 
                        $res = $dbr->select( 'user_groups',
                                array( 'ug_group' ),
@@ -733,7 +893,26 @@ class User {
                        while( $row = $dbr->fetchObject( $res ) ) {
                                $this->mGroups[] = $row->ug_group;
                        }
-                       $effectiveGroups = array_merge( array( '*', 'user' ), $this->mGroups );
+                       $implicitGroups = array( '*', 'user' );
+
+                       global $wgAutoConfirmAge;
+                       $accountAge = time() - wfTimestampOrNull( TS_UNIX, $this->mRegistration );
+                       if( $accountAge >= $wgAutoConfirmAge ) {
+                               $implicitGroups[] = 'autoconfirmed';
+                       }
+                       
+                       # Implicit group for users whose email addresses are confirmed
+                       global $wgEmailAuthentication;
+                       if( $this->isValidEmailAddr( $this->mEmail ) ) {
+                               if( $wgEmailAuthentication ) {
+                                       if( $this->mEmailAuthenticated )
+                                               $implicitGroups[] = 'emailconfirmed';
+                               } else {
+                                       $implicitGroups[] = 'emailconfirmed';
+                               }
+                       }
+
+                       $effectiveGroups = array_merge( $implicitGroups, $this->mGroups );
                        $this->mRights = $this->getGroupPermissions( $effectiveGroups );
                }
 
@@ -763,20 +942,18 @@ class User {
        /**
         * Return the title dbkey form of the name, for eg user pages.
         * @return string
-        * @access public
+        * @public
         */
        function getTitleKey() {
                return str_replace( ' ', '_', $this->getName() );
        }
 
        function getNewtalk() {
-               global $wgUseEnotif;
-               $fname = 'User::getNewtalk';
                $this->loadFromDatabase();
 
                # Load the newtalk status if it is unloaded (mNewtalk=-1)
-               if( $this->mNewtalk == -1 ) {
-                       $this->mNewtalk = 0; # reset talk page status
+               if( $this->mNewtalk === -1 ) {
+                       $this->mNewtalk = false; # reset talk page status
 
                        # Check memcached separately for anons, who have no
                        # entire User object stored in there.
@@ -785,57 +962,181 @@ class User {
                                $key = "$wgDBname:newtalk:ip:" . $this->getName();
                                $newtalk = $wgMemc->get( $key );
                                if( is_integer( $newtalk ) ) {
-                                       $this->mNewtalk = $newtalk ? 1 : 0;
-                                       return (bool)$this->mNewtalk;
+                                       $this->mNewtalk = (bool)$newtalk;
+                               } else {
+                                       $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName() );
+                                       $wgMemc->set( $key, $this->mNewtalk, time() ); // + 1800 );
                                }
+                       } else {
+                               $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
                        }
+               }
 
-                       $dbr =& wfGetDB( DB_SLAVE );
-                       if ( $wgUseEnotif ) {
-                               $res = $dbr->select( 'watchlist',
-                                       array( 'wl_user' ),
-                                       array( 'wl_title'     => $this->getTitleKey(),
-                                                  'wl_namespace' => NS_USER_TALK,
-                                                  'wl_user'      => $this->mId,
-                                                  'wl_notificationtimestamp ' . $dbr->notNullTimestamp() ),
-                                       'User::getNewtalk' );
-                               if( $dbr->numRows($res) > 0 ) {
-                                       $this->mNewtalk = 1;
-                               }
-                               $dbr->freeResult( $res );
-                       } elseif ( $this->mId ) {
-                               $res = $dbr->select( 'user_newtalk', 1, array( 'user_id' => $this->mId ), $fname );
+               return (bool)$this->mNewtalk;
+       }
 
-                               if ( $dbr->numRows($res)>0 ) {
-                                       $this->mNewtalk= 1;
-                               }
-                               $dbr->freeResult( $res );
-                       } else {
-                               $res = $dbr->select( 'user_newtalk', 1, array( 'user_ip' => $this->getName() ), $fname );
-                               $this->mNewtalk = $dbr->numRows( $res ) > 0 ? 1 : 0;
-                               $dbr->freeResult( $res );
-                       }
+       /**
+        * Return the talk page(s) this user has new messages on.
+        */
+       function getNewMessageLinks() {
+       global  $wgDBname;
+               $talks = array();
+               if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
+                       return $talks;
 
-                       if( !$this->mId ) {
-                               $wgMemc->set( $key, $this->mNewtalk, time() ); // + 1800 );
-                       }
+               if (!$this->getNewtalk())
+                       return array();
+               $up = $this->getUserPage();
+               $utp = $up->getTalkPage();
+               return array(array("wiki" => $wgDBname, "link" => $utp->getLocalURL()));
+       }
+
+               
+       /**
+        * Perform a user_newtalk check on current slaves; if the memcached data
+        * is funky we don't want newtalk state to get stuck on save, as that's
+        * damn annoying.
+        *
+        * @param string $field
+        * @param mixed $id
+        * @return bool
+        * @private
+        */
+       function checkNewtalk( $field, $id ) {
+               $fname = 'User::checkNewtalk';
+               $dbr =& wfGetDB( DB_SLAVE );
+               $ok = $dbr->selectField( 'user_newtalk', $field,
+                       array( $field => $id ), $fname );
+               return $ok !== false;
+       }
+
+       /**
+        * Add or update the
+        * @param string $field
+        * @param mixed $id
+        * @private
+        */
+       function updateNewtalk( $field, $id ) {
+               $fname = 'User::updateNewtalk';
+               if( $this->checkNewtalk( $field, $id ) ) {
+                       wfDebug( "$fname already set ($field, $id), ignoring\n" );
+                       return false;
                }
+               $dbw =& wfGetDB( DB_MASTER );
+               $dbw->insert( 'user_newtalk',
+                       array( $field => $id ),
+                       $fname,
+                       'IGNORE' );
+               wfDebug( "$fname: set on ($field, $id)\n" );
+               return true;
+       }
 
-               return ( 0 != $this->mNewtalk );
+       /**
+        * Clear the new messages flag for the given user
+        * @param string $field
+        * @param mixed $id
+        * @private
+        */
+       function deleteNewtalk( $field, $id ) {
+               $fname = 'User::deleteNewtalk';
+               if( !$this->checkNewtalk( $field, $id ) ) {
+                       wfDebug( "$fname: already gone ($field, $id), ignoring\n" );
+                       return false;
+               }
+               $dbw =& wfGetDB( DB_MASTER );
+               $dbw->delete( 'user_newtalk',
+                       array( $field => $id ),
+                       $fname );
+               wfDebug( "$fname: killed on ($field, $id)\n" );
+               return true;
        }
 
+       /**
+        * Update the 'You have new messages!' status.
+        * @param bool $val
+        */
        function setNewtalk( $val ) {
+               if( wfReadOnly() ) {
+                       return;
+               }
+
                $this->loadFromDatabase();
                $this->mNewtalk = $val;
-               $this->invalidateCache();
+
+               $fname = 'User::setNewtalk';
+
+               if( $this->isAnon() ) {
+                       $field = 'user_ip';
+                       $id = $this->getName();
+               } else {
+                       $field = 'user_id';
+                       $id = $this->getId();
+               }
+
+               if( $val ) {
+                       $changed = $this->updateNewtalk( $field, $id );
+               } else {
+                       $changed = $this->deleteNewtalk( $field, $id );
+               }
+
+               if( $changed ) {
+                       if( $this->isAnon() ) {
+                               // Anons have a separate memcached space, since
+                               // user records aren't kept for them.
+                               global $wgDBname, $wgMemc;
+                               $key = "$wgDBname:newtalk:ip:$val";
+                               $wgMemc->set( $key, $val ? 1 : 0 );
+                       } else {
+                               if( $val ) {
+                                       // Make sure the user page is watched, so a notification
+                                       // will be sent out if enabled.
+                                       $this->addWatch( $this->getTalkPage() );
+                               }
+                       }
+                       $this->invalidateCache();
+               }
+       }
+       
+       /**
+        * Generate a current or new-future timestamp to be stored in the
+        * user_touched field when we update things.
+        */
+       private static function newTouchedTimestamp() {
+               global $wgClockSkewFudge;
+               return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
+       }
+       
+       /**
+        * Clear user data from memcached.
+        * Use after applying fun updates to the database; caller's
+        * responsibility to update user_touched if appropriate.
+        *
+        * Called implicitly from invalidateCache() and saveSettings().
+        */
+       private function clearUserCache() {
+               if( $this->mId ) {
+                       global $wgMemc, $wgDBname;
+                       $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
+               }
        }
 
+       /**
+        * Immediately touch the user data cache for this account.
+        * Updates user_touched field, and removes account data from memcached
+        * for reload on the next hit.
+        */
        function invalidateCache() {
-               global $wgClockSkewFudge;
-               $this->loadFromDatabase();
-               $this->mTouched = wfTimestamp(TS_MW, time() + $wgClockSkewFudge );
-               # Don't forget to save the options after this or
-               # it won't take effect!
+               if( $this->mId ) {
+                       $this->mTouched = self::newTouchedTimestamp();
+                       
+                       $dbw =& wfGetDB( DB_MASTER );
+                       $dbw->update( 'user',
+                               array( 'user_touched' => $dbw->timestamp( $this->mTouched ) ),
+                               array( 'user_id' => $this->mId ),
+                               __METHOD__ );
+                       
+                       $this->clearUserCache();
+               }
        }
 
        function validateCache( $timestamp ) {
@@ -914,8 +1215,15 @@ class User {
                $this->mRealName = $str;
        }
 
+       /**
+        * @param string $oname The option to check
+        * @return string
+        */
        function getOption( $oname ) {
                $this->loadFromDatabase();
+               if ( is_null( $this->mOptions ) ) {
+                       $this->mOptions = User::getDefaultOptions();
+               }
                if ( array_key_exists( $oname, $this->mOptions ) ) {
                        return trim( $this->mOptions[$oname] );
                } else {
@@ -923,14 +1231,60 @@ class User {
                }
        }
 
+       /**
+        * Get the user's date preference, including some important migration for 
+        * old user rows.
+        */
+       function getDatePreference() {
+               if ( is_null( $this->mDatePreference ) ) {
+                       global $wgLang;
+                       $value = $this->getOption( 'date' );
+                       $map = $wgLang->getDatePreferenceMigrationMap();
+                       if ( isset( $map[$value] ) ) {
+                               $value = $map[$value];
+                       }
+                       $this->mDatePreference = $value;
+               }
+               return $this->mDatePreference;
+       }
+
+       /**
+        * @param string $oname The option to check
+        * @return bool False if the option is not selected, true if it is
+        */
+       function getBoolOption( $oname ) {
+               return (bool)$this->getOption( $oname );
+       }
+       
+       /**
+        * Get an option as an integer value from the source string.
+        * @param string $oname The option to check
+        * @param int $default Optional value to return if option is unset/blank.
+        * @return int
+        */
+       function getIntOption( $oname, $default=0 ) {
+               $val = $this->getOption( $oname );
+               if( $val == '' ) {
+                       $val = $default;
+               }
+               return intval( $val );
+       }
+
        function setOption( $oname, $val ) {
                $this->loadFromDatabase();
+               if ( is_null( $this->mOptions ) ) {
+                       $this->mOptions = User::getDefaultOptions();
+               }
                if ( $oname == 'skin' ) {
                        # Clear cached skin, so the new one displays immediately in Special:Preferences
                        unset( $this->mSkin );
                }
+               // Filter out any newlines that may have passed through input validation.
+               // Newlines are used to separate items in the options blob.
+               $val = str_replace( "\r\n", "\n", $val );
+               $val = str_replace( "\r", "\n", $val );
+               $val = str_replace( "\n", " ", $val );
                $this->mOptions[$oname] = $val;
-               $this->invalidateCache();
        }
 
        function getRights() {
@@ -963,7 +1317,7 @@ class User {
        }
 
        /**
-        * Remove the user from the given group.
+        * Add the user to the given group.
         * This takes immediate effect.
         * @string $group
         */
@@ -981,7 +1335,6 @@ class User {
                $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups() );
 
                $this->invalidateCache();
-               $this->saveSettings();
        }
 
        /**
@@ -1002,7 +1355,6 @@ class User {
                $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups() );
 
                $this->invalidateCache();
-               $this->saveSettings();
        }
 
 
@@ -1026,40 +1378,24 @@ class User {
                return !$this->isLoggedIn();
        }
 
-       /**
-        * Check if a user is sysop
-        * Die with backtrace. Use User:isAllowed() instead.
-        * @deprecated
-        */
-       function isSysop() {
-               return $this->isAllowed( 'protect' );
-       }
-
-       /** @deprecated */
-       function isDeveloper() {
-               return $this->isAllowed( 'siteadmin' );
-       }
-
-       /** @deprecated */
-       function isBureaucrat() {
-               return $this->isAllowed( 'makesysop' );
-       }
-
        /**
         * Whether the user is a bot
-        * @todo need to be migrated to the new user level management sytem
+        * @deprecated
         */
        function isBot() {
-               $this->loadFromDatabase();
-               return in_array( 'bot', $this->mRights );
+               return $this->isAllowed( 'bot' );
        }
 
        /**
         * Check if user is allowed to access a feature / make an action
-        * @param string $action Action to be checked (see $wgAvailableRights in Defines.php for possible actions).
+        * @param string $action Action to be checked
         * @return boolean True: action is allowed, False: action should not be allowed
         */
        function isAllowed($action='') {
+               if ( $action === '' )
+                       // In the spirit of DWIM
+                       return true;
+
                $this->loadFromDatabase();
                return in_array( $action , $this->mRights );
        }
@@ -1074,51 +1410,11 @@ class User {
                        $fname = 'User::getSkin';
                        wfProfileIn( $fname );
 
-                       # get all skin names available
-                       $skinNames = Skin::getSkinNames();
-
                        # get the user skin
                        $userSkin = $this->getOption( 'skin' );
-                       $userSkin = $wgRequest->getText('useskin', $userSkin);
-                       if ( $userSkin == '' ) { $userSkin = 'standard'; }
-
-                       if ( !isset( $skinNames[$userSkin] ) ) {
-                               # in case the user skin could not be found find a replacement
-                               $fallback = array(
-                                       0 => 'Standard',
-                                       1 => 'Nostalgia',
-                                       2 => 'CologneBlue');
-                               # if phptal is enabled we should have monobook skin that
-                               # superseed the good old SkinStandard.
-                               if ( isset( $skinNames['monobook'] ) ) {
-                                       $fallback[0] = 'MonoBook';
-                               }
-
-                               if(is_numeric($userSkin) && isset( $fallback[$userSkin]) ){
-                                       $sn = $fallback[$userSkin];
-                               } else {
-                                       $sn = 'Standard';
-                               }
-                       } else {
-                               # The user skin is available
-                               $sn = $skinNames[$userSkin];
-                       }
+                       $userSkin = $wgRequest->getVal('useskin', $userSkin);
 
-                       # Grab the skin class and initialise it. Each skin checks for PHPTal
-                       # and will not load if it's not enabled.
-                       require_once( $IP.'/skins/'.$sn.'.php' );
-
-                       # Check if we got if not failback to default skin
-                       $className = 'Skin'.$sn;
-                       if( !class_exists( $className ) ) {
-                               # DO NOT die if the class isn't found. This breaks maintenance
-                               # scripts and can cause a user account to be unrecoverable
-                               # except by SQL manipulation if a previously valid skin name
-                               # is no longer valid.
-                               $className = 'SkinStandard';
-                               require_once( $IP.'/skins/Standard.php' );
-                       }
-                       $this->mSkin =& new $className;
+                       $this->mSkin =& Skin::newFromKey( $userSkin );
                        wfProfileOut( $fname );
                }
                return $this->mSkin;
@@ -1163,12 +1459,20 @@ class User {
        function clearNotification( &$title ) {
                global $wgUser, $wgUseEnotif;
 
-               if ( !$wgUseEnotif ) {
+
+               if ($title->getNamespace() == NS_USER_TALK &&
+                       $title->getText() == $this->getName() ) {
+                       if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
+                               return;
+                       $this->setNewtalk( false );
+               }
+
+               if( !$wgUseEnotif ) {
                        return;
                }
 
-               $userid = $this->getID();
-               if ($userid==0) {
+               if( $this->isAnon() ) {
+                       // Nothing else to do...
                        return;
                }
 
@@ -1210,11 +1514,12 @@ class User {
         * the next change of any watched page.
         *
         * @param int $currentUser user ID number
-        * @access public
+        * @public
         */
        function clearAllNotifications( $currentUser ) {
                global $wgUseEnotif;
                if ( !$wgUseEnotif ) {
+                       $this->setNewtalk( false );
                        return;
                }
                if( $currentUser != 0 )  {
@@ -1222,7 +1527,7 @@ class User {
                        $dbw =& wfGetDB( DB_MASTER );
                        $success = $dbw->update( 'watchlist',
                                array( /* SET */
-                                       'wl_notificationtimestamp' => 0
+                                       'wl_notificationtimestamp' => NULL
                                ), array( /* WHERE */
                                        'wl_user' => $currentUser
                                ), 'UserMailer::clearAll'
@@ -1234,10 +1539,13 @@ class User {
        }
 
        /**
-        * @access private
+        * @private
         * @return string Encoding options
         */
        function encodeOptions() {
+               if ( is_null( $this->mOptions ) ) {
+                       $this->mOptions = User::getDefaultOptions();
+               }
                $a = array();
                foreach ( $this->mOptions as $oname => $oval ) {
                        array_push( $a, $oname.'='.$oval );
@@ -1247,9 +1555,12 @@ class User {
        }
 
        /**
-        * @access private
+        * @private
         */
        function decodeOptions( $str ) {
+               global $wgLang;
+               
+               $this->mOptions = array();
                $a = explode( "\n", $str );
                foreach ( $a as $s ) {
                        if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
@@ -1259,22 +1570,22 @@ class User {
        }
 
        function setCookies() {
-               global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
+               global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
                if ( 0 == $this->mId ) return;
                $this->loadFromDatabase();
                $exp = time() + $wgCookieExpiration;
 
                $_SESSION['wsUserID'] = $this->mId;
-               setcookie( $wgDBname.'UserID', $this->mId, $exp, $wgCookiePath, $wgCookieDomain );
+               setcookie( $wgCookiePrefix.'UserID', $this->mId, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
 
                $_SESSION['wsUserName'] = $this->getName();
-               setcookie( $wgDBname.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain );
+               setcookie( $wgCookiePrefix.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
 
                $_SESSION['wsToken'] = $this->mToken;
                if ( 1 == $this->getOption( 'rememberpassword' ) ) {
-                       setcookie( $wgDBname.'Token', $this->mToken, $exp, $wgCookiePath, $wgCookieDomain );
+                       setcookie( $wgCookiePrefix.'Token', $this->mToken, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
                } else {
-                       setcookie( $wgDBname.'Token', '', time() - 3600 );
+                       setcookie( $wgCookiePrefix.'Token', '', time() - 3600 );
                }
        }
 
@@ -1283,29 +1594,30 @@ class User {
         * It will clean the session cookie
         */
        function logout() {
-               global $wgCookiePath, $wgCookieDomain, $wgDBname;
+               global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
                $this->loadDefaults();
                $this->setLoaded( true );
 
                $_SESSION['wsUserID'] = 0;
 
-               setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
-               setcookie( $wgDBname.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
+               setcookie( $wgCookiePrefix.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
+               setcookie( $wgCookiePrefix.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
 
                # Remember when user logged out, to prevent seeing cached pages
-               setcookie( $wgDBname.'LoggedOut', wfTimestampNow(), time() + 86400, $wgCookiePath, $wgCookieDomain );
+               setcookie( $wgCookiePrefix.'LoggedOut', wfTimestampNow(), time() + 86400, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
        }
 
        /**
         * Save object settings into database
+        * @fixme Only rarely do all these fields need to be set!
         */
        function saveSettings() {
-               global $wgMemc, $wgDBname, $wgUseEnotif;
                $fname = 'User::saveSettings';
 
                if ( wfReadOnly() ) { return; }
-               $this->saveNewtalk();
                if ( 0 == $this->mId ) { return; }
+               
+               $this->mTouched = self::newTouchedTimestamp();
 
                $dbw =& wfGetDB( DB_MASTER );
                $dbw->update( 'user',
@@ -1323,82 +1635,9 @@ class User {
                                'user_id' => $this->mId
                        ), $fname
                );
-               $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
+               $this->clearUserCache();
        }
 
-       /**
-        * Save value of new talk flag.
-        */
-       function saveNewtalk() {
-               global $wgDBname, $wgMemc, $wgUseEnotif;
-
-               $fname = 'User::saveNewtalk';
-
-               $changed = false;
-
-               if ( wfReadOnly() ) { return ; }
-               $dbr =& wfGetDB( DB_SLAVE );
-               $dbw =& wfGetDB( DB_MASTER );
-               $changed = false;
-               if ( $wgUseEnotif ) {
-                       if ( ! $this->getNewtalk() ) {
-                               # Delete the watchlist entry for user_talk page X watched by user X
-                               $dbw->delete( 'watchlist',
-                                       array( 'wl_user'      => $this->mId,
-                                                  'wl_title'     => $this->getTitleKey(),
-                                                  'wl_namespace' => NS_USER_TALK ),
-                                       $fname );
-                               if ( $dbw->affectedRows() ) {
-                                       $changed = true;
-                               }
-                               if( !$this->mId ) {
-                                       # Anon users have a separate memcache space for newtalk
-                                       # since they don't store their own info. Trim...
-                                       $wgMemc->delete( "$wgDBname:newtalk:ip:" . $this->getName() );
-                               }
-                       }
-               } else {
-                       if ($this->getID() != 0) {
-                               $field = 'user_id';
-                               $value = $this->getID();
-                               $key = false;
-                       } else {
-                               $field = 'user_ip';
-                               $value = $this->getName();
-                               $key = "$wgDBname:newtalk:ip:$value";
-                       }
-
-                       $dbr =& wfGetDB( DB_SLAVE );
-                       $dbw =& wfGetDB( DB_MASTER );
-
-                       $res = $dbr->selectField('user_newtalk', $field,
-                                                                        array($field => $value), $fname);
-
-                       $changed = true;
-                       if ($res !== false && $this->mNewtalk == 0) {
-                               $dbw->delete('user_newtalk', array($field => $value), $fname);
-                               if ( $key ) {
-                                       $wgMemc->set( $key, 0 );
-                               }
-                       } else if ($res === false && $this->mNewtalk == 1) {
-                               $dbw->insert('user_newtalk', array($field => $value), $fname);
-                               if ( $key ) {
-                                       $wgMemc->set( $key, 1 );
-                               }
-                       } else {
-                               $changed = false;
-                       }
-               }
-
-               # Update user_touched, so that newtalk notifications in the client cache are invalidated
-               if ( $changed && $this->getID() ) {
-                       $dbw->update('user',
-                               /*SET*/ array( 'user_touched' => $this->mTouched ),
-                               /*WHERE*/ array( 'user_id' => $this->getID() ),
-                               $fname);
-                       $wgMemc->set( "$wgDBname:user:id:{$this->mId}", $this, 86400 );
-               }
-       }
 
        /**
         * Checks if a user with the given name exists, returns the ID
@@ -1435,7 +1674,8 @@ class User {
                                'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
                                'user_real_name' => $this->mRealName,
                                'user_options' => $this->encodeOptions(),
-                               'user_token' => $this->mToken
+                               'user_token' => $this->mToken,
+                               'user_registration' => $dbw->timestamp( $this->mRegistration ),
                        ), $fname
                );
                $this->mId = $dbw->insertId();
@@ -1452,13 +1692,13 @@ class User {
                }
 
                $userblock = Block::newFromDB( '', $this->mId );
-               if ( !$userblock->isValid() ) {
+               if ( !$userblock ) {
                        return;
                }
 
                # Check if this IP address is already blocked
                $ipblock = Block::newFromDB( wfGetIP() );
-               if ( $ipblock->isValid() ) {
+               if ( $ipblock ) {
                        # If the user is already blocked. Then check if the autoblock would
                        # excede the user block. If it would excede, then do nothing, else
                        # prolong block time
@@ -1469,6 +1709,8 @@ class User {
                        # Just update the timestamp
                        $ipblock->updateTimestamp();
                        return;
+               } else {
+                       $ipblock = new Block;
                }
 
                # Make a new block object with the desired properties
@@ -1492,8 +1734,21 @@ class User {
 
        }
 
+       /**
+        * Generate a string which will be different for any combination of
+        * user options which would produce different parser output.
+        * This will be used as part of the hash key for the parser cache,
+        * so users will the same options can share the same cached data
+        * safely.
+        *
+        * Extensions which require it should install 'PageRenderingHash' hook,
+        * which will give them a chance to modify this key based on their own
+        * settings.
+        *
+        * @return string
+        */
        function getPageRenderingHash() {
-               global $wgContLang;
+               global $wgContLang, $wgUseDynamicDates;
                if( $this->mHash ){
                        return $this->mHash;
                }
@@ -1503,20 +1758,31 @@ class User {
 
                $confstr =        $this->getOption( 'math' );
                $confstr .= '!' . $this->getOption( 'stubthreshold' );
-               $confstr .= '!' . $this->getOption( 'date' );
-               $confstr .= '!' . $this->getOption( 'numberheadings' );
+               if ( $wgUseDynamicDates ) {
+                       $confstr .= '!' . $this->getDatePreference();
+               }
+               $confstr .= '!' . ($this->getOption( 'numberheadings' ) ? '1' : '');
                $confstr .= '!' . $this->getOption( 'language' );
                $confstr .= '!' . $this->getOption( 'thumbsize' );
                // add in language specific options, if any
                $extra = $wgContLang->getExtraHashOptions();
                $confstr .= $extra;
 
+               // Give a chance for extensions to modify the hash, if they have
+               // extra options or other effects on the parser cache.
+               wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
+
                $this->mHash = $confstr;
-               return $confstr ;
+               return $confstr;
+       }
+
+       function isBlockedFromCreateAccount() {
+               $this->getBlockedStatus();
+               return $this->mBlock && $this->mBlock->mCreateAccount;
        }
 
        function isAllowedToCreateAccount() {
-               return $this->isAllowed( 'createaccount' ) && !$this->isBlocked();
+               return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
        }
 
        /**
@@ -1531,7 +1797,7 @@ class User {
         * Get this user's personal page title.
         *
         * @return Title
-        * @access public
+        * @public
         */
        function getUserPage() {
                return Title::makeTitle( NS_USER, $this->getName() );
@@ -1541,7 +1807,7 @@ class User {
         * Get this user's talk page title.
         *
         * @return Title
-        * @access public
+        * @public
         */
        function getTalkPage() {
                $title = $this->getUserPage();
@@ -1552,18 +1818,23 @@ class User {
         * @static
         */
        function getMaxID() {
-               $dbr =& wfGetDB( DB_SLAVE );
-               return $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
+               static $res; // cache
+
+               if ( isset( $res ) )
+                       return $res;
+               else {
+                       $dbr =& wfGetDB( DB_SLAVE );
+                       return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
+               }
        }
 
        /**
         * Determine whether the user is a newbie. Newbies are either
-        * anonymous IPs, or the 1% most recently created accounts.
-        * Bots and sysops are excluded.
+        * anonymous IPs, or the most recently created accounts.
         * @return bool True if it is a newbie.
         */
        function isNewbie() {
-               return $this->isAnon() || $this->mId > User::getMaxID() * 0.99 && !$this->isAllowed( 'delete' ) && !$this->isBot();
+               return !$this->isAllowed( 'autoconfirmed' );
        }
 
        /**
@@ -1615,7 +1886,7 @@ class User {
         * @param mixed $salt - Optional function-specific data for hash.
         *                      Use a string or an array of strings.
         * @return string
-        * @access public
+        * @public
         */
        function editToken( $salt = '' ) {
                if( !isset( $_SESSION['wsEditToken'] ) ) {
@@ -1649,27 +1920,15 @@ class User {
         * @param string $val - the input value to compare
         * @param string $salt - Optional function-specific data for hash
         * @return bool
-        * @access public
+        * @public
         */
        function matchEditToken( $val, $salt = '' ) {
                global $wgMemc;
-
-/*
-               if ( !isset( $_SESSION['wsEditToken'] ) ) {
-                       $logfile = '/home/wikipedia/logs/session_debug/session.log';
-                       $mckey = memsess_key( session_id() );
-                       $uname = @posix_uname();
-                       $msg = "wsEditToken not set!\n" .
-                       'apache server=' . $uname['nodename'] . "\n" .
-                       'session_id = ' . session_id() . "\n" .
-                       '$_SESSION=' . var_export( $_SESSION, true ) . "\n" .
-                       '$_COOKIE=' . var_export( $_COOKIE, true ) . "\n" .
-                       "mc get($mckey) = " . var_export( $wgMemc->get( $mckey ), true ) . "\n\n\n";
-
-                       @error_log( $msg, 3, $logfile );
+               $sessionToken = $this->editToken( $salt );
+               if ( $val != $sessionToken ) {
+                       wfDebug( "User::matchEditToken: broken session data\n" );
                }
-*/
-               return ( $val == $this->editToken( $salt ) );
+               return $val == $sessionToken;
        }
 
        /**
@@ -1705,7 +1964,9 @@ class User {
                }
 
                require_once( 'UserMailer.php' );
-               $error = userMailer( $this->getEmail(), $from, $subject, $body );
+               $to = new MailAddress( $this );
+               $sender = new MailAddress( $from );
+               $error = userMailer( $to, $sender, $subject, $body );
 
                if( $error == '' ) {
                        return true;
@@ -1719,7 +1980,7 @@ class User {
         * A hash (unsalted since it's used as a key) is stored.
         * @param &$expiration mixed output: accepts the expiration time
         * @return string
-        * @access private
+        * @private
         */
        function confirmationToken( &$expiration ) {
                $fname = 'User::confirmationToken';
@@ -1746,7 +2007,7 @@ class User {
         * the URL the user can use to confirm.
         * @param &$expiration mixed output: accepts the expiration time
         * @return string
-        * @access private
+        * @private
         */
        function confirmationTokenUrl( &$expiration ) {
                $token = $this->confirmationToken( $expiration );
@@ -1795,13 +2056,18 @@ class User {
        function isEmailConfirmed() {
                global $wgEmailAuthentication;
                $this->loadFromDatabase();
-               if( $this->isAnon() )
-                       return false;
-               if( !$this->isValidEmailAddr( $this->mEmail ) )
-                       return false;
-               if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
-                       return false;
-               return true;
+               $confirmed = true;
+               if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
+                       if( $this->isAnon() )
+                               return false;
+                       if( !$this->isValidEmailAddr( $this->mEmail ) )
+                               return false;
+                       if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
+                               return false;
+                       return true;
+               } else {
+                       return $confirmed;
+               }
        }
 
        /**
@@ -1809,7 +2075,7 @@ class User {
         * @return array list of permission key names for given groups combined
         * @static
         */
-       function getGroupPermissions( $groups ) {
+       static function getGroupPermissions( $groups ) {
                global $wgGroupPermissions;
                $rights = array();
                foreach( $groups as $group ) {
@@ -1823,13 +2089,28 @@ class User {
 
        /**
         * @param string $group key name
-        * @return string localized descriptive name, if provided
+        * @return string localized descriptive name for group, if provided
+        * @static
+        */
+       static function getGroupName( $group ) {
+               $key = "group-$group";
+               $name = wfMsg( $key );
+               if( $name == '' || wfEmptyMsg( $key, $name ) ) {
+                       return $group;
+               } else {
+                       return $name;
+               }
+       }
+
+       /**
+        * @param string $group key name
+        * @return string localized descriptive name for member of a group, if provided
         * @static
         */
-       function getGroupName( $group ) {
-               $key = "group-$group-name";
+       static function getGroupMember( $group ) {
+               $key = "group-$group-member";
                $name = wfMsg( $key );
-               if( $name == '' || $name == "&lt;$key&gt;" ) {
+               if( $name == '' || wfEmptyMsg( $key, $name ) ) {
                        return $group;
                } else {
                        return $name;
@@ -1838,17 +2119,75 @@ class User {
 
        /**
         * Return the set of defined explicit groups.
-        * The * and 'user' groups are not included.
+        * The *, 'user', 'autoconfirmed' and 'emailconfirmed'
+        * groups are not included, as they are defined
+        * automatically, not in the database.
         * @return array
         * @static
         */
-       function getAllGroups() {
+       static function getAllGroups() {
                global $wgGroupPermissions;
                return array_diff(
                        array_keys( $wgGroupPermissions ),
-                       array( '*', 'user' ) );
+                       array( '*', 'user', 'autoconfirmed', 'emailconfirmed' ) );
+       }
+
+       /**
+        * Get the title of a page describing a particular group
+        *
+        * @param $group Name of the group
+        * @return mixed
+        */
+       static function getGroupPage( $group ) {
+               $page = wfMsgForContent( 'grouppage-' . $group );
+               if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
+                       $title = Title::newFromText( $page );
+                       if( is_object( $title ) )
+                               return $title;
+               }
+               return false;
+       }
+
+       /**
+        * Create a link to the group in HTML, if available
+        *
+        * @param $group Name of the group
+        * @param $text The text of the link
+        * @return mixed
+        */
+       static function makeGroupLinkHTML( $group, $text = '' ) {
+               if( $text == '' ) {
+                       $text = self::getGroupName( $group );
+               }
+               $title = self::getGroupPage( $group );
+               if( $title ) {
+                       global $wgUser;
+                       $sk = $wgUser->getSkin();
+                       return $sk->makeLinkObj( $title, $text );
+               } else {
+                       return $text;
+               }
        }
 
+       /**
+        * Create a link to the group in Wikitext, if available
+        *
+        * @param $group Name of the group
+        * @param $text The text of the link (by default, the name of the group)
+        * @return mixed
+        */
+       static function makeGroupLinkWiki( $group, $text = '' ) {
+               if( $text == '' ) {
+                       $text = self::getGroupName( $group );
+               }
+               $title = self::getGroupPage( $group );
+               if( $title ) {
+                       $page = $title->getPrefixedText();
+                       return "[[$page|$text]]";
+               } else {
+                       return $text;
+               }
+       }
 }
 
 ?>