X-Git-Url: http://git.cyclocoop.org/?a=blobdiff_plain;ds=sidebyside;f=includes%2FUser.php;h=ed5257f8e40c4703e1f9e4b788e3226cf6617975;hb=ab89e683a4c8cecf0fa4ebc95b3ab1736770cef0;hp=6734c322ee715b328296282d118c1d8f0804c5a4;hpb=60731518dbba0af4955b661732ecf3fe1fbb91a9;p=lhc%2Fweb%2Fwiklou.git diff --git a/includes/User.php b/includes/User.php index 6734c322ee..ed5257f8e4 100644 --- a/includes/User.php +++ b/includes/User.php @@ -1,21 +1,21 @@ getExtraUserToggles(). */ static public $mToggles = array( @@ -76,11 +76,12 @@ class User { 'watchlisthideminor', 'ccmeonemails', 'diffonly', + 'showhiddencats', ); /** * List of member variables which are saved to the shared cache (memcached). - * Any operation which changes the corresponding database fields must + * Any operation which changes the corresponding database fields must * call a cache-clearing function. */ static $mCacheVars = array( @@ -104,11 +105,58 @@ class User { 'mGroups', ); + /** + * Core rights + * Each of these should have a corresponding message of the form "right-$right" + */ + static $mCoreRights = array( + 'apihighlimits', + 'autoconfirmed', + 'autopatrol', + 'bigdelete', + 'block', + 'blockemail', + 'bot', + 'browsearchive', + 'createaccount', + 'createpage', + 'createtalk', + 'delete', + 'deletedhistory', + 'edit', + 'editinterface', + 'editusercssjs', + 'import', + 'importupload', + 'ipblock-exempt', + 'markbotedits', + 'minoredit', + 'move', + 'nominornewtalk', + 'noratelimit', + 'patrol', + 'protect', + 'proxyunbannable', + 'purge', + 'read', + 'reupload', + 'reupload-shared', + 'rollback', + 'suppressredirect', + 'trackback', + 'undelete', + 'unwatchedpages', + 'upload', + 'upload_by_url', + 'userrights', + ); + static $mAllRights = false; + /** * The cache variable declarations */ - var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime, - $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated, + var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime, + $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated, $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups; /** @@ -133,7 +181,7 @@ class User { var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights, $mBlockreason, $mBlock, $mEffectiveGroups; - /** + /** * Lightweight constructor for anonymous user * Use the User::newFrom* factory functions for other kinds of users */ @@ -188,7 +236,7 @@ class User { if ( $this->mId == 0 ) { $this->loadDefaults(); return false; - } + } # Try cache $key = wfMemcKey( 'user', 'id', $this->mId ); @@ -197,7 +245,7 @@ class User { # Object is expired, load from DB $data = false; } - + if ( !$data ) { wfDebug( "Cache miss for user {$this->mId}\n" ); # Load from DB @@ -205,7 +253,6 @@ class User { # Can't load from ID, user is anonymous return false; } - $this->saveToCache(); } else { wfDebug( "Got user {$this->mId} from cache\n" ); @@ -222,6 +269,7 @@ class User { */ function saveToCache() { $this->load(); + $this->loadGroups(); if ( $this->isAnon() ) { // Anonymous users are uncached return; @@ -240,17 +288,16 @@ class User { * Static factory method for creation from username. * * This is slightly less efficient than newFromId(), so use newFromId() if - * you have both an ID and a name handy. + * you have both an ID and a name handy. * - * @param string $name Username, validated by Title:newFromText() - * @param mixed $validate Validate username. Takes the same parameters as - * User::getCanonicalName(), except that true is accepted as an alias + * @param $name String: username, validated by Title:newFromText() + * @param $validate Mixed: validate username. Takes the same parameters as + * User::getCanonicalName(), except that true is accepted as an alias * for 'valid', for BC. - * - * @return User object, or null if the username is invalid. If the username + * + * @return User object, or null if the username is invalid. If the username * is not present in the database, the result will be a user object with - * a name, zero user ID and default settings. - * @static + * a name, zero user ID and default settings. */ static function newFromName( $name, $validate = 'valid' ) { if ( $validate === true ) { @@ -282,9 +329,8 @@ class User { * * If the code is invalid or has expired, returns NULL. * - * @param string $code + * @param $code string * @return User - * @static */ static function newFromConfirmationCode( $code ) { $dbr = wfGetDB( DB_SLAVE ); @@ -298,13 +344,12 @@ class User { return null; } } - + /** * Create a new user object using data from session or cookies. If the * login credentials are invalid, the result is an anonymous user. * * @return User - * @static */ static function newFromSession() { $user = new User; @@ -312,11 +357,20 @@ class User { return $user; } + /** + * Create a new user object from a user row. + * The row should have all fields from the user table in it. + */ + static function newFromRow( $row ) { + $user = new User; + $user->loadFromRow( $row ); + return $user; + } + /** * Get username given an id. - * @param integer $id Database user id + * @param $id Integer: database user id * @return string Nickname of a user - * @static */ static function whoIs( $id ) { $dbr = wfGetDB( DB_SLAVE ); @@ -326,7 +380,7 @@ class User { /** * Get the real name of a user given their identifier * - * @param int $id Database user id + * @param $id Int: database user id * @return string Real name of a user */ static function whoIsReal( $id ) { @@ -336,7 +390,7 @@ class User { /** * Get database id given a user name - * @param string $name Nickname of a user + * @param $name String: nickname of a user * @return integer|null Database user id (null: if non existent * @static */ @@ -361,47 +415,19 @@ class User { * * 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 + * 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. * - * @static - * @param string $name Nickname of a user + * @param $name String: nickname of a user * @return bool */ static function isIP( $name ) { - return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || User::isIPv6($name); - /*return preg_match("/^ - (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\. - (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\. - (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\. - (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5])) - $/x", $name);*/ - } - - /** - * Check if $name is an IPv6 IP. - */ - static function isIPv6($name) { - /* - * if it has any non-valid characters, it can't be a valid IPv6 - * address. - */ - if (preg_match("/[^:a-fA-F0-9]/", $name)) - return false; - - $parts = explode(":", $name); - if (count($parts) < 3) - return false; - foreach ($parts as $part) { - if (!preg_match("/^[0-9a-fA-F]{0,4}$/", $part)) - return false; - } - return true; + return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP::isIPv6($name); } /** @@ -412,9 +438,8 @@ class User { * is longer than the maximum allowed username size or doesn't begin with * a capital letter. * - * @param string $name + * @param $name string * @return bool - * @static */ static function isValidUserName( $name ) { global $wgContLang, $wgMaxNameChars; @@ -423,17 +448,23 @@ class User { || User::isIP( $name ) || strpos( $name, '/' ) !== false || strlen( $name ) > $wgMaxNameChars - || $name != $wgContLang->ucfirst( $name ) ) + || $name != $wgContLang->ucfirst( $name ) ) { + wfDebugLog( 'username', __METHOD__ . + ": '$name' invalid due to empty, IP, slash, length, or lowercase" ); return false; + } // 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() ) ) + || strcmp( $name, $parsed->getPrefixedText() ) ) { + wfDebugLog( 'username', __METHOD__ . + ": '$name' invalid due to ambiguous prefixes" ); return false; - + } + // Check an additional blacklist of troublemaker characters. // Should these be merged into the title char list? $unicodeBlacklist = '/[' . @@ -445,12 +476,14 @@ class User { '\x{e000}-\x{f8ff}' . # private use ']/u'; if( preg_match( $unicodeBlacklist, $name ) ) { + wfDebugLog( 'username', __METHOD__ . + ": '$name' invalid due to blacklisted characters" ); 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 @@ -459,7 +492,7 @@ class User { * If an account already exists in this form, login will be blocked * by a failure to pass this function. * - * @param string $name + * @param $name string * @return bool */ static function isUsableName( $name ) { @@ -467,11 +500,11 @@ class User { return // Must be a valid 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 @@ -482,13 +515,13 @@ class User { * rather than in isValidUserName() to avoid disrupting * existing accounts. * - * @param string $name + * @param $name string * @return bool */ static function isCreatableName( $name ) { return self::isUsableName( $name ) && - + // Registration-time character blacklisting... strpos( $name, '@' ) === false; } @@ -496,7 +529,7 @@ class User { /** * Is the input a valid password for this user? * - * @param string $password Desired password + * @param $password String: desired password * @return bool */ function isValidPassword( $password ) { @@ -507,7 +540,7 @@ class User { return $result; if( $result === false ) return false; - + // Password needs to be long enough, and can't be the same as the username return strlen( $password ) >= $wgMinimalPasswordLength && $wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName ); @@ -522,7 +555,7 @@ class User { * * @todo Check for RFC 2822 compilance (bug 959) * - * @param string $addr email address + * @param $addr String: email address * @return bool */ public static function isValidEmailAddr( $addr ) { @@ -535,14 +568,14 @@ class User { } /** - * Given unvalidated user input, return a canonical username, or false if + * Given unvalidated user input, return a canonical username, or false if * the username is invalid. - * @param string $name - * @param mixed $validate Type of validation to use: - * false No validation - * 'valid' Valid for batch processes - * 'usable' Valid for batch processes and login - * 'creatable' Valid for batch processes, login and account creation + * @param $name string + * @param $validate Mixed: type of validation to use: + * false No validation + * 'valid' Valid for batch processes + * 'usable' Valid for batch processes and login + * 'creatable' Valid for batch processes, login and account creation */ static function getCanonicalName( $name, $validate = 'valid' ) { # Force usernames to capital @@ -594,10 +627,9 @@ class User { * Count the number of edits of a user * * It should not be static and some day should be merged as proper member function / deprecated -- domas - * - * @param int $uid The user ID to check + * + * @param $uid Int: the user ID to check * @return int - * @static */ static function edits( $uid ) { wfProfileIn( __METHOD__ ); @@ -634,7 +666,6 @@ class User { * @todo hash random numbers to improve security, like generateToken() * * @return string - * @static */ static function randomPassword() { global $wgMinimalPasswordLength; @@ -651,7 +682,7 @@ class User { } /** - * Set cached properties to default. Note: this no longer clears + * Set cached properties to default. Note: this no longer clears * uncached lazy-initialised properties. The constructor does that instead. * * @private @@ -682,14 +713,17 @@ class User { $this->mRegistration = wfTimestamp( TS_MW ); $this->mGroups = array(); + wfRunHooks( 'UserLoadDefaults', array( $this, $name ) ); + wfProfileOut( __METHOD__ ); } - + /** * Initialise php session * @deprecated use wfSetupSession() */ function SetupSession() { + wfDeprecated( __METHOD__ ); wfSetupSession(); } @@ -701,6 +735,12 @@ class User { private function loadFromSession() { global $wgMemc, $wgCookiePrefix; + $result = null; + wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) ); + if ( $result !== null ) { + return $result; + } + if ( isset( $_SESSION['wsUserID'] ) ) { if ( 0 != $_SESSION['wsUserID'] ) { $sId = $_SESSION['wsUserID']; @@ -731,7 +771,7 @@ class User { # Not a valid ID, loadFromId has switched the object to anon for us return false; } - + if ( isset( $_SESSION['wsToken'] ) ) { $passwordCorrect = $_SESSION['wsToken'] == $this->mToken; $from = 'session'; @@ -755,11 +795,11 @@ class User { return false; } } - + /** * Load user and user_group data from the database * $this->mId must be set, this is how the user is identified. - * + * * @return true if the user exists, false if the user is anonymous * @private */ @@ -778,23 +818,50 @@ class User { if ( $s !== false ) { # Initialise user table data - $this->mName = $s->user_name; - $this->mRealName = $s->user_real_name; - $this->mPassword = $s->user_password; - $this->mNewpassword = $s->user_newpassword; - $this->mNewpassTime = wfTimestampOrNull( TS_MW, $s->user_newpass_time ); - $this->mEmail = $s->user_email; - $this->decodeOptions( $s->user_options ); - $this->mTouched = wfTimestamp(TS_MW,$s->user_touched); - $this->mToken = $s->user_token; - $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $s->user_email_authenticated ); - $this->mEmailToken = $s->user_email_token; - $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $s->user_email_token_expires ); - $this->mRegistration = wfTimestampOrNull( TS_MW, $s->user_registration ); - $this->mEditCount = $s->user_editcount; + $this->loadFromRow( $s ); + $this->mGroups = null; // deferred $this->getEditCount(); // revalidation for nulls + return true; + } else { + # Invalid user_id + $this->mId = 0; + $this->loadDefaults(); + return false; + } + } + + /** + * Initialise the user object from a row from the user table + */ + function loadFromRow( $row ) { + $this->mDataLoaded = true; - # Load group data + if ( isset( $row->user_id ) ) { + $this->mId = $row->user_id; + } + $this->mName = $row->user_name; + $this->mRealName = $row->user_real_name; + $this->mPassword = $row->user_password; + $this->mNewpassword = $row->user_newpassword; + $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time ); + $this->mEmail = $row->user_email; + $this->decodeOptions( $row->user_options ); + $this->mTouched = wfTimestamp(TS_MW,$row->user_touched); + $this->mToken = $row->user_token; + $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated ); + $this->mEmailToken = $row->user_email_token; + $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires ); + $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration ); + $this->mEditCount = $row->user_editcount; + } + + /** + * Load the groups from the database if they aren't already loaded + * @private + */ + function loadGroups() { + if ( is_null( $this->mGroups ) ) { + $dbr = wfGetDB( DB_MASTER ); $res = $dbr->select( 'user_groups', array( 'ug_group' ), array( 'ug_user' => $this->mId ), @@ -803,19 +870,13 @@ class User { while( $row = $dbr->fetchObject( $res ) ) { $this->mGroups[] = $row->ug_group; } - return true; - } else { - # Invalid user_id - $this->mId = 0; - $this->loadDefaults(); - return false; } } /** - * Clear various cached data stored in this object. - * @param string $reloadFrom Reload user and user_groups table data from a - * given source. May be "name", "id", "defaults", "session" or false for + * Clear various cached data stored in this object. + * @param $reloadFrom String: reload user and user_groups table data from a + * given source. May be "name", "id", "defaults", "session" or false for * no reload. */ function clearInstanceCache( $reloadFrom = false ) { @@ -838,7 +899,6 @@ class User { * and add the default language variants. * Not really private cause it's called by Language class * @return array - * @static * @private */ static function getDefaultOptions() { @@ -865,13 +925,11 @@ class User { /** * Get a given default option value. * - * @param string $opt + * @param $opt string * @return string - * @static - * @public */ - function getDefaultOption( $opt ) { - $defOpts = User::getDefaultOptions(); + public static function getDefaultOption( $opt ) { + $defOpts = self::getDefaultOptions(); if( isset( $defOpts[$opt] ) ) { return $defOpts[$opt]; } else { @@ -894,9 +952,10 @@ class User { /** * Get blocking information * @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. + * @param $bFromSlave Bool: 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. */ function getBlockedStatus( $bFromSlave = true ) { global $wgEnableSorbs, $wgProxyWhitelist; @@ -909,7 +968,14 @@ class User { wfProfileIn( __METHOD__ ); wfDebug( __METHOD__.": checking...\n" ); - $this->mBlockedby = 0; + // Initialize data... + // Otherwise something ends up stomping on $this->mBlockedby when + // things get lazy-loaded later, causing false positive block hits + // due to -1 !== 0. Probably session-related... Nothing should be + // overwriting mBlockedby, surely? + $this->load(); + + $this->mBlockedby = 0; $this->mHideName = 0; $ip = wfGetIP(); @@ -936,7 +1002,6 @@ class User { # Proxy blocking if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) { - # Local list if ( wfIsLocallyBlockedProxy( $ip ) ) { $this->mBlockedby = wfMsg( 'proxyblocker' ); @@ -970,7 +1035,7 @@ class User { $found = false; $host = ''; - + // FIXME: IPv6 ??? $m = array(); if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) { # Make hostname @@ -1001,7 +1066,11 @@ class User { */ public function isPingLimitable() { global $wgRateLimitsExcludedGroups; - return array_intersect($this->getEffectiveGroups(), $wgRateLimitsExcludedGroups) == array(); + if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) { + // Deprecated, but kept for backwards-compatibility config + return false; + } + return !$this->isAllowed('noratelimit'); } /** @@ -1012,7 +1081,6 @@ class User { * last-hit counters will be shared across wikis. * * @return bool true if a rate limiter was tripped - * @public */ function pingLimiter( $action='edit' ) { @@ -1022,7 +1090,7 @@ class User { return $result; } - global $wgRateLimits, $wgRateLimitsExcludedGroups; + global $wgRateLimits; if( !isset( $wgRateLimits[$action] ) ) { return false; } @@ -1038,13 +1106,14 @@ class User { $keys = array(); $id = $this->getId(); $ip = wfGetIP(); + $userLimit = false; if( isset( $limits['anon'] ) && $id == 0 ) { $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon']; } if( isset( $limits['user'] ) && $id != 0 ) { - $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['user']; + $userLimit = $limits['user']; } if( $this->isNewbie() ) { if( isset( $limits['newbie'] ) && $id != 0 ) { @@ -1059,6 +1128,20 @@ class User { $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet']; } } + // Check for group-specific permissions + // If more than one group applies, use the group with the highest limit + foreach ( $this->getGroups() as $group ) { + if ( isset( $limits[$group] ) ) { + if ( $userLimit === false || $limits[$group] > $userLimit ) { + $userLimit = $limits[$group]; + } + } + } + // Set the user limit key + if ( $userLimit !== false ) { + wfDebug( __METHOD__.": effective user limit: $userLimit\n" ); + $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit; + } $triggered = false; foreach( $keys as $key => $limit ) { @@ -1137,7 +1220,7 @@ class User { /** * Get the user ID. Returns 0 if the user is anonymous or nonexistent. */ - function getID() { + function getId() { if( $this->mId === null and $this->mName !== null and User::isIP( $this->mName ) ) { // Special case, we know the user is anonymous @@ -1151,9 +1234,8 @@ class User { /** * Set the user and reload all fields according to that ID - * @deprecated use User::newFromId() */ - function setID( $v ) { + function setId( $v ) { $this->mId = $v; $this->clearInstanceCache( 'id' ); } @@ -1176,12 +1258,12 @@ class User { } /** - * Set the user name. + * Set the user name. * - * This does not reload fields from the database according to the given + * This does not reload fields from the database according to the given * name. Rather, it is used to create a temporary "nonexistent user" for - * later addition to the database. It can also be used to set the IP - * address for an anonymous user to something other than the current + * later addition to the database. It can also be used to set the IP + * address for an anonymous user to something other than the current * remote IP. * * User::newFromName() has rougly the same function, when the named user @@ -1195,7 +1277,6 @@ class User { /** * Return the title dbkey form of the name, for eg user pages. * @return string - * @public */ function getTitleKey() { return str_replace( ' ', '_', $this->getName() ); @@ -1245,14 +1326,14 @@ class User { return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL())); } - + /** - * Perform a user_newtalk check, uncached. + * Perform a user_newtalk check, uncached. * Use getNewtalk for a cached check. - * - * @param string $field - * @param mixed $id - * @param bool $fromMaster True to fetch from the master, false for a slave + * + * @param $field string + * @param $id mixed + * @param $fromMaster Bool: true to fetch from the master, false for a slave * @return bool * @private */ @@ -1269,8 +1350,8 @@ class User { /** * Add or update the - * @param string $field - * @param mixed $id + * @param $field string + * @param $id mixed * @private */ function updateNewtalk( $field, $id ) { @@ -1290,8 +1371,8 @@ class User { /** * Clear the new messages flag for the given user - * @param string $field - * @param mixed $id + * @param $field string + * @param $id mixed * @private */ function deleteNewtalk( $field, $id ) { @@ -1310,7 +1391,7 @@ class User { /** * Update the 'You have new messages!' status. - * @param bool $val + * @param $val bool */ function setNewtalk( $val ) { if( wfReadOnly() ) { @@ -1345,7 +1426,7 @@ class User { $this->invalidateCache(); } } - + /** * Generate a current or new-future timestamp to be stored in the * user_touched field when we update things. @@ -1354,7 +1435,7 @@ class User { global $wgClockSkewFudge; return wfTimestamp( TS_MW, time() + $wgClockSkewFudge ); } - + /** * Clear user data from memcached. * Use after applying fun updates to the database; caller's @@ -1378,13 +1459,13 @@ class User { $this->load(); 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->clearSharedCache(); } } @@ -1394,18 +1475,6 @@ class User { return ($timestamp >= $this->mTouched); } - /** - * Encrypt a password. - * It can eventually salt a password. - * @see User::addSalt() - * @param string $p clear Password. - * @return string Encrypted password. - */ - function encryptPassword( $p ) { - $this->load(); - return wfEncryptPassword( $this->mId, $p ); - } - /** * Set the password and reset the random token * Calls through to authentication plugin if necessary; @@ -1417,20 +1486,20 @@ class User { * wipes it, so the account cannot be logged in until * a new password is set, for instance via e-mail. * - * @param string $str + * @param $str string * @throws PasswordError on failure */ function setPassword( $str ) { global $wgAuth; - + if( $str !== null ) { if( !$wgAuth->allowPasswordChange() ) { throw new PasswordError( wfMsg( 'password-change-forbidden' ) ); } - + if( !$this->isValidPassword( $str ) ) { global $wgMinimalPasswordLength; - throw new PasswordError( wfMsg( 'passwordtooshort', + throw new PasswordError( wfMsgExt( 'passwordtooshort', array( 'parsemag' ), $wgMinimalPasswordLength ) ); } } @@ -1438,7 +1507,7 @@ class User { if( !$wgAuth->setPassword( $this, $str ) ) { throw new PasswordError( wfMsg( 'externaldberror' ) ); } - + $this->setInternalPassword( $str ); return true; @@ -1448,21 +1517,27 @@ class User { * Set the password and reset the random token no matter * what. * - * @param string $str + * @param $str string */ function setInternalPassword( $str ) { $this->load(); $this->setToken(); - + if( $str === null ) { // Save an invalid hash... $this->mPassword = ''; } else { - $this->mPassword = $this->encryptPassword( $str ); + $this->mPassword = self::crypt( $str ); } $this->mNewpassword = ''; $this->mNewpassTime = null; } + + function getToken() { + $this->load(); + return $this->mToken; + } + /** * Set the random token (used for persistent authentication) * Called from loadDefaults() among other places. @@ -1496,7 +1571,7 @@ class User { */ function setNewpassword( $str, $throttle = true ) { $this->load(); - $this->mNewpassword = $this->encryptPassword( $str ); + $this->mNewpassword = self::crypt( $str ); if ( $throttle ) { $this->mNewpassTime = wfTimestampNow(); } @@ -1515,20 +1590,23 @@ class User { $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600; return time() < $expiry; } - + function getEmail() { $this->load(); + wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) ); return $this->mEmail; } function getEmailAuthenticationTimestamp() { $this->load(); + wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) ); return $this->mEmailAuthenticated; } function setEmail( $str ) { $this->load(); $this->mEmail = $str; + wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) ); } function getRealName() { @@ -1542,8 +1620,8 @@ class User { } /** - * @param string $oname The option to check - * @param string $defaultOverride A default value returned if the option does not exist + * @param $oname String: the option to check + * @param $defaultOverride String: A default value returned if the option does not exist * @return string */ function getOption( $oname, $defaultOverride = '' ) { @@ -1564,7 +1642,7 @@ class User { } /** - * Get the user's date preference, including some important migration for + * Get the user's date preference, including some important migration for * old user rows. */ function getDatePreference() { @@ -1581,17 +1659,17 @@ class User { } /** - * @param string $oname The option to check + * @param $oname String: 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. + * @param $oname String: the option to check + * @param $default Int: optional value to return if option is unset/blank. * @return int */ function getIntOption( $oname, $default=0 ) { @@ -1613,9 +1691,16 @@ class User { } // 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 ); + 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; } @@ -1623,6 +1708,8 @@ class User { if ( is_null( $this->mRights ) ) { $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() ); wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) ); + // Force reindexation of rights when a hook has unset one of them + $this->mRights = array_values( $this->mRights ); } return $this->mRights; } @@ -1639,17 +1726,16 @@ class User { /** * Get the list of implicit group memberships this user has. - * This includes all explicit groups, plus 'user' if logged in - * and '*' for all accounts. - * @param boolean $recache Don't use the cache + * This includes all explicit groups, plus 'user' if logged in, + * '*' for all accounts and autopromoted groups + * @param $recache Boolean: don't use the cache * @return array of strings */ function getEffectiveGroups( $recache = false ) { if ( $recache || is_null( $this->mEffectiveGroups ) ) { - $this->load(); - $this->mEffectiveGroups = $this->mGroups; + $this->mEffectiveGroups = $this->getGroups(); $this->mEffectiveGroups[] = '*'; - if( $this->mId ) { + if( $this->getId() ) { $this->mEffectiveGroups[] = 'user'; $this->mEffectiveGroups = array_unique( array_merge( @@ -1663,28 +1749,27 @@ class User { } return $this->mEffectiveGroups; } - + /* Return the edit count for the user. This is where User::edits should have been */ function getEditCount() { if ($this->mId) { if ( !isset( $this->mEditCount ) ) { /* Populate the count, if it has not been populated yet */ $this->mEditCount = User::edits($this->mId); - } + } return $this->mEditCount; } else { /* nil */ return null; } } - + /** * Add the user to the given group. * This takes immediate effect. - * @param string $group + * @param $group string */ function addGroup( $group ) { - $this->load(); $dbw = wfGetDB( DB_MASTER ); if( $this->getId() ) { $dbw->insert( 'user_groups', @@ -1696,6 +1781,7 @@ class User { array( 'IGNORE' ) ); } + $this->loadGroups(); $this->mGroups[] = $group; $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) ); @@ -1705,7 +1791,7 @@ class User { /** * Remove the user from the given group. * This takes immediate effect. - * @param string $group + * @param $group string */ function removeGroup( $group ) { $this->load(); @@ -1717,6 +1803,7 @@ class User { ), 'User::removeGroup' ); + $this->loadGroups(); $this->mGroups = array_diff( $this->mGroups, array( $group ) ); $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) ); @@ -1749,12 +1836,13 @@ class User { * @deprecated */ function isBot() { + wfDeprecated( __METHOD__ ); return $this->isAllowed( 'bot' ); } /** * Check if user is allowed to access a feature / make an action - * @param string $action Action to be checked + * @param $action String: action to be checked * @return boolean True: action is allowed, False: action should not be allowed */ function isAllowed($action='') { @@ -1765,6 +1853,24 @@ class User { return in_array( $action, $this->getRights() ); } + /** + * Check whether to enable recent changes patrol features for this user + * @return bool + */ + public function useRCPatrol() { + global $wgUseRCPatrol; + return( $wgUseRCPatrol && ($this->isAllowed('patrol') || $this->isAllowed('patrolmarks')) ); + } + + /** + * Check whether to enable recent changes patrol features for this user + * @return bool + */ + public function useNPPatrol() { + global $wgUseRCPatrol, $wgUseNPPatrol; + return( ($wgUseRCPatrol || $wgUseNPPatrol) && ($this->isAllowed('patrol') || $this->isAllowed('patrolmarks')) ); + } + /** * Load a skin if it doesn't exist or return it * @todo FIXME : need to check the old failback system [AV] @@ -1785,7 +1891,7 @@ class User { } /**#@+ - * @param string $title Article title to look at + * @param $title Title: article title to look at */ /** @@ -1821,7 +1927,7 @@ class User { * the next change of the page if it's watched etc. */ function clearNotification( &$title ) { - global $wgUser, $wgUseEnotif; + global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker; # Do nothing if the database is locked to writes if( wfReadOnly() ) { @@ -1835,7 +1941,7 @@ class User { $this->setNewtalk( false ); } - if( !$wgUseEnotif ) { + if( !$wgUseEnotif && !$wgShowUpdatedMarker ) { return; } @@ -1852,7 +1958,7 @@ class User { $title->getText() == $wgUser->getName()) { $watched = true; - } elseif ( $this->getID() == $wgUser->getID() ) { + } elseif ( $this->getId() == $wgUser->getId() ) { $watched = $title->userIsWatching(); } else { $watched = true; @@ -1869,7 +1975,7 @@ class User { 'wl_title' => $title->getDBkey(), 'wl_namespace' => $title->getNamespace(), 'wl_user' => $this->getID() - ), 'User::clearLastVisited' + ), __METHOD__ ); } } @@ -1881,17 +1987,15 @@ class User { * If e-notif e-mails are on, they will receive notification mails on * the next change of any watched page. * - * @param int $currentUser user ID number - * @public + * @param $currentUser Int: user ID number */ function clearAllNotifications( $currentUser ) { - global $wgUseEnotif; - if ( !$wgUseEnotif ) { + global $wgUseEnotif, $wgShowUpdatedMarker; + if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) { $this->setNewtalk( false ); return; } if( $currentUser != 0 ) { - $dbw = wfGetDB( DB_MASTER ); $dbw->update( 'watchlist', array( /* SET */ @@ -1900,8 +2004,7 @@ class User { 'wl_user' => $currentUser ), __METHOD__ ); - - # we also need to clear here the "you have new message" notification for the own user_talk page + # We also need to clear here the "you have new message" notification for the own user_talk page # This is cleared one page view later in Article::viewUpdates(); } } @@ -1936,24 +2039,73 @@ class User { } } } + + protected function setCookie( $name, $value, $exp=0 ) { + global $wgCookiePrefix,$wgCookieDomain,$wgCookieSecure,$wgCookieExpiration, $wgCookieHttpOnly; + if( $exp == 0 ) { + $exp = time() + $wgCookieExpiration; + } + $httpOnlySafe = wfHttpOnlySafe(); + wfDebugLog( 'cookie', + 'setcookie: "' . implode( '", "', + array( + $wgCookiePrefix . $name, + $value, + $exp, + '/', + $wgCookieDomain, + $wgCookieSecure, + $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' ); + if( $httpOnlySafe && isset( $wgCookieHttpOnly ) ) { + setcookie( $wgCookiePrefix . $name, + $value, + $exp, + '/', + $wgCookieDomain, + $wgCookieSecure, + $wgCookieHttpOnly ); + } else { + // setcookie() fails on PHP 5.1 if you give it future-compat paramters. + // stab stab! + setcookie( $wgCookiePrefix . $name, + $value, + $exp, + '/', + $wgCookieDomain, + $wgCookieSecure ); + } + } + + protected function clearCookie( $name ) { + $this->setCookie( $name, '', time() - 86400 ); + } function setCookies() { - global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix; $this->load(); if ( 0 == $this->mId ) return; - $exp = time() + $wgCookieExpiration; - - $_SESSION['wsUserID'] = $this->mId; - setcookie( $wgCookiePrefix.'UserID', $this->mId, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure ); - - $_SESSION['wsUserName'] = $this->getName(); - setcookie( $wgCookiePrefix.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure ); - - $_SESSION['wsToken'] = $this->mToken; + $session = array( + 'wsUserID' => $this->mId, + 'wsToken' => $this->mToken, + 'wsUserName' => $this->getName() + ); + $cookies = array( + 'UserID' => $this->mId, + 'UserName' => $this->getName(), + ); if ( 1 == $this->getOption( 'rememberpassword' ) ) { - setcookie( $wgCookiePrefix.'Token', $this->mToken, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure ); + $cookies['Token'] = $this->mToken; } else { - setcookie( $wgCookiePrefix.'Token', '', time() - 3600 ); + $cookies['Token'] = false; + } + + wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) ); + $_SESSION = $session + $_SESSION; + foreach ( $cookies as $name => $value ) { + if ( $value === false ) { + $this->clearCookie( $name ); + } else { + $this->setCookie( $name, $value ); + } } } @@ -1964,7 +2116,6 @@ class User { global $wgUser; if( wfRunHooks( 'UserLogout', array(&$this) ) ) { $this->doLogout(); - wfRunHooks( 'UserLogoutComplete', array(&$wgUser) ); } } @@ -1973,16 +2124,15 @@ class User { * Clears the cookies and session, resets the instance cache */ function doLogout() { - global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix; $this->clearInstanceCache( 'defaults' ); $_SESSION['wsUserID'] = 0; - setcookie( $wgCookiePrefix.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure ); - setcookie( $wgCookiePrefix.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure ); + $this->clearCookie( 'UserID' ); + $this->clearCookie( 'Token' ); # Remember when user logged out, to prevent seeing cached pages - setcookie( $wgCookiePrefix.'LoggedOut', wfTimestampNow(), time() + 86400, $wgCookiePath, $wgCookieDomain, $wgCookieSecure ); + $this->setCookie( 'LoggedOut', wfTimestampNow(), time() + 86400 ); } /** @@ -1993,7 +2143,7 @@ class User { $this->load(); if ( wfReadOnly() ) { return; } if ( 0 == $this->mId ) { return; } - + $this->mTouched = self::newTouchedTimestamp(); $dbw = wfGetDB( DB_MASTER ); @@ -2008,21 +2158,23 @@ class User { 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ), 'user_options' => $this->encodeOptions(), 'user_touched' => $dbw->timestamp($this->mTouched), - 'user_token' => $this->mToken + 'user_token' => $this->mToken, + 'user_email_token' => $this->mEmailToken, + 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ), ), array( /* WHERE */ 'user_id' => $this->mId ), __METHOD__ ); + wfRunHooks( 'UserSaveSettings', array( $this ) ); $this->clearSharedCache(); } - /** - * Checks if a user with the given name exists, returns the ID + * Checks if a user with the given name exists, returns the ID. */ function idForName() { $s = trim( $this->getName() ); - if ( 0 == strcmp( '', $s ) ) return 0; + if ( $s === '' ) return 0; $dbr = wfGetDB( DB_SLAVE ); $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ ); @@ -2035,8 +2187,8 @@ class User { /** * Add a user to the database, return the user object * - * @param string $name The user's name - * @param array $params Associative array of non-default parameters to save to the database: + * @param $name String: the user's name + * @param $params Associative array of non-default parameters to save to the database: * password The user's password. Password logins will be disabled if this is omitted. * newpassword A temporary password mailed to the user * email The user's email address @@ -2082,7 +2234,7 @@ class User { } return $newUser; } - + /** * Add an existing user object to the database */ @@ -2184,7 +2336,6 @@ class User { /** * Determine if the user is blocked from using Special:Emailuser. * - * @public * @return boolean */ function isBlockedFromEmailuser() { @@ -2199,13 +2350,14 @@ class User { /** * @deprecated */ - function setLoaded( $loaded ) {} + function setLoaded( $loaded ) { + wfDeprecated( __METHOD__ ); + } /** * Get this user's personal page title. * * @return Title - * @public */ function getUserPage() { return Title::makeTitle( NS_USER, $this->getName() ); @@ -2215,7 +2367,6 @@ class User { * Get this user's talk page title. * * @return Title - * @public */ function getTalkPage() { $title = $this->getUserPage(); @@ -2244,10 +2395,36 @@ class User { function isNewbie() { return !$this->isAllowed( 'autoconfirmed' ); } + + /** + * Is the user active? We check to see if they've made at least + * X number of edits in the last Y days. + * + * @return bool true if the user is active, false if not + */ + public function isActiveEditor() { + global $wgActiveUserEditCount, $wgActiveUserDays; + $dbr = wfGetDB( DB_SLAVE ); + + // Stolen without shame from RC + $cutoff_unixtime = time() - ( $wgActiveUserDays * 86400 ); + $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime % 86400 ); + $oldTime = $dbr->addQuotes( $dbr->timestamp( $cutoff_unixtime ) ); + + $res = $dbr->select( 'revision', '1', + array( 'rev_user_text' => $this->getName(), "rev_timestamp > $oldTime"), + __METHOD__, + array('LIMIT' => $wgActiveUserEditCount ) ); + + $count = $dbr->numRows($res); + $dbr->freeResult($res); + + return $count == $wgActiveUserEditCount; + } /** * Check to see if the given clear-text password is one of the accepted passwords - * @param string $password User password. + * @param $password String: user password. * @return bool True if the given password is correct otherwise False. */ function checkPassword( $password ) { @@ -2272,28 +2449,26 @@ class User { /* Auth plugin doesn't allow local authentication for this user name */ return false; } - $ep = $this->encryptPassword( $password ); - if ( 0 == strcmp( $ep, $this->mPassword ) ) { + if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) { return true; } elseif ( function_exists( 'iconv' ) ) { # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted # Check for this with iconv - $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) ); - if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) { + $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ); + if ( self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId ) ) { return true; } } return false; } - + /** * Check if the given clear-text password matches the temporary password * sent by e-mail for password reset operations. * @return bool */ function checkTemporaryPassword( $plaintext ) { - $hash = $this->encryptPassword( $plaintext ); - return $hash === $this->mNewpassword; + return self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ); } /** @@ -2302,10 +2477,9 @@ class User { * login credentials aren't being hijacked with a foreign form * submission. * - * @param mixed $salt - Optional function-specific data for hash. - * Use a string or an array of strings. + * @param $salt Mixed: optional function-specific data for hash. + * Use a string or an array of strings. * @return string - * @public */ function editToken( $salt = '' ) { if ( $this->isAnon() ) { @@ -2340,10 +2514,9 @@ class User { * user's own login session, not a form submission from a third-party * site. * - * @param string $val - the input value to compare - * @param string $salt - Optional function-specific data for hash + * @param $val String: the input value to compare + * @param $salt String: optional function-specific data for hash * @return bool - * @public */ function matchEditToken( $val, $salt = '' ) { $sessionToken = $this->editToken( $salt ); @@ -2362,33 +2535,42 @@ class User { } /** - * Generate a new e-mail confirmation token and send a confirmation + * Generate a new e-mail confirmation token and send a confirmation/invalidation * mail to the user's given address. * + * Calls saveSettings() internally; as it has side effects, not committing changes + * would be pretty silly. + * * @return mixed True on success, a WikiError object on failure. */ function sendConfirmationMail() { - global $wgContLang; + global $wgLang; $expiration = null; // gets passed-by-ref and defined in next line. - $url = $this->confirmationTokenUrl( $expiration ); + $token = $this->confirmationToken( $expiration ); + $url = $this->confirmationTokenUrl( $token ); + $invalidateURL = $this->invalidationTokenUrl( $token ); + $this->saveSettings(); + return $this->sendMail( wfMsg( 'confirmemail_subject' ), wfMsg( 'confirmemail_body', wfGetIP(), $this->getName(), $url, - $wgContLang->timeanddate( $expiration, false ) ) ); + $wgLang->timeanddate( $expiration, false ), + $invalidateURL ) ); } /** * Send an e-mail to this user's account. Does not check for * confirmed status or validity. * - * @param string $subject - * @param string $body - * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise. + * @param $subject string + * @param $body string + * @param $from string: optional from address; default $wgPasswordSender will be used otherwise. + * @param $replyto string * @return mixed True on success, a WikiError object on failure. */ - function sendMail( $subject, $body, $from = null ) { + function sendMail( $subject, $body, $from = null, $replyto = null ) { if( is_null( $from ) ) { global $wgPasswordSender; $from = $wgPasswordSender; @@ -2396,18 +2578,16 @@ class User { $to = new MailAddress( $this ); $sender = new MailAddress( $from ); - $error = UserMailer::send( $to, $sender, $subject, $body ); - - if( $error == '' ) { - return true; - } else { - return new WikiError( $error ); - } + return UserMailer::send( $to, $sender, $subject, $body, $replyto ); } /** * Generate, store, and return a new e-mail confirmation code. * A hash (unsalted since it's used as a key) is stored. + * + * Call saveSettings() after calling this function to commit + * this change to the database. + * * @param &$expiration mixed output: accepts the expiration time * @return string * @private @@ -2416,50 +2596,91 @@ class User { $now = time(); $expires = $now + 7 * 24 * 60 * 60; $expiration = wfTimestamp( TS_MW, $expires ); - $token = $this->generateToken( $this->mId . $this->mEmail . $expires ); $hash = md5( $token ); - - $dbw = wfGetDB( DB_MASTER ); - $dbw->update( 'user', - array( 'user_email_token' => $hash, - 'user_email_token_expires' => $dbw->timestamp( $expires ) ), - array( 'user_id' => $this->mId ), - __METHOD__ ); - + $this->load(); + $this->mEmailToken = $hash; + $this->mEmailTokenExpires = $expiration; return $token; } /** - * Generate and store a new e-mail confirmation token, and return - * the URL the user can use to confirm. - * @param &$expiration mixed output: accepts the expiration time + * Return a URL the user can use to confirm their email address. + * @param $token accepts the email confirmation token * @return string * @private */ - function confirmationTokenUrl( &$expiration ) { - $token = $this->confirmationToken( $expiration ); - $title = SpecialPage::getTitleFor( 'Confirmemail', $token ); - return $title->getFullUrl(); + function confirmationTokenUrl( $token ) { + return $this->getTokenUrl( 'ConfirmEmail', $token ); + } + /** + * Return a URL the user can use to invalidate their email address. + * @param $token accepts the email confirmation token + * @return string + * @private + */ + function invalidationTokenUrl( $token ) { + return $this->getTokenUrl( 'Invalidateemail', $token ); + } + + /** + * Internal function to format the e-mail validation/invalidation URLs. + * This uses $wgArticlePath directly as a quickie hack to use the + * hardcoded English names of the Special: pages, for ASCII safety. + * + * Since these URLs get dropped directly into emails, using the + * short English names avoids insanely long URL-encoded links, which + * also sometimes can get corrupted in some browsers/mailers + * (bug 6957 with Gmail and Internet Explorer). + */ + protected function getTokenUrl( $page, $token ) { + global $wgArticlePath; + return wfExpandUrl( + str_replace( + '$1', + "Special:$page/$token", + $wgArticlePath ) ); } /** - * Mark the e-mail address confirmed and save. + * Mark the e-mail address confirmed. + * + * Call saveSettings() after calling this function to commit the change. */ function confirmEmail() { + $this->setEmailAuthenticationTimestamp( wfTimestampNow() ); + return true; + } + + /** + * Invalidate the user's email confirmation, unauthenticate the email + * if it was already confirmed. + * + * Call saveSettings() after calling this function to commit the change. + */ + function invalidateEmail() { $this->load(); - $this->mEmailAuthenticated = wfTimestampNow(); - $this->saveSettings(); + $this->mEmailToken = null; + $this->mEmailTokenExpires = null; + $this->setEmailAuthenticationTimestamp( null ); return true; } + function setEmailAuthenticationTimestamp( $timestamp ) { + $this->load(); + $this->mEmailAuthenticated = $timestamp; + wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) ); + } + /** * Is this user allowed to send e-mails within limits of current * site configuration? * @return bool */ function canSendEmail() { - return $this->isEmailConfirmed(); + $canSend = $this->isEmailConfirmed(); + wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) ); + return $canSend; } /** @@ -2468,7 +2689,7 @@ class User { * @return bool */ function canReceiveEmail() { - return $this->canSendEmail() && !$this->getOption( 'disablemail' ); + return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' ); } /** @@ -2497,7 +2718,7 @@ class User { return $confirmed; } } - + /** * Return true if there is an outstanding request for e-mail confirmation. * @return bool @@ -2509,7 +2730,7 @@ class User { $this->mEmailToken && $this->mEmailTokenExpires > wfTimestamp(); } - + /** * Get the timestamp of account creation, or false for * non-existent/anonymous user accounts @@ -2523,9 +2744,8 @@ class User { } /** - * @param array $groups list of groups + * @param $groups Array: list of groups * @return array list of permission key names for given groups combined - * @static */ static function getGroupPermissions( $groups ) { global $wgGroupPermissions; @@ -2540,9 +2760,8 @@ class User { } /** - * @param string $group key name + * @param $group String: key name * @return string localized descriptive name for group, if provided - * @static */ static function getGroupName( $group ) { global $wgMessageCache; @@ -2555,9 +2774,8 @@ class User { } /** - * @param string $group key name + * @param $group String: key name * @return string localized descriptive name for member of a group, if provided - * @static */ static function getGroupMember( $group ) { global $wgMessageCache; @@ -2571,11 +2789,10 @@ class User { /** * Return the set of defined explicit groups. - * The *, 'user', 'autoconfirmed' and 'emailconfirmed' - * groups are not included, as they are defined - * automatically, not in the database. + * The implicit groups (by default *, 'user' and 'autoconfirmed') + * are not included, as they are defined automatically, + * not in the database. * @return array - * @static */ static function getAllGroups() { global $wgGroupPermissions; @@ -2585,6 +2802,22 @@ class User { ); } + /** + * Get a list of all available permissions + */ + static function getAllRights() { + if ( self::$mAllRights === false ) { + global $wgAvailableRights; + if ( count( $wgAvailableRights ) ) { + self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) ); + } else { + self::$mAllRights = self::$mCoreRights; + } + wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) ); + } + return self::$mAllRights; + } + /** * Get a list of implicit groups * @@ -2655,7 +2888,7 @@ class User { return $text; } } - + /** * Increment the user's edit-count field. * Will have no effect for anonymous users. @@ -2667,7 +2900,7 @@ class User { array( 'user_editcount=user_editcount+1' ), array( 'user_id' => $this->getId() ), __METHOD__ ); - + // Lazy initialization check... if( $dbw->affectedRows() == 0 ) { // Pull from a slave to be less cruel to servers @@ -2677,7 +2910,7 @@ class User { 'COUNT(rev_user)', array( 'rev_user' => $this->getId() ), __METHOD__ ); - + // Now here's a goddamn hack... if( $dbr !== $dbw ) { // If we actually have a slave server, the count is @@ -2689,7 +2922,7 @@ class User { // count we just read includes the revision that was // just added in the working transaction. } - + $dbw->update( 'user', array( 'user_editcount' => $count ), array( 'user_id' => $this->getId() ), @@ -2699,7 +2932,72 @@ class User { // edit count in user cache too $this->invalidateCache(); } -} + + static function getRightDescription( $right ) { + global $wgMessageCache; + $wgMessageCache->loadAllMessages(); + $key = "right-$right"; + $name = wfMsg( $key ); + return $name == '' || wfEmptyMsg( $key, $name ) + ? $right + : $name; + } + + /** + * Make an old-style password hash + * + * @param $password String: plain-text password + * @param $userId String: user ID + */ + static function oldCrypt( $password, $userId ) { + global $wgPasswordSalt; + if ( $wgPasswordSalt ) { + return md5( $userId . '-' . md5( $password ) ); + } else { + return md5( $password ); + } + } + /** + * Make a new-style password hash + * + * @param $password String: plain-text password + * @param $salt String: salt, may be random or the user ID. False to generate a salt. + */ + static function crypt( $password, $salt = false ) { + global $wgPasswordSalt; + if($wgPasswordSalt) { + if ( $salt === false ) { + $salt = substr( wfGenerateToken(), 0, 8 ); + } + return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) ); + } else { + return ':A:' . md5( $password); + } + } + /** + * Compare a password hash with a plain-text password. Requires the user + * ID if there's a chance that the hash is an old-style hash. + * + * @param $hash String: password hash + * @param $password String: plain-text password to compare + * @param $userId String: user ID for old-style password salt + */ + static function comparePasswords( $hash, $password, $userId = false ) { + $m = false; + $type = substr( $hash, 0, 3 ); + if ( $type == ':A:' ) { + # Unsalted + return md5( $password ) === substr( $hash, 3 ); + } elseif ( $type == ':B:' ) { + # Salted + list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 ); + return md5( $salt.'-'.md5( $password ) ) == $realHash; + } else { + # Old-style + return self::oldCrypt( $password, $userId ) === $hash; + } + } +}