X-Git-Url: https://git.heureux-cyclage.org/?p=lhc%2Fweb%2Fwiklou.git;a=blobdiff_plain;f=includes%2FUser.php;h=bc06f979c838f3afa747e58654a42166029a663f;hp=13121045453b559cc61b9d2197d61f40ed6209b0;hb=1a8daf2c07e31337d83ee39b42873373023c8d40;hpb=efa4652fcf8004413875debdc42524e80404323c diff --git a/includes/User.php b/includes/User.php index 1312104545..bc06f979c8 100644 --- a/includes/User.php +++ b/includes/User.php @@ -30,7 +30,7 @@ define( 'USER_TOKEN_LENGTH', 32 ); * Int Serialized record version. * @ingroup Constants */ -define( 'MW_USER_VERSION', 8 ); +define( 'MW_USER_VERSION', 10 ); /** * String Some punctuation to prevent editing from broken text-mangling proxies. @@ -38,14 +38,6 @@ define( 'MW_USER_VERSION', 8 ); */ define( 'EDIT_TOKEN_SUFFIX', '+\\' ); -/** - * Thrown by User::setPassword() on error. - * @ingroup Exception - */ -class PasswordError extends MWException { - // NOP -} - /** * The User object encapsulates all of the user-specific settings (user_id, * name, rights, password, email address, options, last login time). Client @@ -56,7 +48,7 @@ class PasswordError extends MWException { * for rendering normal pages are set in the cookie to minimize use * of the database. */ -class User { +class User implements IDBAccessObject { /** * Global constants made accessible as class constants so that autoloader * magic can be used. @@ -70,20 +62,22 @@ class User { */ const MAX_WATCHED_ITEMS_CACHE = 100; + /** + * @var PasswordFactory Lazily loaded factory object for passwords + */ + private static $mPasswordFactory = null; + /** * Array of Strings List of member variables which are saved to the * shared cache (memcached). Any operation which changes the * corresponding database fields must call a cache-clearing function. * @showinitializer */ - static $mCacheVars = array( + protected static $mCacheVars = array( // user table 'mId', 'mName', 'mRealName', - 'mPassword', - 'mNewpassword', - 'mNewpassTime', 'mEmail', 'mTouched', 'mToken', @@ -104,7 +98,7 @@ class User { * "right-$right". * @showinitializer */ - static $mCoreRights = array( + protected static $mCoreRights = array( 'apihighlimits', 'autoconfirmed', 'autopatrol', @@ -124,6 +118,12 @@ class User { 'edit', 'editinterface', 'editprotected', + 'editmyoptions', + 'editmyprivateinfo', + 'editmyusercss', + 'editmyuserjs', + 'editmywatchlist', + 'editsemiprotected', 'editusercssjs', #deprecated 'editusercss', 'edituserjs', @@ -136,11 +136,13 @@ class User { 'minoredit', 'move', 'movefile', + 'move-categorypages', 'move-rootuserpages', 'move-subpages', 'nominornewtalk', 'noratelimit', 'override-export-depth', + 'pagelang', 'passwordreset', 'patrol', 'patrolmarks', @@ -164,31 +166,64 @@ class User { 'upload_by_url', 'userrights', 'userrights-interwiki', + 'viewmyprivateinfo', + 'viewmywatchlist', + 'viewsuppressed', 'writeapi', ); + /** * String Cached results of getAllRights() */ - static $mAllRights = false; + protected static $mAllRights = false; /** @name Cache variables */ //@{ - var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime, - $mEmail, $mTouched, $mToken, $mEmailAuthenticated, - $mEmailToken, $mEmailTokenExpires, $mRegistration, $mEditCount, - $mGroups, $mOptionOverrides; + public $mId; + + public $mName; + + public $mRealName; + + public $mPassword; + + public $mNewpassword; + + public $mNewpassTime; + + public $mEmail; + + public $mTouched; + + protected $mToken; + + public $mEmailAuthenticated; + + protected $mEmailToken; + + protected $mEmailTokenExpires; + + protected $mRegistration; + + protected $mEditCount; + + public $mGroups; + + protected $mOptionOverrides; + + protected $mPasswordExpires; //@} /** * Bool Whether the cache variables have been loaded. */ //@{ - var $mOptionsLoaded; + public $mOptionsLoaded; /** * Array with already loaded items or true if all items have been loaded. */ - private $mLoadedItems = array(); + protected $mLoadedItems = array(); //@} /** @@ -200,41 +235,55 @@ class User { * * Use the User::newFrom*() family of functions to set this. */ - var $mFrom; + public $mFrom; /** * Lazy-initialized variables, invalidated with clearInstanceCache */ - var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mRights, - $mBlockreason, $mEffectiveGroups, $mImplicitGroups, $mFormerGroups, $mBlockedGlobally, - $mLocked, $mHideName, $mOptions; + protected $mNewtalk; + + protected $mDatePreference; + + public $mBlockedby; + + protected $mHash; + + public $mRights; + + protected $mBlockreason; + + protected $mEffectiveGroups; + + protected $mImplicitGroups; + + protected $mFormerGroups; + + protected $mBlockedGlobally; + + protected $mLocked; + + public $mHideName; + + public $mOptions; /** * @var WebRequest */ private $mRequest; - /** - * @var Block - */ - var $mBlock; + /** @var Block */ + public $mBlock; - /** - * @var bool - */ - var $mAllowUsertalk; + /** @var bool */ + protected $mAllowUsertalk; - /** - * @var Block - */ + /** @var Block */ private $mBlockedFromCreateAccount = false; - /** - * @var Array - */ + /** @var array */ private $mWatchedItems = array(); - static $idCacheByName = array(); + public static $idCacheByName = array(); /** * Lightweight constructor for an anonymous user. @@ -246,14 +295,14 @@ class User { * @see newFromSession() * @see newFromRow() */ - function __construct() { + public function __construct() { $this->clearInstanceCache( 'defaults' ); } /** - * @return String + * @return string */ - function __toString() { + public function __toString() { return $this->getName(); } @@ -266,7 +315,7 @@ class User { } wfProfileIn( __METHOD__ ); - # Set it now to avoid infinite recursion in accessors + // Set it now to avoid infinite recursion in accessors $this->mLoadedItems = true; switch ( $this->mFrom ) { @@ -276,7 +325,7 @@ class User { case 'name': $this->mId = self::idFromName( $this->mName ); if ( !$this->mId ) { - # Nonexistent user placeholder object + // Nonexistent user placeholder object $this->loadDefaults( $this->mName ); } else { $this->loadFromId(); @@ -301,7 +350,7 @@ class User { /** * Load user table data, given mId has already been set. - * @return Bool false if the ID does not exist, true otherwise + * @return bool False if the ID does not exist, true otherwise */ public function loadFromId() { global $wgMemc; @@ -310,25 +359,25 @@ class User { return false; } - # Try cache + // Try cache $key = wfMemcKey( 'user', 'id', $this->mId ); $data = $wgMemc->get( $key ); - if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) { - # Object is expired, load from DB + if ( !is_array( $data ) || $data['mVersion'] != MW_USER_VERSION ) { + // Object is expired, load from DB $data = false; } if ( !$data ) { wfDebug( "User: cache miss for user {$this->mId}\n" ); - # Load from DB + // Load from DB if ( !$this->loadFromDatabase() ) { - # Can't load from ID, user is anonymous + // Can't load from ID, user is anonymous return false; } $this->saveToCache(); } else { wfDebug( "User: got user {$this->mId} from cache\n" ); - # Restore from cache + // Restore from cache foreach ( self::$mCacheVars as $name ) { $this->$name = $data[$name]; } @@ -370,14 +419,14 @@ class User { * you have both an ID and a name handy. * * @param string $name Username, validated by Title::newFromText() - * @param string|Bool $validate Validate username. Takes the same parameters as - * User::getCanonicalName(), except that true is accepted as an alias - * for 'valid', for BC. + * @param string|bool $validate Validate username. Takes the same parameters as + * User::getCanonicalName(), except that true is accepted as an alias + * for 'valid', for BC. * * @return User|bool User object, or false if the username is invalid - * (e.g. if it contains illegal characters or is an IP address). 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. + * (e.g. if it contains illegal characters or is an IP address). 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. */ public static function newFromName( $name, $validate = 'valid' ) { if ( $validate === true ) { @@ -387,7 +436,7 @@ class User { if ( $name === false ) { return false; } else { - # Create unloaded user object + // Create unloaded user object $u = new User; $u->mName = $name; $u->mFrom = 'name'; @@ -418,7 +467,7 @@ class User { * If the code is invalid or has expired, returns NULL. * * @param string $code Confirmation code - * @return User object, or null + * @return User|null */ public static function newFromConfirmationCode( $code ) { $dbr = wfGetDB( DB_SLAVE ); @@ -437,8 +486,8 @@ class User { * Create a new user object using data from session or cookies. If the * login credentials are invalid, the result is an anonymous user. * - * @param $request WebRequest object to use; $wgRequest will be used if omitted. - * @return User object + * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted. + * @return User */ public static function newFromSession( WebRequest $request = null ) { $user = new User; @@ -457,7 +506,7 @@ class User { * user_name and user_real_name are not provided because the whole row * will be loaded once more from the database when accessing them. * - * @param array $row A row from the user table + * @param stdClass $row A row from the user table * @param array $data Further data to load into the object (see User::loadFromRow for valid keys) * @return User */ @@ -472,7 +521,7 @@ class User { /** * Get the username corresponding to a given user ID * @param int $id User ID - * @return String|bool The corresponding username + * @return string|bool The corresponding username */ public static function whoIs( $id ) { return UserCache::singleton()->getProp( $id, 'name' ); @@ -482,7 +531,7 @@ class User { * Get the real name of a user given their user ID * * @param int $id User ID - * @return String|bool The corresponding user's real name + * @return string|bool The corresponding user's real name */ public static function whoIsReal( $id ) { return UserCache::singleton()->getProp( $id, 'real_name' ); @@ -491,12 +540,12 @@ class User { /** * Get database id given a user name * @param string $name Username - * @return Int|Null The corresponding user's ID, or null if user is nonexistent + * @return int|null The corresponding user's ID, or null if user is nonexistent */ public static function idFromName( $name ) { $nt = Title::makeTitleSafe( NS_USER, $name ); if ( is_null( $nt ) ) { - # Illegal name + // Illegal name return null; } @@ -505,7 +554,12 @@ class User { } $dbr = wfGetDB( DB_SLAVE ); - $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ ); + $s = $dbr->selectRow( + 'user', + array( 'user_id' ), + array( 'user_name' => $nt->getText() ), + __METHOD__ + ); if ( $s === false ) { $result = null; @@ -542,11 +596,12 @@ class User { * addresses like this, if we allowed accounts like this to be created * new users could get the old edits of these anonymous users. * - * @param string $name to match - * @return Bool + * @param string $name Name to match + * @return bool */ public static function isIP( $name ) { - return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name ) || IP::isIPv6( $name ); + return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name ) + || IP::isIPv6( $name ); } /** @@ -557,8 +612,8 @@ class User { * is longer than the maximum allowed username size or doesn't begin with * a capital letter. * - * @param string $name to match - * @return Bool + * @param string $name Name to match + * @return bool */ public static function isValidUserName( $name ) { global $wgContLang, $wgMaxNameChars; @@ -611,8 +666,8 @@ class User { * If an account already exists in this form, login will be blocked * by a failure to pass this function. * - * @param string $name to match - * @return Bool + * @param string $name Name to match + * @return bool */ public static function isUsableName( $name ) { global $wgReservedUsernames; @@ -648,8 +703,8 @@ class User { * Additional blacklisting may be added here rather than in * isValidUserName() to avoid disrupting existing accounts. * - * @param string $name to match - * @return Bool + * @param string $name String to match + * @return bool */ public static function isCreatableName( $name ) { global $wgInvalidUsernameCharacters; @@ -679,20 +734,48 @@ class User { * Is the input a valid password for this user? * * @param string $password Desired password - * @return Bool + * @return bool */ public function isValidPassword( $password ) { //simple boolean wrapper for getPasswordValidity return $this->getPasswordValidity( $password ) === true; } + /** * Given unvalidated password input, return error message on failure. * * @param string $password Desired password - * @return mixed: true on success, string or array of error message on failure + * @return bool|string|array True on success, string or array of error message on failure */ public function getPasswordValidity( $password ) { + $result = $this->checkPasswordValidity( $password ); + if ( $result->isGood() ) { + return true; + } else { + $messages = array(); + foreach ( $result->getErrorsByType( 'error' ) as $error ) { + $messages[] = $error['message']; + } + foreach ( $result->getErrorsByType( 'warning' ) as $warning ) { + $messages[] = $warning['message']; + } + if ( count( $messages ) === 1 ) { + return $messages[0]; + } + return $messages; + } + } + + /** + * Check if this is a valid password for this user. Status will be good if + * the password is valid, or have an array of error messages if not. + * + * @param string $password Desired password + * @return Status + * @since 1.23 + */ + public function checkPasswordValidity( $password ) { global $wgMinimalPasswordLength, $wgContLang; static $blockedLogins = array( @@ -700,80 +783,124 @@ class User { 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605 ); + $status = Status::newGood(); + $result = false; //init $result to false for the internal checks if ( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) ) { - return $result; + $status->error( $result ); + return $status; } if ( $result === false ) { if ( strlen( $password ) < $wgMinimalPasswordLength ) { - return 'passwordtooshort'; + $status->error( 'passwordtooshort', $wgMinimalPasswordLength ); + return $status; } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName ) ) { - return 'password-name-match'; - } elseif ( isset( $blockedLogins[$this->getName()] ) && $password == $blockedLogins[$this->getName()] ) { - return 'password-login-forbidden'; + $status->error( 'password-name-match' ); + return $status; + } elseif ( isset( $blockedLogins[$this->getName()] ) + && $password == $blockedLogins[$this->getName()] + ) { + $status->error( 'password-login-forbidden' ); + return $status; } else { - //it seems weird returning true here, but this is because of the + //it seems weird returning a Good status here, but this is because of the //initialization of $result to false above. If the hook is never run or it //doesn't modify $result, then we will likely get down into this if with //a valid password. - return true; + return $status; } } elseif ( $result === true ) { - return true; + return $status; } else { - return $result; //the isValidPassword hook set a string $result and returned true + $status->error( $result ); + return $status; //the isValidPassword hook set a string $result and returned true } } /** - * Does a string look like an e-mail address? - * - * This validates an email address using an HTML5 specification found at: - * http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address - * Which as of 2011-01-24 says: - * - * A valid e-mail address is a string that matches the ABNF production - * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined - * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section - * 3.5. - * - * This function is an implementation of the specification as requested in - * bug 22449. - * - * Client-side forms will use the same standard validation rules via JS or - * HTML 5 validation; additional restrictions can be enforced server-side - * by extensions via the 'isValidEmailAddr' hook. - * - * Note that this validation doesn't 100% match RFC 2822, but is believed - * to be liberal enough for wide use. Some invalid addresses will still - * pass validation here. - * - * @param string $addr E-mail address - * @return Bool - * @deprecated since 1.18 call Sanitizer::isValidEmail() directly + * Expire a user's password + * @since 1.23 + * @param int $ts Optional timestamp to convert, default 0 for the current time */ - public static function isValidEmailAddr( $addr ) { - wfDeprecated( __METHOD__, '1.18' ); - return Sanitizer::validateEmail( $addr ); + public function expirePassword( $ts = 0 ) { + $this->load(); + $timestamp = wfTimestamp( TS_MW, $ts ); + $this->mPasswordExpires = $timestamp; + $this->saveSettings(); + } + + /** + * Clear the password expiration for a user + * @since 1.23 + * @param bool $load Ensure user object is loaded first + */ + public function resetPasswordExpiration( $load = true ) { + global $wgPasswordExpirationDays; + if ( $load ) { + $this->load(); + } + $newExpire = null; + if ( $wgPasswordExpirationDays ) { + $newExpire = wfTimestamp( + TS_MW, + time() + ( $wgPasswordExpirationDays * 24 * 3600 ) + ); + } + // Give extensions a chance to force an expiration + wfRunHooks( 'ResetPasswordExpiration', array( $this, &$newExpire ) ); + $this->mPasswordExpires = $newExpire; + } + + /** + * Check if the user's password is expired. + * TODO: Put this and password length into a PasswordPolicy object + * @since 1.23 + * @return string|bool The expiration type, or false if not expired + * hard: A password change is required to login + * soft: Allow login, but encourage password change + * false: Password is not expired + */ + public function getPasswordExpired() { + global $wgPasswordExpireGrace; + $expired = false; + $now = wfTimestamp(); + $expiration = $this->getPasswordExpireDate(); + $expUnix = wfTimestamp( TS_UNIX, $expiration ); + if ( $expiration !== null && $expUnix < $now ) { + $expired = ( $expUnix + $wgPasswordExpireGrace < $now ) ? 'hard' : 'soft'; + } + return $expired; + } + + /** + * Get this user's password expiration date. Since this may be using + * the cached User object, we assume that whatever mechanism is setting + * the expiration date is also expiring the User cache. + * @since 1.23 + * @return string|bool The datestamp of the expiration, or null if not set + */ + public function getPasswordExpireDate() { + $this->load(); + return $this->mPasswordExpires; } /** * Given unvalidated user input, return a canonical username, or false if * the username is invalid. * @param string $name User input - * @param string|Bool $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 string|bool $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 * * @throws MWException * @return bool|string */ public static function getCanonicalName( $name, $validate = 'valid' ) { - # Force usernames to capital + // Force usernames to capital global $wgContLang; $name = $wgContLang->ucfirst( $name ); @@ -784,15 +911,15 @@ class User { return false; } - # Clean up name according to title rules + // Clean up name according to title rules $t = ( $validate === 'valid' ) ? Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name ); - # Check for invalid titles + // Check for invalid titles if ( is_null( $t ) ) { return false; } - # Reject various classes of invalid names + // Reject various classes of invalid names global $wgAuth; $name = $wgAuth->getCanonicalName( $t->getText() ); @@ -824,7 +951,7 @@ class User { * Count the number of edits of a user * * @param int $uid User ID to check - * @return Int the user's edit count + * @return int The user's edit count * * @deprecated since 1.21 in favour of User::getEditCount */ @@ -837,11 +964,12 @@ class User { /** * Return a random password. * - * @return String new random password + * @return string New random password */ public static function randomPassword() { global $wgMinimalPasswordLength; - // Decide the final password length based on our min password length, stopping at a minimum of 10 chars + // Decide the final password length based on our min password length, + // stopping at a minimum of 10 chars. $length = max( 10, $wgMinimalPasswordLength ); // Multiply by 1.25 to get the number of hex characters we need $length = $length * 1.25; @@ -857,15 +985,18 @@ class User { * @note This no longer clears uncached lazy-initialised properties; * the constructor does that instead. * - * @param $name string|bool + * @param string|bool $name */ public function loadDefaults( $name = false ) { wfProfileIn( __METHOD__ ); + $passwordFactory = self::getPasswordFactory(); + $this->mId = 0; $this->mName = $name; $this->mRealName = ''; - $this->mPassword = $this->mNewpassword = ''; + $this->mPassword = $passwordFactory->newFromCiphertext( null ); + $this->mNewpassword = $passwordFactory->newFromCiphertext( null ); $this->mNewpassTime = null; $this->mEmail = ''; $this->mOptionOverrides = null; @@ -882,6 +1013,8 @@ class User { $this->mEmailAuthenticated = null; $this->mEmailToken = ''; $this->mEmailTokenExpires = null; + $this->mPasswordExpires = null; + $this->resetPasswordExpiration( false ); $this->mRegistration = wfTimestamp( TS_MW ); $this->mGroups = array(); @@ -893,14 +1026,14 @@ class User { /** * Return whether an item has been loaded. * - * @param string $item item to check. Current possibilities: - * - id - * - name - * - realname + * @param string $item Item to check. Current possibilities: + * - id + * - name + * - realname * @param string $all 'all' to check if the whole object has been loaded - * or any other string to check if only the item is available (e.g. - * for optimisation) - * @return Boolean + * or any other string to check if only the item is available (e.g. + * for optimisation) + * @return bool */ public function isItemLoaded( $item, $all = 'all' ) { return ( $this->mLoadedItems === true && $all === 'all' ) || @@ -910,9 +1043,9 @@ class User { /** * Set that an item has been loaded * - * @param $item String + * @param string $item */ - private function setItemLoaded( $item ) { + protected function setItemLoaded( $item ) { if ( is_array( $this->mLoadedItems ) ) { $this->mLoadedItems[$item] = true; } @@ -920,7 +1053,7 @@ class User { /** * Load user data from the session or login cookie. - * @return Bool True if the user is logged in, false otherwise. + * @return bool True if the user is logged in, false otherwise. */ private function loadFromSession() { $result = null; @@ -959,27 +1092,30 @@ class User { $proposedUser = User::newFromId( $sId ); if ( !$proposedUser->isLoggedIn() ) { - # Not a valid ID + // Not a valid ID return false; } global $wgBlockDisablesLogin; if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) { - # User blocked and we've disabled blocked user logins + // User blocked and we've disabled blocked user logins return false; } if ( $request->getSessionData( 'wsToken' ) ) { - $passwordCorrect = ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) ); + $passwordCorrect = + ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) ); $from = 'session'; } elseif ( $request->getCookie( 'Token' ) ) { # Get the token from DB/cache and clean it up to remove garbage padding. # This deals with historical problems with bugs and the default column value. $token = rtrim( $proposedUser->getToken( false ) ); // correct token - $passwordCorrect = ( strlen( $token ) && $token === $request->getCookie( 'Token' ) ); + // Make comparison in constant time (bug 61346) + $passwordCorrect = strlen( $token ) + && hash_equals( $token, $request->getCookie( 'Token' ) ); $from = 'cookie'; } else { - # No session or persistent login cookie + // No session or persistent login cookie return false; } @@ -989,7 +1125,7 @@ class User { wfDebug( "User: logged in from $from\n" ); return true; } else { - # Invalid credentials + // Invalid credentials wfDebug( "User: can't log in from $from, invalid credentials\n" ); return false; } @@ -999,31 +1135,40 @@ class User { * Load user and user_group data from the database. * $this->mId must be set, this is how the user is identified. * - * @return Bool True if the user exists, false if the user is anonymous + * @param int $flags Supports User::READ_LOCKING + * @return bool True if the user exists, false if the user is anonymous */ - public function loadFromDatabase() { - # Paranoia + public function loadFromDatabase( $flags = 0 ) { + // Paranoia $this->mId = intval( $this->mId ); - /** Anonymous user */ + // Anonymous user if ( !$this->mId ) { $this->loadDefaults(); return false; } $dbr = wfGetDB( DB_MASTER ); - $s = $dbr->selectRow( 'user', self::selectFields(), array( 'user_id' => $this->mId ), __METHOD__ ); + $s = $dbr->selectRow( + 'user', + self::selectFields(), + array( 'user_id' => $this->mId ), + __METHOD__, + ( $flags & self::READ_LOCKING == self::READ_LOCKING ) + ? array( 'LOCK IN SHARE MODE' ) + : array() + ); wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) ); if ( $s !== false ) { - # Initialise user table data + // Initialise user table data $this->loadFromRow( $s ); $this->mGroups = null; // deferred $this->getEditCount(); // revalidation for nulls return true; } else { - # Invalid user_id + // Invalid user_id $this->mId = 0; $this->loadDefaults(); return false; @@ -1033,7 +1178,7 @@ class User { /** * Initialize this object from a row from the user table. * - * @param array $row Row from the user table to load. + * @param stdClass $row Row from the user table to load. * @param array $data Further user data to load into the object * * user_groups Array with groups out of the user_groups table @@ -1041,6 +1186,7 @@ class User { */ public function loadFromRow( $row, $data = null ) { $all = true; + $passwordFactory = self::getPasswordFactory(); $this->mGroups = null; // deferred @@ -1074,13 +1220,32 @@ class User { } if ( isset( $row->user_password ) ) { - $this->mPassword = $row->user_password; - $this->mNewpassword = $row->user_newpassword; + // Check for *really* old password hashes that don't even have a type + // The old hash format was just an md5 hex hash, with no type information + if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password ) ) { + $row->user_password = ":A:{$this->mId}:{$row->user_password}"; + } + + try { + $this->mPassword = $passwordFactory->newFromCiphertext( $row->user_password ); + } catch ( PasswordError $e ) { + wfDebug( 'Invalid password hash found in database.' ); + $this->mPassword = $passwordFactory->newFromCiphertext( null ); + } + + try { + $this->mNewpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword ); + } catch ( PasswordError $e ) { + wfDebug( 'Invalid password hash found in database.' ); + $this->mNewpassword = $passwordFactory->newFromCiphertext( null ); + } + $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time ); + $this->mPasswordExpires = wfTimestampOrNull( TS_MW, $row->user_password_expires ); + } + + if ( isset( $row->user_email ) ) { $this->mEmail = $row->user_email; - if ( isset( $row->user_options ) ) { - $this->decodeOptions( $row->user_options ); - } $this->mTouched = wfTimestamp( TS_MW, $row->user_touched ); $this->mToken = $row->user_token; if ( $this->mToken == '' ) { @@ -1111,7 +1276,7 @@ class User { /** * Load the data for this user object from another user object. * - * @param $user User + * @param User $user */ protected function loadFromUserObject( $user ) { $user->load(); @@ -1139,6 +1304,26 @@ class User { } } + /** + * Load the user's password hashes from the database + * + * This is usually called in a scenario where the actual User object was + * loaded from the cache, and then password comparison needs to be performed. + * Password hashes are not stored in memcached. + * + * @since 1.24 + */ + private function loadPasswords() { + if ( $this->getId() !== 0 && ( $this->mPassword === null || $this->mNewpassword === null ) ) { + $this->loadFromRow( wfGetDB( DB_MASTER )->selectRow( + 'user', + array( 'user_password', 'user_newpassword', 'user_newpass_time', 'user_password_expires' ), + array( 'user_id' => $this->getId() ), + __METHOD__ + ) ); + } + } + /** * Add the user to the group if he/she meets given criteria. * @@ -1147,23 +1332,27 @@ class User { * will not be re-added automatically. The user will also not lose the * group if they no longer meet the criteria. * - * @param string $event key in $wgAutopromoteOnce (each one has groups/criteria) + * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria) * * @return array Array of groups the user has been promoted to. * * @see $wgAutopromoteOnce */ public function addAutopromoteOnceGroups( $event ) { - global $wgAutopromoteOnceLogInRC; + global $wgAutopromoteOnceLogInRC, $wgAuth; $toPromote = array(); if ( $this->getId() ) { $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event ); if ( count( $toPromote ) ) { $oldGroups = $this->getGroups(); // previous groups + foreach ( $toPromote as $group ) { $this->addGroup( $group ); } + // update groups in external authentication database + $wgAuth->updateExternalDBGroups( $this, $toPromote ); + $newGroups = array_merge( $oldGroups, $toPromote ); // all groups $logEntry = new ManualLogEntry( 'rights', 'autopromote' ); @@ -1186,9 +1375,8 @@ class User { * Clear various cached data stored in this object. The cache of the user table * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given. * - * @param bool|String $reloadFrom Reload user and user_groups table data from a - * given source. May be "name", "id", "defaults", "session", or false for - * no reload. + * @param bool|string $reloadFrom Reload user and user_groups table data from a + * given source. May be "name", "id", "defaults", "session", or false for no reload. */ public function clearInstanceCache( $reloadFrom = false ) { $this->mNewtalk = -1; @@ -1213,7 +1401,7 @@ class User { * Combine the language default options with any site-specific options * and add the default language variants. * - * @return Array of String options + * @return array Array of String options */ public static function getDefaultOptions() { global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin; @@ -1227,13 +1415,15 @@ class User { } $defOpt = $wgDefaultUserOptions; - # default language setting - $defOpt['variant'] = $wgContLang->getCode(); + // Default language setting $defOpt['language'] = $wgContLang->getCode(); + foreach ( LanguageConverter::$languagesWithVariants as $langCode ) { + $defOpt[$langCode == $wgContLang->getCode() ? 'variant' : "variant-$langCode"] = $langCode; + } foreach ( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) { $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] ); } - $defOpt['skin'] = $wgDefaultSkin; + $defOpt['skin'] = Skin::normalizeKey( $wgDefaultSkin ); wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) ); @@ -1244,7 +1434,7 @@ class User { * Get a given default option value. * * @param string $opt Name of option to retrieve - * @return String Default option value + * @return string Default option value */ public static function getDefaultOption( $opt ) { $defOpts = self::getDefaultOptions(); @@ -1257,10 +1447,9 @@ class User { /** * Get blocking information - * @param bool $bFromSlave Whether to check the slave database first. To - * improve performance, non-critical checks are done - * against slaves. Check when actually saving should be - * done against master. + * @param bool $bFromSlave Whether to check the slave database first. + * To improve performance, non-critical checks are done against slaves. + * Check when actually saving should be done against master. */ private function getBlockedStatus( $bFromSlave = true ) { global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff; @@ -1288,14 +1477,14 @@ class User { $ip = null; } - # User/IP blocking + // User/IP blocking $block = Block::newFromTarget( $this, $ip, !$bFromSlave ); - # Proxy blocking + // Proxy blocking if ( !$block instanceof Block && $ip !== null && !$this->isAllowed( 'proxyunbannable' ) - && !in_array( $ip, $wgProxyWhitelist ) ) - { - # Local list + && !in_array( $ip, $wgProxyWhitelist ) + ) { + // Local list if ( self::isLocallyBlockedProxy( $ip ) ) { $block = new Block; $block->setBlocker( wfMessage( 'proxyblocker' )->text() ); @@ -1309,7 +1498,7 @@ class User { } } - # (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled + // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled if ( !$block instanceof Block && $wgApplyIpBlocksToXff && $ip !== null @@ -1351,14 +1540,13 @@ class User { * Whether the given IP is in a DNS blacklist. * * @param string $ip IP to check - * @param bool $checkWhitelist whether to check the whitelist first - * @return Bool True if blacklisted. + * @param bool $checkWhitelist Whether to check the whitelist first + * @return bool True if blacklisted. */ public function isDnsBlacklisted( $ip, $checkWhitelist = false ) { - global $wgEnableSorbs, $wgEnableDnsBlacklist, - $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist; + global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist; - if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs ) { + if ( !$wgEnableDnsBlacklist ) { return false; } @@ -1366,16 +1554,15 @@ class User { return false; } - $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl ); - return $this->inDnsBlacklist( $ip, $urls ); + return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls ); } /** * Whether the given IP is in a given DNS blacklist. * * @param string $ip IP to check - * @param string|array $bases of Strings: URL of the DNS blacklist - * @return Bool True if blacklisted. + * @param string|array $bases Array of Strings: URL of the DNS blacklist + * @return bool True if blacklisted. */ public function inDnsBlacklist( $ip, $bases ) { wfProfileIn( __METHOD__ ); @@ -1383,15 +1570,15 @@ class User { $found = false; // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170) if ( IP::isIPv4( $ip ) ) { - # Reverse IP, bug 21255 + // Reverse IP, bug 21255 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) ); foreach ( (array)$bases as $base ) { - # Make hostname - # If we have an access key, use that too (ProjectHoneypot, etc.) + // Make hostname + // If we have an access key, use that too (ProjectHoneypot, etc.) if ( is_array( $base ) ) { if ( count( $base ) >= 2 ) { - # Access key is 1, base URL is 0 + // Access key is 1, base URL is 0 $host = "{$base[1]}.$ipReversed.{$base[0]}"; } else { $host = "$ipReversed.{$base[0]}"; @@ -1400,15 +1587,15 @@ class User { $host = "$ipReversed.$base"; } - # Send query + // Send query $ipList = gethostbynamel( $host ); if ( $ipList ) { - wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" ); + wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" ); $found = true; break; } else { - wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base.\n" ); + wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." ); } } } @@ -1420,7 +1607,7 @@ class User { /** * Check if an IP address is in the local proxy list * - * @param $ip string + * @param string $ip * * @return bool */ @@ -1433,7 +1620,7 @@ class User { wfProfileIn( __METHOD__ ); if ( !is_array( $wgProxyList ) ) { - # Load from the specified file + // Load from the specified file $wgProxyList = array_map( 'trim', file( $wgProxyList ) ); } @@ -1442,7 +1629,7 @@ class User { } elseif ( array_search( $ip, $wgProxyList ) !== false ) { $ret = true; } elseif ( array_key_exists( $ip, $wgProxyList ) ) { - # Old-style flipped proxy list + // Old-style flipped proxy list $ret = true; } else { $ret = false; @@ -1454,7 +1641,7 @@ class User { /** * Is this user subject to rate limiting? * - * @return Bool True if rate limited + * @return bool True if rate limited */ public function isPingLimitable() { global $wgRateLimitsExcludedIPs; @@ -1471,16 +1658,20 @@ class User { * Primitive rate limits: enforce maximum actions per time period * to put a brake on flooding. * + * The method generates both a generic profiling point and a per action one + * (suffix being "-$action". + * * @note When using a shared cache like memcached, IP-address * last-hit counters will be shared across wikis. * * @param string $action Action to enforce; 'edit' if unspecified - * @return Bool True if a rate limiter was tripped + * @param int $incrBy Positive amount to increment counter by [defaults to 1] + * @return bool True if a rate limiter was tripped */ - public function pingLimiter( $action = 'edit' ) { - # Call the 'PingLimiter' hook + public function pingLimiter( $action = 'edit', $incrBy = 1 ) { + // Call the 'PingLimiter' hook $result = false; - if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result ) ) ) { + if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) { return $result; } @@ -1489,18 +1680,18 @@ class User { return false; } - # Some groups shouldn't trigger the ping limiter, ever + // Some groups shouldn't trigger the ping limiter, ever if ( !$this->isPingLimitable() ) { return false; } - global $wgMemc, $wgRateLimitLog; + global $wgMemc; wfProfileIn( __METHOD__ ); + wfProfileIn( __METHOD__ . '-' . $action ); $limits = $wgRateLimits[$action]; $keys = array(); $id = $this->getId(); - $ip = $this->getRequest()->getIP(); $userLimit = false; if ( isset( $limits['anon'] ) && $id == 0 ) { @@ -1515,12 +1706,23 @@ class User { $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie']; } if ( isset( $limits['ip'] ) ) { + $ip = $this->getRequest()->getIP(); $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip']; } - $matches = array(); - if ( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) { - $subnet = $matches[1]; - $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet']; + if ( isset( $limits['subnet'] ) ) { + $ip = $this->getRequest()->getIP(); + $matches = array(); + $subnet = false; + if ( IP::isIPv6( $ip ) ) { + $parts = IP::parseRange( "$ip/64" ); + $subnet = $parts[0]; + } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) { + // IPv4 + $subnet = $matches[1]; + } + if ( $subnet !== false ) { + $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet']; + } } } // Check for group-specific permissions @@ -1547,23 +1749,24 @@ class User { // Already pinged? if ( $count ) { if ( $count >= $max ) { - wfDebug( __METHOD__ . ": tripped! $key at $count $summary\n" ); - if ( $wgRateLimitLog ) { - wfSuppressWarnings(); - file_put_contents( $wgRateLimitLog, wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", FILE_APPEND ); - wfRestoreWarnings(); - } + wfDebugLog( 'ratelimit', "User '{$this->getName()}' " . + "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" ); $triggered = true; } else { wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" ); } } else { wfDebug( __METHOD__ . ": adding record for $key $summary\n" ); - $wgMemc->add( $key, 0, intval( $period ) ); // first ping + if ( $incrBy > 0 ) { + $wgMemc->add( $key, 0, intval( $period ) ); // first ping + } + } + if ( $incrBy > 0 ) { + $wgMemc->incr( $key, $incrBy ); } - $wgMemc->incr( $key ); } + wfProfileOut( __METHOD__ . '-' . $action ); wfProfileOut( __METHOD__ ); return $triggered; } @@ -1571,10 +1774,11 @@ class User { /** * Check if user is blocked * - * @param bool $bFromSlave Whether to check the slave database instead of the master - * @return Bool True if blocked, false otherwise + * @param bool $bFromSlave Whether to check the slave database instead of + * the master. Hacked from false due to horrible probs on site. + * @return bool True if blocked, false otherwise */ - public function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site + public function isBlocked( $bFromSlave = true ) { return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' ); } @@ -1592,19 +1796,19 @@ class User { /** * Check if user is blocked from editing a particular article * - * @param $title Title to check - * @param bool $bFromSlave whether to check the slave database instead of the master - * @return Bool + * @param Title $title Title to check + * @param bool $bFromSlave Whether to check the slave database instead of the master + * @return bool */ - function isBlockedFrom( $title, $bFromSlave = false ) { + public function isBlockedFrom( $title, $bFromSlave = false ) { global $wgBlockAllowsUTEdit; wfProfileIn( __METHOD__ ); $blocked = $this->isBlocked( $bFromSlave ); $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false ); - # If a user's name is suppressed, they cannot make edits anywhere - if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName() && - $title->getNamespace() == NS_USER_TALK ) { + // If a user's name is suppressed, they cannot make edits anywhere + if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName() + && $title->getNamespace() == NS_USER_TALK ) { $blocked = false; wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" ); } @@ -1617,7 +1821,7 @@ class User { /** * If user is blocked, return the name of the user who placed the block - * @return String name of blocker + * @return string Name of blocker */ public function blockedBy() { $this->getBlockedStatus(); @@ -1626,7 +1830,7 @@ class User { /** * If user is blocked, return the specified reason for the block - * @return String Blocking reason + * @return string Blocking reason */ public function blockedFor() { $this->getBlockedStatus(); @@ -1635,7 +1839,7 @@ class User { /** * If user is blocked, return the ID for the block - * @return Int Block ID + * @return int Block ID */ public function getBlockId() { $this->getBlockedStatus(); @@ -1648,7 +1852,7 @@ class User { * This is intended for quick UI checks. * * @param string $ip IP address, uses current client if none given - * @return Bool True if blocked, false otherwise + * @return bool True if blocked, false otherwise */ public function isBlockedGlobally( $ip = '' ) { if ( $this->mBlockedGlobally !== null ) { @@ -1669,13 +1873,14 @@ class User { /** * Check if user account is locked * - * @return Bool True if locked, false otherwise + * @return bool True if locked, false otherwise */ public function isLocked() { if ( $this->mLocked !== null ) { return $this->mLocked; } global $wgAuth; + StubObject::unstub( $wgAuth ); $authUser = $wgAuth->getUserInstance( $this ); $this->mLocked = (bool)$authUser->isLocked(); return $this->mLocked; @@ -1684,7 +1889,7 @@ class User { /** * Check if user account is hidden * - * @return Bool True if hidden, false otherwise + * @return bool True if hidden, false otherwise */ public function isHidden() { if ( $this->mHideName !== null ) { @@ -1693,6 +1898,7 @@ class User { $this->getBlockedStatus(); if ( !$this->mHideName ) { global $wgAuth; + StubObject::unstub( $wgAuth ); $authUser = $wgAuth->getUserInstance( $this ); $this->mHideName = (bool)$authUser->isHidden(); } @@ -1701,7 +1907,7 @@ class User { /** * Get the user's ID. - * @return Int The user's ID; 0 if the user is anonymous or nonexistent + * @return int The user's ID; 0 if the user is anonymous or nonexistent */ public function getId() { if ( $this->mId === null && $this->mName !== null && User::isIP( $this->mName ) ) { @@ -1725,16 +1931,16 @@ class User { /** * Get the user name, or the IP of an anonymous user - * @return String User's name or IP address + * @return string User's name or IP address */ public function getName() { if ( $this->isItemLoaded( 'name', 'only' ) ) { - # Special case optimisation + // Special case optimisation return $this->mName; } else { $this->load(); if ( $this->mName === false ) { - # Clean up IPs + // Clean up IPs $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() ); } return $this->mName; @@ -1761,7 +1967,7 @@ class User { /** * Get the user's name escaped by underscores. - * @return String Username escaped by underscores. + * @return string Username escaped by underscores. */ public function getTitleKey() { return str_replace( ' ', '_', $this->getName() ); @@ -1769,17 +1975,17 @@ class User { /** * Check if the user has new messages. - * @return Bool True if the user has new messages + * @return bool True if the user has new messages */ public function getNewtalk() { $this->load(); - # Load the newtalk status if it is unloaded (mNewtalk=-1) + // Load the newtalk status if it is unloaded (mNewtalk=-1) if ( $this->mNewtalk === -1 ) { $this->mNewtalk = false; # reset talk page status - # Check memcached separately for anons, who have no - # entire User object stored in there. + // Check memcached separately for anons, who have no + // entire User object stored in there. if ( !$this->mId ) { global $wgDisableAnonTalk; if ( $wgDisableAnonTalk ) { @@ -1807,11 +2013,17 @@ class User { } /** - * Return the revision and link for the oldest new talk page message for - * this user. - * Note: This function was designed to accomodate multiple talk pages, but + * Return the data needed to construct links for new talk page message + * alerts. If there are new messages, this will return an associative array + * with the following data: + * wiki: The database name of the wiki + * link: Root-relative link to the user's talk page + * rev: The last talk page revision that the user has seen or null. This + * is useful for building diff links. + * If there are no new messages, it returns an empty array. + * @note This function was designed to accomodate multiple talk pages, but * currently only returns a single link and revision. - * @return Array + * @return array */ public function getNewMessageLinks() { $talks = array(); @@ -1832,8 +2044,9 @@ class User { } /** - * Get the revision ID for the oldest new talk page message for this user - * @return Integer or null if there are no new messages + * Get the revision ID for the last talk page revision viewed by the talk + * page owner. + * @return int|null Revision ID or null */ public function getNewMessageRevisionId() { $newMessageRevisionId = null; @@ -1858,9 +2071,9 @@ class User { * * @see getNewtalk() * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise - * @param string|Int $id User's IP address for anonymous users, User ID otherwise - * @param bool $fromMaster true to fetch from the master, false for a slave - * @return Bool True if the user has new messages + * @param string|int $id User's IP address for anonymous users, User ID otherwise + * @param bool $fromMaster True to fetch from the master, false for a slave + * @return bool True if the user has new messages */ protected function checkNewtalk( $field, $id, $fromMaster = false ) { if ( $fromMaster ) { @@ -1876,9 +2089,9 @@ class User { /** * Add or update the new messages flag * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise - * @param string|Int $id User's IP address for anonymous users, User ID otherwise - * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null. - * @return Bool True if successful, false otherwise + * @param string|int $id User's IP address for anonymous users, User ID otherwise + * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null. + * @return bool True if successful, false otherwise */ protected function updateNewtalk( $field, $id, $curRev = null ) { // Get timestamp of the talk page revision prior to the current one @@ -1902,8 +2115,8 @@ class User { /** * Clear the new messages flag for the given user * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise - * @param string|Int $id User's IP address for anonymous users, User ID otherwise - * @return Bool True if successful, false otherwise + * @param string|int $id User's IP address for anonymous users, User ID otherwise + * @return bool True if successful, false otherwise */ protected function deleteNewtalk( $field, $id ) { $dbw = wfGetDB( DB_MASTER ); @@ -1922,7 +2135,8 @@ class User { /** * Update the 'You have new messages!' status. * @param bool $val Whether the user has new messages - * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null or !$val. + * @param Revision $curRev New, as yet unseen revision of the user talk + * page. Ignored if null or !$val. */ public function setNewtalk( $val, $curRev = null ) { if ( wfReadOnly() ) { @@ -1961,7 +2175,7 @@ class User { /** * Generate a current or new-future timestamp to be stored in the * user_touched field when we update things. - * @return String Timestamp in TS_MW format + * @return string Timestamp in TS_MW format */ private static function newTouchedTimestamp() { global $wgClockSkewFudge; @@ -1975,7 +2189,7 @@ class User { * * Called implicitly from invalidateCache() and saveSettings(). */ - private function clearSharedCache() { + public function clearSharedCache() { $this->load(); if ( $this->mId ) { global $wgMemc; @@ -2000,7 +2214,7 @@ class User { $userid = $this->mId; $touched = $this->mTouched; $method = __METHOD__; - $dbw->onTransactionIdle( function() use ( $dbw, $userid, $touched, $method ) { + $dbw->onTransactionIdle( function () use ( $dbw, $userid, $touched, $method ) { // Prevent contention slams by checking user_touched first $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) ); $needsPurge = $dbw->selectField( 'user', '1', @@ -2020,7 +2234,6 @@ class User { /** * Validate the cache for this account. * @param string $timestamp A timestamp in TS_MW format - * * @return bool */ public function validateCache( $timestamp ) { @@ -2030,7 +2243,7 @@ class User { /** * Get the user touched timestamp - * @return String timestamp + * @return string Timestamp */ public function getTouched() { $this->load(); @@ -2049,7 +2262,7 @@ class User { * a new password is set, for instance via e-mail. * * @param string $str New password to set - * @throws PasswordError on failure + * @throws PasswordError On failure * * @return bool */ @@ -2088,27 +2301,28 @@ class User { * Set the password and reset the random token unconditionally. * * @param string|null $str New password to set or null to set an invalid - * password hash meaning that the user will not be able to log in - * through the web interface. + * password hash meaning that the user will not be able to log in + * through the web interface. */ public function setInternalPassword( $str ) { - $this->load(); $this->setToken(); + $passwordFactory = self::getPasswordFactory(); if ( $str === null ) { - // Save an invalid hash... - $this->mPassword = ''; + $this->mPassword = $passwordFactory->newFromCiphertext( null ); } else { - $this->mPassword = self::crypt( $str ); + $this->mPassword = $passwordFactory->newFromPlaintext( $str ); } - $this->mNewpassword = ''; + + $this->mNewpassword = $passwordFactory->newFromCiphertext( null ); $this->mNewpassTime = null; } /** * Get the user's current token. - * @param bool $forceCreation Force the generation of a new token if the user doesn't have one (default=true for backwards compatibility) - * @return String Token + * @param bool $forceCreation Force the generation of a new token if the + * user doesn't have one (default=true for backwards compatibility). + * @return string Token */ public function getToken( $forceCreation = true ) { $this->load(); @@ -2136,21 +2350,28 @@ class User { /** * Set the password for a password reminder or new account email * - * @param string $str New password to set + * @param string $str New password to set or null to set an invalid + * password hash meaning that the user will not be able to use it * @param bool $throttle If true, reset the throttle timestamp to the present */ public function setNewpassword( $str, $throttle = true ) { $this->load(); - $this->mNewpassword = self::crypt( $str ); - if ( $throttle ) { - $this->mNewpassTime = wfTimestampNow(); + + if ( $str === null ) { + $this->mNewpassword = ''; + $this->mNewpassTime = null; + } else { + $this->mNewpassword = self::getPasswordFactory()->newFromPlaintext( $str ); + if ( $throttle ) { + $this->mNewpassTime = wfTimestampNow(); + } } } /** * Has password reminder email been sent within the last * $wgPasswordReminderResendTime hours? - * @return Bool + * @return bool */ public function isPasswordReminderThrottled() { global $wgPasswordReminderResendTime; @@ -2164,7 +2385,7 @@ class User { /** * Get the user's e-mail address - * @return String User's email address + * @return string User's email address */ public function getEmail() { $this->load(); @@ -2174,7 +2395,7 @@ class User { /** * Get the timestamp of the user's e-mail authentication - * @return String TS_MW timestamp + * @return string TS_MW timestamp */ public function getEmailAuthenticationTimestamp() { $this->load(); @@ -2218,11 +2439,11 @@ class User { $this->setEmail( $str ); if ( $str !== '' && $wgEmailAuthentication ) { - # Send a confirmation request to the new address if needed + // Send a confirmation request to the new address if needed $type = $oldaddr != '' ? 'changed' : 'set'; $result = $this->sendConfirmationMail( $type ); if ( $result->isGood() ) { - # Say the the caller that a confirmation mail has been sent + // Say the the caller that a confirmation mail has been sent $result->value = 'eauth'; } } else { @@ -2234,7 +2455,7 @@ class User { /** * Get the user's real name - * @return String User's real name + * @return string User's real name */ public function getRealName() { if ( !$this->isItemLoaded( 'realname' ) ) { @@ -2258,8 +2479,8 @@ class User { * * @param string $oname The option to check * @param string $defaultOverride A default value returned if the option does not exist - * @param bool $ignoreHidden = whether to ignore the effects of $wgHiddenPrefs - * @return String User's current value for the option + * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs + * @return string User's current value for the option * @see getBoolOption() * @see getIntOption() */ @@ -2272,7 +2493,7 @@ class User { # set it, and then it was disabled removing their ability to change it). But # we don't want to erase the preferences in the database in case the preference # is re-enabled again. So don't touch $mOptions, just override the returned value - if ( in_array( $oname, $wgHiddenPrefs ) && !$ignoreHidden ) { + if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) { return self::getDefaultOption( $oname ); } @@ -2312,7 +2533,7 @@ class User { * Get the user's current setting for a given option, as a boolean value. * * @param string $oname The option to check - * @return Bool User's current value for the option + * @return bool User's current value for the option * @see getOption() */ public function getBoolOption( $oname ) { @@ -2320,11 +2541,11 @@ class User { } /** - * Get the user's current setting for a given option, as a boolean value. + * Get the user's current setting for a given option, as an integer value. * * @param string $oname The option to check * @param int $defaultOverride A default value returned if the option does not exist - * @return Int User's current value for the option + * @return int User's current value for the option * @see getOption() */ public function getIntOption( $oname, $defaultOverride = 0 ) { @@ -2338,8 +2559,10 @@ class User { /** * Set the given option for a user. * + * You need to call saveSettings() to actually write to the database. + * * @param string $oname The option to set - * @param $val mixed New value to set + * @param mixed $val New value to set */ public function setOption( $oname, $val ) { $this->loadOptions(); @@ -2352,6 +2575,49 @@ class User { $this->mOptions[$oname] = $val; } + /** + * Get a token stored in the preferences (like the watchlist one), + * resetting it if it's empty (and saving changes). + * + * @param string $oname The option name to retrieve the token from + * @return string|bool User's current value for the option, or false if this option is disabled. + * @see resetTokenFromOption() + * @see getOption() + */ + public function getTokenFromOption( $oname ) { + global $wgHiddenPrefs; + if ( in_array( $oname, $wgHiddenPrefs ) ) { + return false; + } + + $token = $this->getOption( $oname ); + if ( !$token ) { + $token = $this->resetTokenFromOption( $oname ); + $this->saveSettings(); + } + return $token; + } + + /** + * Reset a token stored in the preferences (like the watchlist one). + * *Does not* save user's preferences (similarly to setOption()). + * + * @param string $oname The option name to reset the token in + * @return string|bool New token value, or false if this option is disabled. + * @see getTokenFromOption() + * @see setOption() + */ + public function resetTokenFromOption( $oname ) { + global $wgHiddenPrefs; + if ( in_array( $oname, $wgHiddenPrefs ) ) { + return false; + } + + $token = MWCryptRand::generateHex( 40 ); + $this->setOption( $oname, $token ); + return $token; + } + /** * Return a list of the types of user options currently returned by * User::getOptionKinds(). @@ -2363,6 +2629,8 @@ class User { * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type. * - 'userjs' - preferences with names starting with 'userjs-', intended to * be used by user scripts. + * - 'special' - "preferences" that are not accessible via User::getOptions + * or User::setOptions. * - 'unused' - preferences about which MediaWiki doesn't know anything. * These are usually legacy options, removed in newer versions. * @@ -2379,6 +2647,7 @@ class User { 'registered-multiselect', 'registered-checkmatrix', 'userjs', + 'special', 'unused' ); } @@ -2390,9 +2659,10 @@ class User { * See User::listOptionKinds for the list of valid option types that can be provided. * * @see User::listOptionKinds - * @param $context IContextSource - * @param array $options assoc. array with options keys to check as keys. Defaults to $this->mOptions. - * @return array the key => kind mapping data + * @param IContextSource $context + * @param array $options Assoc. array with options keys to check as keys. + * Defaults to $this->mOptions. + * @return array The key => kind mapping data */ public function getOptionKinds( IContextSource $context, $options = null ) { $this->loadOptions(); @@ -2403,6 +2673,13 @@ class User { $prefs = Preferences::getPreferences( $this, $context ); $mapping = array(); + // Pull out the "special" options, so they don't get converted as + // multiselect or checkmatrix. + $specialOptions = array_fill_keys( Preferences::getSaveBlacklist(), true ); + foreach ( $specialOptions as $name => $value ) { + unset( $prefs[$name] ); + } + // Multiselect and checkmatrix options are stored in the database with // one key per option, each having a boolean value. Extract those keys. $multiselectOptions = array(); @@ -2445,6 +2722,8 @@ class User { $mapping[$key] = 'registered-multiselect'; } elseif ( isset( $checkmatrixOptions[$key] ) ) { $mapping[$key] = 'registered-checkmatrix'; + } elseif ( isset( $specialOptions[$key] ) ) { + $mapping[$key] = 'special'; } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) { $mapping[$key] = 'userjs'; } else { @@ -2462,12 +2741,12 @@ class User { * Supported values are everything that can be reported by getOptionKinds() * and 'all', which forces a reset of *all* preferences and overrides everything else. * - * @param array|string $resetKinds which kinds of preferences to reset. Defaults to - * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ) - * for backwards-compatibility. - * @param $context IContextSource|null context source used when $resetKinds - * does not contain 'all', passed to getOptionKinds(). - * Defaults to RequestContext::getMain() when null. + * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to + * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ) + * for backwards-compatibility. + * @param IContextSource|null $context Context source used when $resetKinds + * does not contain 'all', passed to getOptionKinds(). + * Defaults to RequestContext::getMain() when null. */ public function resetOptions( $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ), @@ -2504,13 +2783,15 @@ class User { } } + wfRunHooks( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions, $resetKinds ) ); + $this->mOptions = $newOptions; $this->mOptionsLoaded = true; } /** * Get the user's preferred date format. - * @return String User's preferred date format + * @return string User's preferred date format */ public function getDatePreference() { // Important migration for old data rows @@ -2526,6 +2807,26 @@ class User { return $this->mDatePreference; } + /** + * Determine based on the wiki configuration and the user's options, + * whether this user must be over HTTPS no matter what. + * + * @return bool + */ + public function requiresHTTPS() { + global $wgSecureLogin; + if ( !$wgSecureLogin ) { + return false; + } else { + $https = $this->getBoolOption( 'prefershttps' ); + wfRunHooks( 'UserRequiresHTTPS', array( $this, &$https ) ); + if ( $https ) { + $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() ); + } + return $https; + } + } + /** * Get the user preferred stub threshold * @@ -2535,8 +2836,8 @@ class User { global $wgMaxArticleSize; # Maximum article size, in Kb $threshold = $this->getIntOption( 'stubthreshold' ); if ( $threshold > $wgMaxArticleSize * 1024 ) { - # If they have set an impossible value, disable the preference - # so we can use the parser cache again. + // If they have set an impossible value, disable the preference + // so we can use the parser cache again. $threshold = 0; } return $threshold; @@ -2544,7 +2845,7 @@ class User { /** * Get the permissions this user has. - * @return Array of String permission names + * @return array Array of String permission names */ public function getRights() { if ( is_null( $this->mRights ) ) { @@ -2559,7 +2860,7 @@ class User { /** * Get the list of explicit group memberships this user has. * The implicit * and user groups are not included. - * @return Array of String internal group names + * @return array Array of String internal group names */ public function getGroups() { $this->load(); @@ -2572,7 +2873,7 @@ class User { * This includes all explicit groups, plus 'user' if logged in, * '*' for all accounts, and autopromoted groups * @param bool $recache Whether to avoid the cache - * @return Array of String internal group names + * @return array Array of String internal group names */ public function getEffectiveGroups( $recache = false ) { if ( $recache || is_null( $this->mEffectiveGroups ) ) { @@ -2581,7 +2882,7 @@ class User { $this->getGroups(), // explicit groups $this->getAutomaticGroups( $recache ) // implicit groups ) ); - # Hook for additional groups + // Hook for additional groups wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) ); // Force reindexation of groups when a hook has unset one of them $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) ); @@ -2595,7 +2896,7 @@ class User { * This includes 'user' if logged in, '*' for all accounts, * and autopromoted groups * @param bool $recache Whether to avoid the cache - * @return Array of String internal group names + * @return array Array of String internal group names */ public function getAutomaticGroups( $recache = false ) { if ( $recache || is_null( $this->mImplicitGroups ) ) { @@ -2610,8 +2911,8 @@ class User { ) ); } if ( $recache ) { - # Assure data consistency with rights/groups, - # as getEffectiveGroups() depends on this function + // Assure data consistency with rights/groups, + // as getEffectiveGroups() depends on this function $this->mEffectiveGroups = null; } wfProfileOut( __METHOD__ ); @@ -2645,14 +2946,14 @@ class User { /** * Get the user's edit count. - * @return Int + * @return int|null Null for anonymous users */ public function getEditCount() { if ( !$this->getId() ) { return null; } - if ( !isset( $this->mEditCount ) ) { + if ( $this->mEditCount === null ) { /* Populate the count, if it has not been populated yet */ wfProfileIn( __METHOD__ ); $dbr = wfGetDB( DB_SLAVE ); @@ -2667,10 +2968,10 @@ class User { // it has not been initialized. do so. $count = $this->initEditCount(); } - $this->mEditCount = intval( $count ); + $this->mEditCount = $count; wfProfileOut( __METHOD__ ); } - return $this->mEditCount; + return (int)$this->mEditCount; } /** @@ -2696,7 +2997,11 @@ class User { // In case loadGroups was not called before, we now have the right twice. // Get rid of the duplicate. $this->mGroups = array_unique( $this->mGroups ); - $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) ); + + // Refresh the groups caches, and clear the rights cache so it will be + // refreshed on the next call to $this->getRights(). + $this->getEffectiveGroups( true ); + $this->mRights = null; $this->invalidateCache(); } @@ -2726,14 +3031,18 @@ class User { } $this->loadGroups(); $this->mGroups = array_diff( $this->mGroups, array( $group ) ); - $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) ); + + // Refresh the groups caches, and clear the rights cache so it will be + // refreshed on the next call to $this->getRights(). + $this->getEffectiveGroups( true ); + $this->mRights = null; $this->invalidateCache(); } /** * Get whether the user is logged in - * @return Bool + * @return bool */ public function isLoggedIn() { return $this->getID() != 0; @@ -2741,7 +3050,7 @@ class User { /** * Get whether the user is anonymous - * @return Bool + * @return bool */ public function isAnon() { return !$this->isLoggedIn(); @@ -2751,7 +3060,7 @@ class User { * Check if user is allowed to access a feature / make an action * * @internal param \String $varargs permissions to test - * @return Boolean: True if user is allowed to perform *any* of the given actions + * @return bool True if user is allowed to perform *any* of the given actions * * @return bool */ @@ -2782,28 +3091,28 @@ class User { /** * Internal mechanics of testing a permission - * @param $action String + * @param string $action * @return bool */ public function isAllowed( $action = '' ) { if ( $action === '' ) { return true; // In the spirit of DWIM } - # Patrolling may not be enabled + // 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' + // Use strict parameter to avoid matching numeric 0 accidentally inserted + // by misconfiguration: 0 == 'foo' return in_array( $action, $this->getRights(), true ); } /** * Check whether to enable recent changes patrol features for this user - * @return Boolean: True or false + * @return bool True or false */ public function useRCPatrol() { global $wgUseRCPatrol; @@ -2812,11 +3121,14 @@ class User { /** * Check whether to enable new pages patrol features for this user - * @return Bool True or false + * @return bool True or false */ public function useNPPatrol() { global $wgUseRCPatrol, $wgUseNPPatrol; - return ( ( $wgUseRCPatrol || $wgUseNPPatrol ) && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) ) ); + return ( + ( $wgUseRCPatrol || $wgUseNPPatrol ) + && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) ) + ); } /** @@ -2847,11 +3159,14 @@ class User { /** * Get a WatchedItem for this user and $title. * - * @param $title Title + * @since 1.22 $checkRights parameter added + * @param Title $title + * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights. + * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS. * @return WatchedItem */ - public function getWatchedItem( $title ) { - $key = $title->getNamespace() . ':' . $title->getDBkey(); + public function getWatchedItem( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) { + $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey(); if ( isset( $this->mWatchedItems[$key] ) ) { return $this->mWatchedItems[$key]; @@ -2861,34 +3176,43 @@ class User { $this->mWatchedItems = array(); } - $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title ); + $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title, $checkRights ); return $this->mWatchedItems[$key]; } /** * Check the watched status of an article. - * @param $title Title of the article to look at - * @return Bool + * @since 1.22 $checkRights parameter added + * @param Title $title Title of the article to look at + * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights. + * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS. + * @return bool */ - public function isWatched( $title ) { - return $this->getWatchedItem( $title )->isWatched(); + public function isWatched( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) { + return $this->getWatchedItem( $title, $checkRights )->isWatched(); } /** * Watch an article. - * @param $title Title of the article to look at + * @since 1.22 $checkRights parameter added + * @param Title $title Title of the article to look at + * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights. + * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS. */ - public function addWatch( $title ) { - $this->getWatchedItem( $title )->addWatch(); + public function addWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) { + $this->getWatchedItem( $title, $checkRights )->addWatch(); $this->invalidateCache(); } /** * Stop watching an article. - * @param $title Title of the article to look at + * @since 1.22 $checkRights parameter added + * @param Title $title Title of the article to look at + * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights. + * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS. */ - public function removeWatch( $title ) { - $this->getWatchedItem( $title )->removeWatch(); + public function removeWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) { + $this->getWatchedItem( $title, $checkRights )->removeWatch(); $this->invalidateCache(); } @@ -2896,22 +3220,42 @@ class User { * Clear the user's notification timestamp for the given title. * If e-notif e-mails are on, they will receive notification mails on * the next change of the page if it's watched etc. - * @param $title Title of the article to look at + * @note If the user doesn't have 'editmywatchlist', this will do nothing. + * @param Title $title Title of the article to look at + * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed. */ - public function clearNotification( &$title ) { + public function clearNotification( &$title, $oldid = 0 ) { global $wgUseEnotif, $wgShowUpdatedMarker; - # Do nothing if the database is locked to writes + // Do nothing if the database is locked to writes if ( wfReadOnly() ) { return; } - if ( $title->getNamespace() == NS_USER_TALK && - $title->getText() == $this->getName() ) { - if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) ) { + // Do nothing if not allowed to edit the watchlist + if ( !$this->isAllowed( 'editmywatchlist' ) ) { + return; + } + + // If we're working on user's talk page, we should update the talk page message indicator + if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) { + if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) { return; } - $this->setNewtalk( false ); + + $nextid = $oldid ? $title->getNextRevisionID( $oldid ) : null; + + if ( !$oldid || !$nextid ) { + // If we're looking at the latest revision, we should definitely clear it + $this->setNewtalk( false ); + } else { + // Otherwise we should update its revision, if it's present + if ( $this->getNewtalk() ) { + // Naturally the other one won't clear by itself + $this->setNewtalk( false ); + $this->setNewtalk( true, Revision::newFromId( $nextid ) ); + } + } } if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) { @@ -2928,25 +3272,29 @@ class User { // and when it does have to be executed, it can be on a slave // If this is the user's newtalk page, we always update the timestamp $force = ''; - if ( $title->getNamespace() == NS_USER_TALK && - $title->getText() == $this->getName() ) - { + if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) { $force = 'force'; } - $this->getWatchedItem( $title )->resetNotificationTimestamp( $force ); + $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid ); } /** * Resets all of the given user's page-change notification timestamps. * If e-notif e-mails are on, they will receive notification mails on * the next change of any watched page. + * @note If the user doesn't have 'editmywatchlist', this will do nothing. */ public function clearAllNotifications() { if ( wfReadOnly() ) { return; } + // Do nothing if not allowed to edit the watchlist + if ( !$this->isAllowed( 'editmywatchlist' ) ) { + return; + } + global $wgUseEnotif, $wgShowUpdatedMarker; if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) { $this->setNewtalk( false ); @@ -2956,42 +3304,12 @@ class User { if ( $id != 0 ) { $dbw = wfGetDB( DB_MASTER ); $dbw->update( 'watchlist', - array( /* SET */ - 'wl_notificationtimestamp' => null - ), array( /* WHERE */ - 'wl_user' => $id - ), __METHOD__ + array( /* SET */ 'wl_notificationtimestamp' => null ), + array( /* WHERE */ 'wl_user' => $id ), + __METHOD__ ); - # 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(); - } - } - - /** - * Set this user's options from an encoded string - * @param string $str Encoded options to import - * - * @deprecated in 1.19 due to removal of user_options from the user table - */ - private function decodeOptions( $str ) { - wfDeprecated( __METHOD__, '1.19' ); - if ( !$str ) { - return; - } - - $this->mOptionsLoaded = true; - $this->mOptionOverrides = array(); - - // If an option is not set in $str, use the default value - $this->mOptions = self::getDefaultOptions(); - - $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]; - } + // We also need to clear here the "you have new message" notification for the own user_talk page; + // it's cleared one page view later in WikiPage::doViewUpdates(). } } @@ -3002,31 +3320,39 @@ class User { * @param string $value Value to set * @param int $exp Expiration time, as a UNIX time value; * if 0 or not specified, use the default $wgCookieExpiration - * @param $secure Bool + * @param bool $secure * true: Force setting the secure attribute when setting the cookie * false: Force NOT setting the secure attribute when setting the cookie * null (default): Use the default ($wgCookieSecure) to set the secure attribute + * @param array $params Array of options sent passed to WebResponse::setcookie() */ - protected function setCookie( $name, $value, $exp = 0, $secure = null ) { - $this->getRequest()->response()->setcookie( $name, $value, $exp, null, null, $secure ); + protected function setCookie( $name, $value, $exp = 0, $secure = null, $params = array() ) { + $params['secure'] = $secure; + $this->getRequest()->response()->setcookie( $name, $value, $exp, $params ); } /** * Clear a cookie on the user's client * @param string $name Name of the cookie to clear + * @param bool $secure + * true: Force setting the secure attribute when setting the cookie + * false: Force NOT setting the secure attribute when setting the cookie + * null (default): Use the default ($wgCookieSecure) to set the secure attribute + * @param array $params Array of options sent passed to WebResponse::setcookie() */ - protected function clearCookie( $name ) { - $this->setCookie( $name, '', time() - 86400 ); + protected function clearCookie( $name, $secure = null, $params = array() ) { + $this->setCookie( $name, '', time() - 86400, $secure, $params ); } /** * Set the default cookies for this session on the user's client. * - * @param $request WebRequest object to use; $wgRequest will be used if null + * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null * is passed. * @param bool $secure Whether to force secure/insecure cookies or use default + * @param bool $rememberMe Whether to add a Token cookie for elongated sessions */ - public function setCookies( $request = null, $secure = null ) { + public function setCookies( $request = null, $secure = null, $rememberMe = false ) { if ( $request === null ) { $request = $this->getRequest(); } @@ -3052,7 +3378,7 @@ class User { 'UserID' => $this->mId, 'UserName' => $this->getName(), ); - if ( 1 == $this->getOption( 'rememberpassword' ) ) { + if ( $rememberMe ) { $cookies['Token'] = $this->mToken; } else { $cookies['Token'] = false; @@ -3074,10 +3400,18 @@ class User { /** * If wpStickHTTPS was selected, also set an insecure cookie that * will cause the site to redirect the user to HTTPS, if they access - * it over HTTP. Bug 29898. + * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same + * as the one set by centralauth (bug 53538). Also set it to session, or + * standard time setting, based on if rememberme was set. */ - if ( $request->getCheck( 'wpStickHTTPS' ) ) { - $this->setCookie( 'forceHTTPS', 'true', time() + 2592000, false ); //30 days + if ( $request->getCheck( 'wpStickHTTPS' ) || $this->requiresHTTPS() ) { + $this->setCookie( + 'forceHTTPS', + 'true', + $rememberMe ? 0 : null, + false, + array( 'prefix' => '' ) // no prefix + ); } } @@ -3101,10 +3435,10 @@ class User { $this->clearCookie( 'UserID' ); $this->clearCookie( 'Token' ); - $this->clearCookie( 'forceHTTPS' ); + $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) ); - # Remember when user logged out, to prevent seeing cached pages - $this->setCookie( 'LoggedOut', wfTimestampNow(), time() + 86400 ); + // Remember when user logged out, to prevent seeing cached pages + $this->setCookie( 'LoggedOut', time(), time() + 86400 ); } /** @@ -3115,6 +3449,7 @@ class User { global $wgAuth; $this->load(); + $this->loadPasswords(); if ( wfReadOnly() ) { return; } @@ -3124,15 +3459,15 @@ class User { $this->mTouched = self::newTouchedTimestamp(); if ( !$wgAuth->allowSetLocalPassword() ) { - $this->mPassword = ''; + $this->mPassword = self::getPasswordFactory()->newFromCiphertext( null ); } $dbw = wfGetDB( DB_MASTER ); $dbw->update( 'user', array( /* SET */ 'user_name' => $this->mName, - 'user_password' => $this->mPassword, - 'user_newpassword' => $this->mNewpassword, + 'user_password' => $this->mPassword->toString(), + 'user_newpassword' => $this->mNewpassword->toString(), 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ), 'user_real_name' => $this->mRealName, 'user_email' => $this->mEmail, @@ -3141,6 +3476,7 @@ class User { 'user_token' => strval( $this->mToken ), 'user_email_token' => $this->mEmailToken, 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ), + 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires ), ), array( /* WHERE */ 'user_id' => $this->mId ), __METHOD__ @@ -3155,7 +3491,7 @@ class User { /** * If only this user's username is known, and it exists, return the user ID. - * @return Int + * @return int */ public function idForName() { $s = trim( $this->getName() ); @@ -3175,21 +3511,25 @@ class User { * Add a user to the database, return the user object * * @param string $name Username to add - * @param array $params of Strings Non-default parameters to save to the database as user_* fields: - * - password The user's password hash. Password logins will be disabled if this is omitted. - * - newpassword Hash for a temporary password that has been mailed to the user - * - email The user's email address - * - email_authenticated The email authentication timestamp - * - real_name The user's real name - * - options An associative array of non-default options - * - token Random authentication token. Do not set. - * - registration Registration timestamp. Do not set. - * - * @return User object, or null if the username already exists + * @param array $params Array of Strings Non-default parameters to save to + * the database as user_* fields: + * - password: The user's password hash. Password logins will be disabled + * if this is omitted. + * - newpassword: Hash for a temporary password that has been mailed to + * the user. + * - email: The user's email address. + * - email_authenticated: The email authentication timestamp. + * - real_name: The user's real name. + * - options: An associative array of non-default options. + * - token: Random authentication token. Do not set. + * - registration: Registration timestamp. Do not set. + * + * @return User|null User object, or null if the username already exists. */ public static function createNew( $name, $params = array() ) { $user = new User; $user->load(); + $user->loadPasswords(); $user->setToken(); // init token if ( isset( $params['options'] ) ) { $user->mOptions = $params['options'] + (array)$user->mOptions; @@ -3201,8 +3541,8 @@ class User { $fields = array( 'user_id' => $seqVal, 'user_name' => $name, - 'user_password' => $user->mPassword, - 'user_newpassword' => $user->mNewpassword, + 'user_password' => $user->mPassword->toString(), + 'user_newpassword' => $user->mNewpassword->toString(), 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ), 'user_email' => $user->mEmail, 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ), @@ -3252,6 +3592,7 @@ class User { */ public function addToDatabase() { $this->load(); + $this->loadPasswords(); if ( !$this->mToken ) { $this->setToken(); // init token } @@ -3259,13 +3600,14 @@ class User { $this->mTouched = self::newTouchedTimestamp(); $dbw = wfGetDB( DB_MASTER ); + $inWrite = $dbw->writesOrCallbacksPending(); $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' ); $dbw->insert( 'user', array( 'user_id' => $seqVal, 'user_name' => $this->mName, - 'user_password' => $this->mPassword, - 'user_newpassword' => $this->mNewpassword, + 'user_password' => $this->mPassword->toString(), + 'user_newpassword' => $this->mNewpassword->toString(), 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ), 'user_email' => $this->mEmail, 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ), @@ -3278,11 +3620,25 @@ class User { array( 'IGNORE' ) ); if ( !$dbw->affectedRows() ) { + // The queries below cannot happen in the same REPEATABLE-READ snapshot. + // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise. + if ( $inWrite ) { + // Can't commit due to pending writes that may need atomicity. + // This may cause some lock contention unlike the case below. + $options = array( 'LOCK IN SHARE MODE' ); + $flags = self::READ_LOCKING; + } else { + // Often, this case happens early in views before any writes when + // using CentralAuth. It's should be OK to commit and break the snapshot. + $dbw->commit( __METHOD__, 'flush' ); + $options = array(); + $flags = 0; + } $this->mId = $dbw->selectField( 'user', 'user_id', - array( 'user_name' => $this->mName ), __METHOD__ ); + array( 'user_name' => $this->mName ), __METHOD__, $options ); $loaded = false; if ( $this->mId ) { - if ( $this->loadFromDatabase() ) { + if ( $this->loadFromDatabase( $flags ) ) { $loaded = true; } } @@ -3333,59 +3689,9 @@ class User { return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() ); } - /** - * Generate a string which will be different for any combination of - * user options which would produce different parser output. - * This will be used as part of the hash key for the parser cache, - * so users with the same options can share the same cached data - * safely. - * - * Extensions which require it should install 'PageRenderingHash' hook, - * which will give them a chance to modify this key based on their own - * settings. - * - * @deprecated since 1.17 use the ParserOptions object to get the relevant options - * @return String Page rendering hash - */ - public function getPageRenderingHash() { - wfDeprecated( __METHOD__, '1.17' ); - - global $wgRenderHashAppend, $wgLang, $wgContLang; - if ( $this->mHash ) { - return $this->mHash; - } - - // stubthreshold is only included below for completeness, - // since it disables the parser cache, its value will always - // be 0 when this function is called by parsercache. - - $confstr = $this->getOption( 'math' ); - $confstr .= '!' . $this->getStubThreshold(); - $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ? '1' : '' ); - $confstr .= '!' . $wgLang->getCode(); - $confstr .= '!' . $this->getOption( 'thumbsize' ); - // add in language specific options, if any - $extra = $wgContLang->getExtraHashOptions(); - $confstr .= $extra; - - // Since the skin could be overloading link(), it should be - // included here but in practice, none of our skins do that. - - $confstr .= $wgRenderHashAppend; - - // Give a chance for extensions to modify the hash, if they have - // extra options or other effects on the parser cache. - wfRunHooks( 'PageRenderingHash', array( &$confstr ) ); - - // Make it a valid memcached key fragment - $confstr = str_replace( ' ', '_', $confstr ); - $this->mHash = $confstr; - return $confstr; - } - /** * Get whether the user is explicitly blocked from account creation. - * @return Bool|Block + * @return bool|Block */ public function isBlockedFromCreateAccount() { $this->getBlockedStatus(); @@ -3399,14 +3705,15 @@ class User { if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) { $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() ); } - return $this->mBlockedFromCreateAccount instanceof Block && $this->mBlockedFromCreateAccount->prevents( 'createaccount' ) + return $this->mBlockedFromCreateAccount instanceof Block + && $this->mBlockedFromCreateAccount->prevents( 'createaccount' ) ? $this->mBlockedFromCreateAccount : false; } /** * Get whether the user is blocked from using Special:Emailuser. - * @return Bool + * @return bool */ public function isBlockedFromEmailuser() { $this->getBlockedStatus(); @@ -3415,16 +3722,16 @@ class User { /** * Get whether the user is allowed to create an account. - * @return Bool + * @return bool */ - function isAllowedToCreateAccount() { + public function isAllowedToCreateAccount() { return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount(); } /** * Get this user's personal page title. * - * @return Title: User's personal page title + * @return Title User's personal page title */ public function getUserPage() { return Title::makeTitle( NS_USER, $this->getName() ); @@ -3433,7 +3740,7 @@ class User { /** * Get this user's talk page title. * - * @return Title: User's talk page title + * @return Title User's talk page title */ public function getTalkPage() { $title = $this->getUserPage(); @@ -3443,7 +3750,7 @@ class User { /** * Determine whether the user is a newbie. Newbies are either * anonymous IPs, or the most recently created accounts. - * @return Bool + * @return bool */ public function isNewbie() { return !$this->isAllowed( 'autoconfirmed' ); @@ -3451,59 +3758,62 @@ class User { /** * Check to see if the given clear-text password is one of the accepted passwords - * @param string $password user password. - * @return Boolean: True if the given password is correct, otherwise False. + * @param string $password User password + * @return bool True if the given password is correct, otherwise False */ public function checkPassword( $password ) { global $wgAuth, $wgLegacyEncoding; - $this->load(); + $this->loadPasswords(); - // Even though we stop people from creating passwords that - // are shorter than this, doesn't mean people wont be able - // to. Certain authentication plugins do NOT want to save + // Certain authentication plugins do NOT want to save // domain passwords in a mysql database, so we should // check this (in case $wgAuth->strict() is false). - if ( !$this->isValidPassword( $password ) ) { - return false; - } if ( $wgAuth->authenticate( $this->getName(), $password ) ) { return true; } elseif ( $wgAuth->strict() ) { - /* Auth plugin doesn't allow local authentication */ + // Auth plugin doesn't allow local authentication return false; } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) { - /* Auth plugin doesn't allow local authentication for this user name */ + // Auth plugin doesn't allow local authentication for this user name return false; } - if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) { - return true; - } elseif ( $wgLegacyEncoding ) { - # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted - # Check for this with iconv - $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ); - if ( $cp1252Password != $password && - self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId ) ) - { - return true; + + $passwordFactory = self::getPasswordFactory(); + if ( !$this->mPassword->equals( $password ) ) { + if ( $wgLegacyEncoding ) { + // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted + // Check for this with iconv + $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ); + if ( $cp1252Password === $password || !$this->mPassword->equals( $cp1252Password ) ) { + return false; + } + } else { + return false; } } - return false; + + if ( $passwordFactory->needsUpdate( $this->mPassword ) ) { + $this->mPassword = $passwordFactory->newFromPlaintext( $password ); + $this->saveSettings(); + } + + return true; } /** * Check if the given clear-text password matches the temporary password * sent by e-mail for password reset operations. * - * @param $plaintext string + * @param string $plaintext * - * @return Boolean: True if matches, false otherwise + * @return bool True if matches, false otherwise */ public function checkTemporaryPassword( $plaintext ) { global $wgNewPasswordExpiry; $this->load(); - if ( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) { + if ( $this->mNewpassword->equals( $plaintext ) ) { if ( is_null( $this->mNewpassTime ) ) { return true; } @@ -3518,9 +3828,9 @@ class User { * Alias for getEditToken. * @deprecated since 1.19, use getEditToken instead. * - * @param string|array $salt of Strings Optional function-specific data for hashing - * @param $request WebRequest object to use or null to use $wgRequest - * @return String The new edit token + * @param string|array $salt Array of Strings Optional function-specific data for hashing + * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest + * @return string The new edit token */ public function editToken( $salt = '', $request = null ) { wfDeprecated( __METHOD__, '1.19' ); @@ -3535,9 +3845,9 @@ class User { * * @since 1.19 * - * @param string|array $salt of Strings Optional function-specific data for hashing - * @param $request WebRequest object to use or null to use $wgRequest - * @return String The new edit token + * @param string|array $salt Array of Strings Optional function-specific data for hashing + * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest + * @return string The new edit token */ public function getEditToken( $salt = '', $request = null ) { if ( $request == null ) { @@ -3562,8 +3872,9 @@ class User { /** * Generate a looking random token for various uses. * - * @return String The new random token - * @deprecated since 1.20; Use MWCryptRand for secure purposes or wfRandomString for pseudo-randomness + * @return string The new random token + * @deprecated since 1.20: Use MWCryptRand for secure purposes or + * wfRandomString for pseudo-randomness. */ public static function generateToken() { return MWCryptRand::generateHex( 32 ); @@ -3577,14 +3888,15 @@ class User { * * @param string $val Input value to compare * @param string $salt Optional function-specific data for hashing - * @param $request WebRequest object to use or null to use $wgRequest - * @return Boolean: Whether the token matches + * @param WebRequest|null $request Object to use or null to use $wgRequest + * @return bool Whether the token matches */ public function matchEditToken( $val, $salt = '', $request = null ) { $sessionToken = $this->getEditToken( $salt, $request ); if ( $val != $sessionToken ) { wfDebug( "User::matchEditToken: broken session data\n" ); } + return $val == $sessionToken; } @@ -3594,8 +3906,8 @@ class User { * * @param string $val Input value to compare * @param string $salt Optional function-specific data for hashing - * @param $request WebRequest object to use or null to use $wgRequest - * @return Boolean: Whether the token matches + * @param WebRequest|null $request Object to use or null to use $wgRequest + * @return bool Whether the token matches */ public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) { $sessionToken = $this->getEditToken( $salt, $request ); @@ -3606,8 +3918,8 @@ class User { * Generate a new e-mail confirmation token and send a confirmation/invalidation * mail to the user's given address. * - * @param string $type message to send, either "created", "changed" or "set" - * @return Status object + * @param string $type Message to send, either "created", "changed" or "set" + * @return Status */ public function sendConfirmationMail( $type = 'created' ) { global $wgLang; @@ -3622,6 +3934,7 @@ class User { } elseif ( $type === true ) { $message = 'confirmemail_body_changed'; } else { + // Messages: confirmemail_body_changed, confirmemail_body_set $message = 'confirmemail_body_' . $type; } @@ -3642,14 +3955,16 @@ class User { * * @param string $subject Message subject * @param string $body Message body - * @param string $from Optional From address; if unspecified, default $wgPasswordSender will be used + * @param string $from Optional From address; if unspecified, default + * $wgPasswordSender will be used. * @param string $replyto Reply-To address * @return Status */ public function sendMail( $subject, $body, $from = null, $replyto = null ) { if ( is_null( $from ) ) { - global $wgPasswordSender, $wgPasswordSenderName; - $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName ); + global $wgPasswordSender; + $sender = new MailAddress( $wgPasswordSender, + wfMessage( 'emailsender' )->inContentLanguage()->text() ); } else { $sender = new MailAddress( $from ); } @@ -3665,10 +3980,10 @@ class User { * @note Call saveSettings() after calling this function to commit * this change to the database. * - * @param &$expiration \mixed Accepts the expiration time - * @return String New token + * @param string &$expiration Accepts the expiration time + * @return string New token */ - private function confirmationToken( &$expiration ) { + protected function confirmationToken( &$expiration ) { global $wgUserEmailConfirmationTokenExpiry; $now = time(); $expires = $now + $wgUserEmailConfirmationTokenExpiry; @@ -3684,18 +3999,18 @@ class User { /** * Return a URL the user can use to confirm their email address. * @param string $token Accepts the email confirmation token - * @return String New token URL + * @return string New token URL */ - private function confirmationTokenUrl( $token ) { + protected function confirmationTokenUrl( $token ) { return $this->getTokenUrl( 'ConfirmEmail', $token ); } /** * Return a URL the user can use to invalidate their email address. * @param string $token Accepts the email confirmation token - * @return String New token URL + * @return string New token URL */ - private function invalidationTokenUrl( $token ) { + protected function invalidationTokenUrl( $token ) { return $this->getTokenUrl( 'InvalidateEmail', $token ); } @@ -3711,7 +4026,7 @@ class User { * * @param string $page Special page * @param string $token Token - * @return String Formatted URL + * @return string Formatted URL */ protected function getTokenUrl( $page, $token ) { // Hack to bypass localization of 'Special:' @@ -3743,7 +4058,7 @@ class User { * @note Call saveSettings() after calling this function to commit the change. * @return bool Returns true */ - function invalidateEmail() { + public function invalidateEmail() { $this->load(); $this->mEmailToken = null; $this->mEmailTokenExpires = null; @@ -3757,7 +4072,7 @@ class User { * Set the e-mail authentication timestamp. * @param string $timestamp TS_MW timestamp */ - function setEmailAuthenticationTimestamp( $timestamp ) { + public function setEmailAuthenticationTimestamp( $timestamp ) { $this->load(); $this->mEmailAuthenticated = $timestamp; wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) ); @@ -3766,7 +4081,7 @@ class User { /** * Is this user allowed to send e-mails within limits of current * site configuration? - * @return Bool + * @return bool */ public function canSendEmail() { global $wgEnableEmail, $wgEnableUserEmail; @@ -3781,7 +4096,7 @@ class User { /** * Is this user allowed to receive e-mails within limits of current * site configuration? - * @return Bool + * @return bool */ public function canReceiveEmail() { return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' ); @@ -3795,7 +4110,7 @@ class User { * confirmed their address by returning a code or using a password * sent to the address from the wiki. * - * @return Bool + * @return bool */ public function isEmailConfirmed() { global $wgEmailAuthentication; @@ -3819,7 +4134,7 @@ class User { /** * Check whether there is an outstanding request for e-mail confirmation. - * @return Bool + * @return bool */ public function isEmailConfirmationPending() { global $wgEmailAuthentication; @@ -3832,9 +4147,9 @@ class User { /** * Get the timestamp of account creation. * - * @return String|Bool|Null Timestamp of account creation, false for - * non-existent/anonymous user accounts, or null if existing account - * but information is not in database. + * @return string|bool|null Timestamp of account creation, false for + * non-existent/anonymous user accounts, or null if existing account + * but information is not in database. */ public function getRegistration() { if ( $this->isAnon() ) { @@ -3847,8 +4162,8 @@ class User { /** * Get the timestamp of the first edit * - * @return String|Bool Timestamp of first edit, or false for - * non-existent/anonymous user accounts. + * @return string|bool Timestamp of first edit, or false for + * non-existent/anonymous user accounts. */ public function getFirstEditTimestamp() { if ( $this->getId() == 0 ) { @@ -3869,8 +4184,8 @@ class User { /** * Get the permissions associated with a given list of groups * - * @param array $groups of Strings List of internal group names - * @return Array of Strings List of permission key names for given groups combined + * @param array $groups Array of Strings List of internal group names + * @return array Array of Strings List of permission key names for given groups combined */ public static function getGroupPermissions( $groups ) { global $wgGroupPermissions, $wgRevokePermissions; @@ -3897,7 +4212,7 @@ class User { * Get all the groups who have a given permission * * @param string $role Role to check - * @return Array of Strings List of internal group names with the given permission + * @return array Array of Strings List of internal group names with the given permission */ public static function getGroupsWithPermission( $role ) { global $wgGroupPermissions; @@ -3913,6 +4228,10 @@ class User { /** * Check, if the given group has the given permission * + * If you're wanting to check whether all users have a permission, use + * User::isEveryoneAllowed() instead. That properly checks if it's revoked + * from anyone. + * * @since 1.21 * @param string $group Group to check * @param string $role Role to check @@ -3924,11 +4243,51 @@ class User { && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] ); } + /** + * Check if all users have the given permission + * + * @since 1.22 + * @param string $right Right to check + * @return bool + */ + public static function isEveryoneAllowed( $right ) { + global $wgGroupPermissions, $wgRevokePermissions; + static $cache = array(); + + // Use the cached results, except in unit tests which rely on + // being able change the permission mid-request + if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) { + return $cache[$right]; + } + + if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) { + $cache[$right] = false; + return false; + } + + // If it's revoked anywhere, then everyone doesn't have it + foreach ( $wgRevokePermissions as $rights ) { + if ( isset( $rights[$right] ) && $rights[$right] ) { + $cache[$right] = false; + return false; + } + } + + // Allow extensions (e.g. OAuth) to say false + if ( !wfRunHooks( 'UserIsEveryoneAllowed', array( $right ) ) ) { + $cache[$right] = false; + return false; + } + + $cache[$right] = true; + return true; + } + /** * Get the localized descriptive name for a group, if it exists * * @param string $group Internal group name - * @return String Localized descriptive group name + * @return string Localized descriptive group name */ public static function getGroupName( $group ) { $msg = wfMessage( "group-$group" ); @@ -3940,7 +4299,7 @@ class User { * * @param string $group Internal group name * @param string $username Username for gender (since 1.19) - * @return String Localized name for group member + * @return string Localized name for group member */ public static function getGroupMember( $group, $username = '#' ) { $msg = wfMessage( "group-$group-member", $username ); @@ -3951,7 +4310,7 @@ class User { * Return the set of defined explicit groups. * The implicit groups (by default *, 'user' and 'autoconfirmed') * are not included, as they are defined automatically, not in the database. - * @return Array of internal group names + * @return array Array of internal group names */ public static function getAllGroups() { global $wgGroupPermissions, $wgRevokePermissions; @@ -3963,7 +4322,7 @@ class User { /** * Get a list of all available permissions. - * @return Array of permission names + * @return array Array of permission names */ public static function getAllRights() { if ( self::$mAllRights === false ) { @@ -3980,12 +4339,15 @@ class User { /** * Get a list of implicit groups - * @return Array of Strings Array of internal group names + * @return array Array of Strings Array of internal group names */ public static function getImplicitGroups() { global $wgImplicitGroups; + $groups = $wgImplicitGroups; - wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead + # Deprecated, use $wgImplictGroups instead + wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); + return $groups; } @@ -3993,7 +4355,7 @@ class User { * Get the title of a page describing a particular group * * @param string $group Internal group name - * @return Title|Bool Title of the page if it exists, false otherwise + * @return Title|bool Title of the page if it exists, false otherwise */ public static function getGroupPage( $group ) { $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage(); @@ -4012,7 +4374,7 @@ class User { * * @param string $group Internal name of the group * @param string $text The text of the link - * @return String HTML link to the group + * @return string HTML link to the group */ public static function makeGroupLinkHTML( $group, $text = '' ) { if ( $text == '' ) { @@ -4032,7 +4394,7 @@ class User { * * @param string $group Internal name of the group * @param string $text The text of the link - * @return String Wikilink to the group + * @return string Wikilink to the group */ public static function makeGroupLinkWiki( $group, $text = '' ) { if ( $text == '' ) { @@ -4050,8 +4412,8 @@ class User { /** * Returns an array of the groups that a particular group can add/remove. * - * @param string $group the group to check for whether it can add/remove - * @return Array array( 'add' => array( addablegroups ), + * @param string $group 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) ) @@ -4059,7 +4421,13 @@ class User { public static function changeableByGroup( $group ) { global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf; - $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() ); + $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 ) { @@ -4115,7 +4483,7 @@ class User { /** * Returns an array of groups that this user can add and remove - * @return Array array( 'add' => array( addablegroups ), + * @return array Array( 'add' => array( addablegroups ), * 'remove' => array( removablegroups ), * 'add-self' => array( addablegroups to self), * 'remove-self' => array( removable groups from self) ) @@ -4194,14 +4562,14 @@ class User { /** * Initialize user_editcount from data out of the revision table * - * @param $add Integer Edits to add to the count from the revision table - * @return Integer Number of edits + * @param int $add Edits to add to the count from the revision table + * @return int Number of edits */ protected function initEditCount( $add = 0 ) { // Pull from a slave to be less cruel to servers // Accuracy isn't the point anyway here $dbr = wfGetDB( DB_SLAVE ); - $count = (int) $dbr->selectField( + $count = (int)$dbr->selectField( 'revision', 'COUNT(rev_user)', array( 'rev_user' => $this->getId() ), @@ -4224,7 +4592,7 @@ class User { * Get the description of a given right * * @param string $right Right to query - * @return String Localized description of the right + * @return string Localized description of the right */ public static function getRightDescription( $right ) { $key = "right-$right"; @@ -4232,47 +4600,19 @@ class User { return $msg->isBlank() ? $right : $msg->text(); } - /** - * Make an old-style password hash - * - * @param string $password Plain-text password - * @param string $userId User ID - * @return String Password hash - */ - public 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 string $password Plain-text password * @param bool|string $salt Optional salt, may be random or the user ID. - - * If unspecified or false, will generate one automatically - * @return String Password hash + * If unspecified or false, will generate one automatically + * @return string Password hash + * @deprecated since 1.24, use Password class */ public static function crypt( $password, $salt = false ) { - global $wgPasswordSalt; - - $hash = ''; - if ( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) { - return $hash; - } - - if ( $wgPasswordSalt ) { - if ( $salt === false ) { - $salt = MWCryptRand::generateHex( 8 ); - } - return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) ); - } else { - return ':A:' . md5( $password ); - } + wfDeprecated( __METHOD__, '1.24' ); + $hash = self::getPasswordFactory()->newFromPlaintext( $password ); + return $hash->toString(); } /** @@ -4283,46 +4623,45 @@ class User { * @param string $password Plain-text password to compare * @param string|bool $userId User ID for old-style password salt * - * @return Boolean + * @return bool + * @deprecated since 1.24, use Password class */ public static function comparePasswords( $hash, $password, $userId = false ) { - $type = substr( $hash, 0, 3 ); - - $result = false; - if ( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) { - return $result; + wfDeprecated( __METHOD__, '1.24' ); + + // Check for *really* old password hashes that don't even have a type + // The old hash format was just an md5 hex hash, with no type information + if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) { + global $wgPasswordSalt; + if ( $wgPasswordSalt ) { + $password = ":B:{$userId}:{$hash}"; + } else { + $password = ":A:{$hash}"; + } } - 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; - } + $hash = self::getPasswordFactory()->newFromCiphertext( $hash ); + return $hash->equals( $password ); } /** * Add a newuser log entry for this user. * Before 1.19 the return value was always true. * - * @param string|bool $action account creation type. + * @param string|bool $action Account creation type. * - String, one of the following values: * - 'create' for an anonymous user creating an account for himself. * This will force the action's performer to be the created user itself, * no matter the value of $wgUser * - 'create2' for a logged in user creating an account for someone else * - 'byemail' when the created user will receive its password by e-mail + * - 'autocreate' when the user is automatically created (such as by CentralAuth). * - Boolean means whether the account was created by e-mail (deprecated): * - true will be converted to 'byemail' * - false will be converted to 'create' if this object is the same as * $wgUser and to 'create2' otherwise * - * @param string $reason user supplied reason + * @param string $reason User supplied reason * * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure */ @@ -4442,7 +4781,9 @@ class User { } /** - * @todo document + * Saves the non-default options for this user, as previously set e.g. via + * setOption(), in the database's "user_properties" (preferences) table. + * Usually used via saveSettings(). */ protected function saveOptions() { $this->loadOptions(); @@ -4457,36 +4798,67 @@ class User { } $userId = $this->getId(); - $insert_rows = array(); + + $insert_rows = array(); // all the new preference rows foreach ( $saveOptions as $key => $value ) { - # Don't bother storing default values + // Don't bother storing default values $defaultOption = self::getDefaultOption( $key ); - if ( ( is_null( $defaultOption ) && - !( $value === false || is_null( $value ) ) ) || - $value != $defaultOption ) { + if ( ( $defaultOption === null && $value !== false && $value !== null ) + || $value != $defaultOption + ) { $insert_rows[] = array( - 'up_user' => $userId, - 'up_property' => $key, - 'up_value' => $value, - ); + 'up_user' => $userId, + 'up_property' => $key, + 'up_value' => $value, + ); } } $dbw = wfGetDB( DB_MASTER ); - $hasRows = $dbw->selectField( 'user_properties', '1', - array( 'up_user' => $userId ), __METHOD__ ); - if ( $hasRows ) { - // Only do this delete if there is something there. A very large portion of - // calls to this function are for setting 'rememberpassword' for new accounts. - // Doing this delete for new accounts with no rows in the table rougly causes - // gap locks on [max user ID,+infinity) which causes high contention since many - // updates will pile up on each other since they are for higher (newer) user IDs. - $dbw->delete( 'user_properties', array( 'up_user' => $userId ), __METHOD__ ); + $res = $dbw->select( 'user_properties', + array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__ ); + + // Find prior rows that need to be removed or updated. These rows will + // all be deleted (the later so that INSERT IGNORE applies the new values). + $keysDelete = array(); + foreach ( $res as $row ) { + if ( !isset( $saveOptions[$row->up_property] ) + || strcmp( $saveOptions[$row->up_property], $row->up_value ) != 0 + ) { + $keysDelete[] = $row->up_property; + } } + + if ( count( $keysDelete ) ) { + // Do the DELETE by PRIMARY KEY for prior rows. + // In the past a very large portion of calls to this function are for setting + // 'rememberpassword' for new accounts (a preference that has since been removed). + // Doing a blanket per-user DELETE for new accounts with no rows in the table + // caused gap locks on [max user ID,+infinity) which caused high contention since + // updates would pile up on each other as they are for higher (newer) user IDs. + // It might not be necessary these days, but it shouldn't hurt either. + $dbw->delete( 'user_properties', + array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__ ); + } + // Insert the new preference rows $dbw->insert( 'user_properties', $insert_rows, __METHOD__, array( 'IGNORE' ) ); } + /** + * Lazily instantiate and return a factory object for making passwords + * + * @return PasswordFactory + */ + public static function getPasswordFactory() { + if ( self::$mPasswordFactory === null ) { + self::$mPasswordFactory = new PasswordFactory(); + self::$mPasswordFactory->init( RequestContext::getMain()->getConfig() ); + } + + return self::$mPasswordFactory; + } + /** * Provide an array of HTML5 attributes to put on an input element * intended for the user to enter a new password. This may include @@ -4508,8 +4880,7 @@ class User { * * @return array Array of HTML attributes suitable for feeding to * Html::element(), directly or indirectly. (Don't feed to Xml::*()! - * That will potentially output invalid XHTML 1.0 Transitional, and will - * get confused by the boolean attribute syntax used.) + * That will get confused by the boolean attribute syntax used.) */ public static function passwordChangeInputAttribs() { global $wgMinimalPasswordLength; @@ -4556,9 +4927,6 @@ class User { 'user_id', 'user_name', 'user_real_name', - 'user_password', - 'user_newpassword', - 'user_newpass_time', 'user_email', 'user_touched', 'user_token', @@ -4569,4 +4937,26 @@ class User { 'user_editcount', ); } + + /** + * Factory function for fatal permission-denied errors + * + * @since 1.22 + * @param string $permission User right required + * @return Status + */ + static function newFatalPermissionDeniedStatus( $permission ) { + global $wgLang; + + $groups = array_map( + array( 'User', 'makeGroupLinkWiki' ), + User::getGroupsWithPermission( $permission ) + ); + + if ( $groups ) { + return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) ); + } else { + return Status::newFatal( 'badaccess-group0' ); + } + } }