added Minguo calendar support for the Taiwan Chinese language
[lhc/web/wiklou.git] / includes / User.php
index 1cfd8d5..d10bc34 100644 (file)
@@ -14,7 +14,7 @@ define( 'USER_TOKEN_LENGTH', 32 );
  * \int Serialized record version.
  * @ingroup Constants
  */
-define( 'MW_USER_VERSION', 6 );
+define( 'MW_USER_VERSION', 8 );
 
 /**
  * \string Some punctuation to prevent editing from broken text-mangling proxies.
@@ -91,6 +91,7 @@ class User {
                'diffonly',
                'showhiddencats',
                'noconvertlink',
+               'norollbackdiff',
        );
 
        /**
@@ -108,7 +109,6 @@ class User {
                'mNewpassword',
                'mNewpassTime',
                'mEmail',
-               'mOptions',
                'mTouched',
                'mToken',
                'mEmailAuthenticated',
@@ -118,6 +118,8 @@ class User {
                'mEditCount',
                // user_group table
                'mGroups',
+               // user_properties table
+               'mOptionOverrides',
        );
 
        /**
@@ -140,17 +142,23 @@ class User {
                'createtalk',
                'delete',
                'deletedhistory',
+               'deleterevision',
                'edit',
                'editinterface',
                'editusercssjs',
+               'hideuser',
                'import',
                'importupload',
                'ipblock-exempt',
                'markbotedits',
                'minoredit',
                'move',
+               'movefile',
+               'move-rootuserpages',
+               'move-subpages',
                'nominornewtalk',
                'noratelimit',
+               'override-export-depth',
                'patrol',
                'protect',
                'proxyunbannable',
@@ -160,13 +168,17 @@ class User {
                'reupload-shared',
                'rollback',
                'siteadmin',
+               'suppressionlog',
                'suppressredirect',
+               'suppressrevision',
                'trackback',
                'undelete',
                'unwatchedpages',
                'upload',
                'upload_by_url',
                'userrights',
+               'userrights-interwiki',
+               'writeapi',
        );
        /**
         * \string Cached results of getAllRights()
@@ -176,14 +188,14 @@ class User {
        /** @name Cache variables */
        //@{
        var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
-               $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
-               $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
+               $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
+               $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups, $mOptionOverrides;
        //@}
 
        /**
         * \bool Whether the cache variables have been loaded.
         */
-       var $mDataLoaded, $mAuthLoaded;
+       var $mDataLoaded, $mAuthLoaded, $mOptionsLoaded;
 
        /**
         * \string Initialization data source if mDataLoaded==false. May be one of:
@@ -200,7 +212,7 @@ class User {
        //@{
        var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
                $mBlockreason, $mBlock, $mEffectiveGroups, $mBlockedGlobally, 
-               $mLocked, $mHideName;
+               $mLocked, $mHideName, $mOptions;
        //@}
 
        /**
@@ -299,6 +311,7 @@ class User {
        function saveToCache() {
                $this->load();
                $this->loadGroups();
+               $this->loadOptions();
                if ( $this->isAnon() ) {
                        // Anonymous users are uncached
                        return;
@@ -435,11 +448,10 @@ class User {
        /**
         * Get database id given a user name
         * @param $name \string Username
-        * @return \2types{\int,\null} The corresponding user's ID, or null if user is nonexistent
-        * @static
+        * @return \types{\int,\null} The corresponding user's ID, or null if user is nonexistent
         */
        static function idFromName( $name ) {
-               $nt = Title::newFromText( $name );
+               $nt = Title::makeTitleSafe( NS_USER, $name );
                if( is_null( $nt ) ) {
                        # Illegal name
                        return null;
@@ -578,11 +590,12 @@ class User {
         * @return \bool True or false
         */
        static function isCreatableName( $name ) {
+               global $wgInvalidUsernameCharacters;
                return
                        self::isUsableName( $name ) &&
 
                        // Registration-time character blacklisting...
-                       strpos( $name, '@' ) === false;
+                       !preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name );
        }
 
        /**
@@ -630,7 +643,7 @@ class User {
         * Given unvalidated user input, return a canonical username, or false if
         * the username is invalid.
         * @param $name \string User input
-        * @param $validate \2types{\string,\bool} Type of validation to use:
+        * @param $validate \types{\string,\bool} Type of validation to use:
         *                - false        No validation
         *                - 'valid'      Valid for batch processes
         *                - 'usable'     Valid for batch processes and login
@@ -759,7 +772,8 @@ class User {
                $this->mPassword = $this->mNewpassword = '';
                $this->mNewpassTime = null;
                $this->mEmail = '';
-               $this->mOptions = null; # Defer init
+               $this->mOptionOverrides = null;
+               $this->mOptionsLoaded = false;
 
                if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
                        $this->mTouched = wfTimestamp( TS_MW, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
@@ -883,6 +897,8 @@ class User {
                $dbr = wfGetDB( DB_MASTER );
                $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId ), __METHOD__ );
 
+               wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
+
                if ( $s !== false ) {
                        # Initialise user table data
                        $this->loadFromRow( $s );
@@ -906,7 +922,7 @@ class User {
                $this->mDataLoaded = true;
 
                if ( isset( $row->user_id ) ) {
-                       $this->mId = $row->user_id;
+                       $this->mId = intval( $row->user_id );
                }
                $this->mName = $row->user_name;
                $this->mRealName = $row->user_real_name;
@@ -956,6 +972,7 @@ class User {
                $this->mSkin = null;
                $this->mRights = null;
                $this->mEffectiveGroups = null;
+               $this->mOptions = null;
 
                if ( $reloadFrom ) {
                        $this->mDataLoaded = false;
@@ -974,7 +991,7 @@ class User {
                /**
                 * Site defaults will override the global/language defaults
                 */
-               global $wgDefaultUserOptions, $wgContLang;
+               global $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
                $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptionOverrides();
 
                /**
@@ -983,10 +1000,11 @@ class User {
                $variant = $wgContLang->getPreferredVariant( false );
                $defOpt['variant'] = $variant;
                $defOpt['language'] = $variant;
-
-               foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
-                       $defOpt['searchNs'.$nsnum] = $val;
+               foreach(  SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
+                       $defOpt['searchNs'.$nsnum] = !empty($wgNamespacesToBeSearchedDefault[$nsnum]);
                }
+               $defOpt['skin'] = $wgDefaultSkin;
+               
                return $defOpt;
        }
 
@@ -1001,7 +1019,7 @@ class User {
                if( isset( $defOpts[$opt] ) ) {
                        return $defOpts[$opt];
                } else {
-                       return '';
+                       return null;
                }
        }
 
@@ -1010,9 +1028,14 @@ class User {
         * @return \type{\arrayof{\string}} Array of user toggle names
         */
        static function getToggles() {
-               global $wgContLang;
+               global $wgContLang, $wgUseRCPatrol;
                $extraToggles = array();
                wfRunHooks( 'UserToggles', array( &$extraToggles ) );
+               if( $wgUseRCPatrol ) {
+                       $extraToggles[] = 'hidepatrolled';
+                       $extraToggles[] = 'newpageshidepatrolled';
+                       $extraToggles[] = 'watchlisthidepatrolled';
+               }
                return array_merge( self::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
        }
 
@@ -1146,10 +1169,17 @@ class User {
         */
        public function isPingLimitable() {
                global $wgRateLimitsExcludedGroups;
+               global $wgRateLimitsExcludedIPs;
                if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
                        // Deprecated, but kept for backwards-compatibility config
                        return false;
                }
+               if( in_array( wfGetIP(), $wgRateLimitsExcludedIPs ) ) {
+                       // No other good way currently to disable rate limits
+                       // for specific IPs. :P
+                       // But this is a crappy hack and should die.
+                       return false;
+               }
                return !$this->isAllowed('noratelimit');
        }
 
@@ -1305,6 +1335,15 @@ class User {
                return $this->mBlockreason;
        }
        
+       /**
+        * If user is blocked, return the ID for the block
+        * @return \int Block ID
+        */
+       function getBlockId() {
+               $this->getBlockedStatus();
+               return ($this->mBlock ? $this->mBlock->mId : false);
+       }
+       
        /**
         * Check if user is blocked on all wikis.
         * Do not use for actual edit permission checks!
@@ -1486,7 +1525,7 @@ class User {
         *
         * @see getNewtalk()
         * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
-        * @param $id \2types{\string,\int} User's IP address for anonymous users, User ID otherwise
+        * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
         * @param $fromMaster \bool true to fetch from the master, false for a slave
         * @return \bool True if the user has new messages
         * @private
@@ -1505,7 +1544,7 @@ class User {
        /**
         * Add or update the new messages flag
         * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
-        * @param $id \2types{\string,\int} User's IP address for anonymous users, User ID otherwise
+        * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
         * @return \bool True if successful, false otherwise
         * @private
         */
@@ -1527,7 +1566,7 @@ class User {
        /**
         * Clear the new messages flag for the given user
         * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
-        * @param $id \2types{\string,\int} User's IP address for anonymous users, User ID otherwise
+        * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
         * @return \bool True if successful, false otherwise
         * @private
         */
@@ -1832,8 +1871,8 @@ class User {
         * @see getBoolOption()
         * @see getIntOption()
         */
-       function getOption( $oname, $defaultOverride = '' ) {
-               $this->load();
+       function getOption( $oname, $defaultOverride = null ) {
+               $this->loadOptions();
 
                if ( is_null( $this->mOptions ) ) {
                        if($defaultOverride != '') {
@@ -1843,7 +1882,7 @@ class User {
                }
 
                if ( array_key_exists( $oname, $this->mOptions ) ) {
-                       return trim( $this->mOptions[$oname] );
+                       return $this->mOptions[$oname];
                } else {
                        return $defaultOverride;
                }
@@ -1885,27 +1924,28 @@ class User {
         */
        function setOption( $oname, $val ) {
                $this->load();
-               if ( is_null( $this->mOptions ) ) {
-                       $this->mOptions = User::getDefaultOptions();
-               }
+               $this->loadOptions();
+               
                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.
-               if( $val ) {
-                       $val = str_replace( "\r\n", "\n", $val );
-                       $val = str_replace( "\r", "\n", $val );
-                       $val = str_replace( "\n", " ", $val );
-               }
+               
                // Explicitly NULL values should refer to defaults
                global $wgDefaultUserOptions;
                if( is_null($val) && isset($wgDefaultUserOptions[$oname]) ) {
                        $val = $wgDefaultUserOptions[$oname];
                }
+               
                $this->mOptions[$oname] = $val;
        }
+       
+       /**
+        * Reset all options to the site defaults
+        */     
+       function resetOptions() {
+               $this->mOptions = User::getDefaultOptions();
+       }
 
        /**
         * Get the user's preferred date format.
@@ -1980,7 +2020,7 @@ class User {
         * @return \int User'e edit count
         */
        function getEditCount() {
-               if ($this->mId) {
+               if ($this->getId()) {
                        if ( !isset( $this->mEditCount ) ) {
                                /* Populate the count, if it has not been populated yet */
                                $this->mEditCount = User::edits($this->mId);
@@ -2070,11 +2110,15 @@ class User {
         * @param $action \string action to be checked
         * @return \bool True if action is allowed, else false
         */
-       function isAllowed($action='') {
+       function isAllowed( $action = '' ) {
                if ( $action === '' )
-                       // In the spirit of DWIM
-                       return true;
-
+                       return true; // In the spirit of DWIM
+               # Patrolling may not be enabled
+               if( $action === 'patrol' || $action === 'autopatrol' ) {
+                       global $wgUseRCPatrol, $wgUseNPPatrol;
+                       if( !$wgUseRCPatrol && !$wgUseNPPatrol )
+                               return false;
+               }
                # Use strict parameter to avoid matching numeric 0 accidentally inserted 
                # by misconfiguration: 0 == 'foo'
                return in_array( $action, $this->getRights(), true );
@@ -2099,22 +2143,35 @@ class User {
        }
 
        /**
-        * Get the current skin, loading it if required
-        * @return \type{Skin} Current skin
+        * Get the current skin, loading it if required, and setting a title
+        * @param $t Title: the title to use in the skin
+        * @return Skin The current skin
         * @todo FIXME : need to check the old failback system [AV]
         */
-       function &getSkin() {
-               global $wgRequest;
+       function &getSkin( $t = null ) {
+               global $wgRequest, $wgAllowUserSkin, $wgDefaultSkin;
                if ( ! isset( $this->mSkin ) ) {
                        wfProfileIn( __METHOD__ );
 
-                       # get the user skin
-                       $userSkin = $this->getOption( 'skin' );
-                       $userSkin = $wgRequest->getVal('useskin', $userSkin);
-
+                       if( $wgAllowUserSkin ) {
+                               # get the user skin
+                               $userSkin = $this->getOption( 'skin' );
+                               $userSkin = $wgRequest->getVal('useskin', $userSkin);
+                       } else {
+                               # if we're not allowing users to override, then use the default
+                               $userSkin = $wgDefaultSkin;
+                       }
+                       
                        $this->mSkin =& Skin::newFromKey( $userSkin );
                        wfProfileOut( __METHOD__ );
                }
+               if( $t || !$this->mSkin->getTitle() ) {
+                       if ( !$t ) {
+                               global $wgOut;
+                               $t = $wgOut->getTitle();
+                       }
+                       $this->mSkin->setTitle( $t );
+               }
                return $this->mSkin;
        }
 
@@ -2235,36 +2292,25 @@ class User {
                }
        }
 
-       /**
-        * Encode this user's options as a string
-        * @return \string Encoded options
-        * @private
-        */
-       function encodeOptions() {
-               $this->load();
-               if ( is_null( $this->mOptions ) ) {
-                       $this->mOptions = User::getDefaultOptions();
-               }
-               $a = array();
-               foreach ( $this->mOptions as $oname => $oval ) {
-                       array_push( $a, $oname.'='.$oval );
-               }
-               $s = implode( "\n", $a );
-               return $s;
-       }
-
        /**
         * Set this user's options from an encoded string
         * @param $str \string Encoded options to import
         * @private
         */
        function decodeOptions( $str ) {
+               if (!$str)
+                       return;
+                       
+               $this->mOptionsLoaded = true;
+               $this->mOptionOverrides = array();
+               
                $this->mOptions = array();
                $a = explode( "\n", $str );
                foreach ( $a as $s ) {
                        $m = array();
                        if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
                                $this->mOptions[$m[1]] = $m[2];
+                               $this->mOptionOverrides[$m[1]] = $m[2];
                        }
                }
        }
@@ -2273,8 +2319,8 @@ class User {
         * Set a cookie on the user's client. Wrapper for 
         * WebResponse::setCookie
         * @param $name \string Name of the cookie to set
-        * @param $name \string Value to set
-        * @param $name \int Expiration time, as a UNIX time value; 
+        * @param $value \string Value to set
+        * @param $exp \int Expiration time, as a UNIX time value; 
         *                   if 0 or not specified, use the default $wgCookieExpiration
         */
        protected function setCookie( $name, $value, $exp=0 ) {
@@ -2313,7 +2359,7 @@ class User {
                
                wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
                #check for null, since the hook could cause a null value 
-               if ( !is_null( $session ) && !is_null( $_SESSION ) ){
+               if ( !is_null( $session ) && isset( $_SESSION ) ){
                        $_SESSION = $session + $_SESSION;
                }
                foreach ( $cookies as $name => $value ) {
@@ -2329,7 +2375,6 @@ class User {
         * Log this user out.
         */
        function logout() {
-               global $wgUser;
                if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
                        $this->doLogout();
                }
@@ -2373,7 +2418,7 @@ class User {
                                'user_real_name' => $this->mRealName,
                                'user_email' => $this->mEmail,
                                'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
-                               'user_options' => $this->encodeOptions(),
+                               'user_options' => '',
                                'user_touched' => $dbw->timestamp($this->mTouched),
                                'user_token' => $this->mToken,
                                'user_email_token' => $this->mEmailToken,
@@ -2382,6 +2427,9 @@ class User {
                                'user_id' => $this->mId
                        ), __METHOD__
                );
+               
+               $this->saveOptions();
+               
                wfRunHooks( 'UserSaveSettings', array( $this ) );
                $this->clearSharedCache();
                $this->getUserPage()->invalidateCache();
@@ -2470,7 +2518,7 @@ class User {
                                'user_email' => $this->mEmail,
                                'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
                                'user_real_name' => $this->mRealName,
-                               'user_options' => $this->encodeOptions(),
+                               'user_options' => '',
                                'user_token' => $this->mToken,
                                'user_registration' => $dbw->timestamp( $this->mRegistration ),
                                'user_editcount' => 0,
@@ -2480,6 +2528,8 @@ class User {
 
                // Clear instance cache other than user table data, which is already accurate
                $this->clearInstanceCache();
+               
+               $this->saveOptions();
        }
 
        /**
@@ -2697,7 +2747,14 @@ class User {
         * @return \bool True if matches, false otherwise
         */
        function checkTemporaryPassword( $plaintext ) {
-               return self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() );
+               global $wgNewPasswordExpiry;
+               if( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) {
+                       $this->load();
+                       $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
+                       return ( time() < $expiry );
+               } else {
+                       return false;
+               }
        }
 
        /**
@@ -2706,7 +2763,7 @@ class User {
         * login credentials aren't being hijacked with a foreign form
         * submission.
         *
-        * @param $salt \2types{\string,\arrayof{\string}} Optional function-specific data for hashing
+        * @param $salt \types{\string,\arrayof{\string}} Optional function-specific data for hashing
         * @return \string The new edit token
         */
        function editToken( $salt = '' ) {
@@ -2772,7 +2829,7 @@ class User {
         * Generate a new e-mail confirmation token and send a confirmation/invalidation
         * mail to the user's given address.
         *
-        * @return \2types{\bool,\type{WikiError}} True on success, a WikiError object on failure.
+        * @return \types{\bool,\type{WikiError}} True on success, a WikiError object on failure.
         */
        function sendConfirmationMail() {
                global $wgLang;
@@ -2799,7 +2856,7 @@ class User {
         * @param $body \string Message body
         * @param $from \string Optional From address; if unspecified, default $wgPasswordSender will be used
         * @param $replyto \string Reply-To address
-        * @return \2types{\bool,\type{WikiError}} True on success, a WikiError object on failure
+        * @return \types{\bool,\type{WikiError}} True on success, a WikiError object on failure
         */
        function sendMail( $subject, $body, $from = null, $replyto = null ) {
                if( is_null( $from ) ) {
@@ -2977,14 +3034,32 @@ class User {
        /**
         * Get the timestamp of account creation.
         *
-        * @return \2types{\string,\bool} string Timestamp of account creation, or false for
+        * @return \types{\string,\bool} string Timestamp of account creation, or false for
         *                                non-existent/anonymous user accounts.
         */
        public function getRegistration() {
-               return $this->mId > 0
+               return $this->getId() > 0
                        ? $this->mRegistration
                        : false;
        }
+       
+       /**
+        * Get the timestamp of the first edit
+        *
+        * @return \types{\string,\bool} string Timestamp of first edit, or false for
+        *                                non-existent/anonymous user accounts.
+        */
+       public function getFirstEditTimestamp() {
+               if( $this->getId() == 0 ) return false; // anons
+               $dbr = wfGetDB( DB_SLAVE );
+               $time = $dbr->selectField( 'revision', 'rev_timestamp',
+                       array( 'rev_user' => $this->getId() ),
+                       __METHOD__,
+                       array( 'ORDER BY' => 'rev_timestamp ASC' )
+               );
+               if( !$time ) return false; // no edits
+               return wfTimestamp( TS_MW, $time );
+       }       
 
        /**
         * Get the permissions associated with a given list of groups
@@ -2998,10 +3073,11 @@ class User {
                foreach( $groups as $group ) {
                        if( isset( $wgGroupPermissions[$group] ) ) {
                                $rights = array_merge( $rights,
+                                       // array_filter removes empty items
                                        array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
                        }
                }
-               return $rights;
+               return array_unique($rights);
        }
        
        /**
@@ -3099,7 +3175,7 @@ class User {
         * Get the title of a page describing a particular group
         *
         * @param $group \string Internal group name
-        * @return \2types{\type{Title},\bool} Title of the page if it exists, false otherwise
+        * @return \types{\type{Title},\bool} Title of the page if it exists, false otherwise
         */
        static function getGroupPage( $group ) {
                global $wgMessageCache;
@@ -3129,7 +3205,7 @@ class User {
                if( $title ) {
                        global $wgUser;
                        $sk = $wgUser->getSkin();
-                       return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
+                       return $sk->link( $title, htmlspecialchars( $text ) );
                } else {
                        return $text;
                }
@@ -3155,6 +3231,114 @@ class User {
                        return $text;
                }
        }
+       
+       /**
+        * Returns an array of the groups that a particular group can add/remove.
+        *
+        * @param $group String: the group to check for whether it can add/remove
+        * @return Array array( 'add' => array( addablegroups ),
+        *  'remove' => array( removablegroups ),
+        *  'add-self' => array( addablegroups to self),
+        *  'remove-self' => array( removable groups from self) )
+        */
+       static function changeableByGroup( $group ) {
+               global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
+
+               $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
+               if( empty($wgAddGroups[$group]) ) {
+                       // Don't add anything to $groups
+               } elseif( $wgAddGroups[$group] === true ) {
+                       // You get everything
+                       $groups['add'] = self::getAllGroups();
+               } elseif( is_array($wgAddGroups[$group]) ) {
+                       $groups['add'] = $wgAddGroups[$group];
+               }
+
+               // Same thing for remove
+               if( empty($wgRemoveGroups[$group]) ) {
+               } elseif($wgRemoveGroups[$group] === true ) {
+                       $groups['remove'] = self::getAllGroups();
+               } elseif( is_array($wgRemoveGroups[$group]) ) {
+                       $groups['remove'] = $wgRemoveGroups[$group];
+               }
+               
+               // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
+               if( empty($wgGroupsAddToSelf['user']) || $wgGroupsAddToSelf['user'] !== true ) {
+                       foreach($wgGroupsAddToSelf as $key => $value) {
+                               if( is_int($key) ) {
+                                       $wgGroupsAddToSelf['user'][] = $value;
+                               }
+                       }
+               }
+               
+               if( empty($wgGroupsRemoveFromSelf['user']) || $wgGroupsRemoveFromSelf['user'] !== true ) {
+                       foreach($wgGroupsRemoveFromSelf as $key => $value) {
+                               if( is_int($key) ) {
+                                       $wgGroupsRemoveFromSelf['user'][] = $value;
+                               }
+                       }
+               }
+               
+               // Now figure out what groups the user can add to him/herself
+               if( empty($wgGroupsAddToSelf[$group]) ) {
+               } elseif( $wgGroupsAddToSelf[$group] === true ) {
+                       // No idea WHY this would be used, but it's there
+                       $groups['add-self'] = User::getAllGroups();
+               } elseif( is_array($wgGroupsAddToSelf[$group]) ) {
+                       $groups['add-self'] = $wgGroupsAddToSelf[$group];
+               }
+               
+               if( empty($wgGroupsRemoveFromSelf[$group]) ) {
+               } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
+                       $groups['remove-self'] = User::getAllGroups();
+               } elseif( is_array($wgGroupsRemoveFromSelf[$group]) ) {
+                       $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
+               }
+               
+               return $groups;
+       }
+       
+       /**
+        * Returns an array of groups that this user can add and remove
+        * @return Array array( 'add' => array( addablegroups ),
+        *  'remove' => array( removablegroups ),
+        *  'add-self' => array( addablegroups to self),
+        *  'remove-self' => array( removable groups from self) )
+        */
+       function changeableGroups() {
+               if( $this->isAllowed( 'userrights' ) ) {
+                       // This group gives the right to modify everything (reverse-
+                       // compatibility with old "userrights lets you change
+                       // everything")
+                       // Using array_merge to make the groups reindexed
+                       $all = array_merge( User::getAllGroups() );
+                       return array(
+                               'add' => $all,
+                               'remove' => $all,
+                               'add-self' => array(),
+                               'remove-self' => array()
+                       );
+               }
+
+               // Okay, it's not so simple, we will have to go through the arrays
+               $groups = array(
+                               'add' => array(),
+                               'remove' => array(),
+                               'add-self' => array(),
+                               'remove-self' => array() );
+               $addergroups = $this->getEffectiveGroups();
+
+               foreach ($addergroups as $addergroup) {
+                       $groups = array_merge_recursive(
+                               $groups, $this->changeableByGroup($addergroup)
+                       );
+                       $groups['add']    = array_unique( $groups['add'] );
+                       $groups['remove'] = array_unique( $groups['remove'] );
+                       $groups['add-self'] = array_unique( $groups['add-self'] );
+                       $groups['remove-self'] = array_unique( $groups['remove-self'] );
+               }
+               return $groups;
+       }
 
        /**
         * Increment the user's edit-count field.
@@ -3243,13 +3427,18 @@ class User {
        static function crypt( $password, $salt = false ) {
                global $wgPasswordSalt;
 
-               if($wgPasswordSalt) {
+               $hash = '';
+               if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
+                       return $hash;
+               }
+               
+               if( $wgPasswordSalt ) {
                        if ( $salt === false ) {
                                $salt = substr( wfGenerateToken(), 0, 8 );
                        }
                        return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
                } else {
-                       return ':A:' . md5( $password);
+                       return ':A:' . md5( $password );
                }
        }
 
@@ -3265,6 +3454,12 @@ class User {
        static function comparePasswords( $hash, $password, $userId = false ) {
                $m = false;
                $type = substr( $hash, 0, 3 );
+               
+               $result = false;
+               if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
+                       return $result;
+               }
+               
                if ( $type == ':A:' ) {
                        # Unsalted
                        return md5( $password ) === substr( $hash, 3 );
@@ -3280,7 +3475,7 @@ class User {
        
        /**
         * Add a newuser log entry for this user
-        * @param bool $byEmail, account made by email?
+        * @param $byEmail Boolean: account made by email?
         */
        public function addNewUserLogEntry( $byEmail = false ) {
                global $wgUser, $wgContLang, $wgNewUserLog;
@@ -3313,5 +3508,72 @@ class User {
                $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );
                return true;
        }
+       
+       protected function loadOptions() {
+               $this->load();
+               if ($this->mOptionsLoaded || !$this->getId() )
+                       return;
+       
+               $this->mOptions = self::getDefaultOptions();
+               
+               // Maybe load from the object
+               
+               if ( !is_null($this->mOptionOverrides) ) {
+                       wfDebug( "Loading options for user ".$this->getId()." from override cache.\n" ); 
+                       foreach( $this->mOptionOverrides as $key => $value ) {
+                               $this->mOptions[$key] = $value;
+                       }
+               } else {
+                       wfDebug( "Loading options for user ".$this->getId()." from database.\n" );
+                       // Load from database
+                       $dbr = wfGetDB( DB_SLAVE );
+                       
+                       $res = $dbr->select( 'user_properties',
+                                                                       '*',
+                                                                       array('up_user' => $this->getId()),
+                                                                       __METHOD__
+                                                               );
+                       
+                       while( $row = $dbr->fetchObject( $res ) ) {
+                               $this->mOptionOverrides[$row->up_property] = $row->up_value;
+                               $this->mOptions[$row->up_property] = $row->up_value;
+                       }
+               }
+               
+               $this->mOptionsLoaded = true;
+               
+               wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
+       }
+       
+       protected function saveOptions() {
+               $this->loadOptions();
+               $dbw = wfGetDB( DB_MASTER );
+               
+               $insert_rows = array();
+               
+               $saveOptions = $this->mOptions;
+               
+               // Allow hooks to abort, for instance to save to a global profile.
+               // Reset options to default state before saving.
+               if (!wfRunHooks( 'UserSaveOptions', array($this, &$saveOptions) ) )
+                       return;
+               
+               foreach( $saveOptions as $key => $value ) {
+                       if ( ( is_null(self::getDefaultOption($key)) &&
+                                       !( $value === false || is_null($value) ) ) ||
+                                       $value != self::getDefaultOption( $key ) ) {
+                               $insert_rows[] = array(
+                                               'up_user' => $this->getId(),
+                                               'up_property' => $key,
+                                               'up_value' => $value,
+                                       );
+                       }
+               }
+               
+               $dbw->begin();
+               $dbw->delete( 'user_properties', array( 'up_user' => $this->getId() ), __METHOD__ );
+               $dbw->insert( 'user_properties', $insert_rows, __METHOD__ );
+               $dbw->commit();
+       }
 
 }