/includes/User.php
PHP | 3404 lines | 2066 code | 280 blank | 1058 comment | 307 complexity | 8653b2a9a6500407554f9532e5a27a41 MD5 | raw file
Possible License(s): GPL-2.0, LGPL-3.0
Large files files are truncated, but you can click here to view the full file
- <?php
- /**
- * Implements the User class for the %MediaWiki software.
- * @file
- */
- /**
- * \int Number of characters in user_token field.
- * @ingroup Constants
- */
- define( 'USER_TOKEN_LENGTH', 32 );
- /**
- * \int Serialized record version.
- * @ingroup Constants
- */
- define( 'MW_USER_VERSION', 6 );
- /**
- * \string Some punctuation to prevent editing from broken text-mangling proxies.
- * @ingroup Constants
- */
- 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
- * classes use the getXXX() functions to access these fields. These functions
- * do all the work of determining whether the user is logged in,
- * whether the requested option can be satisfied from cookies or
- * whether a database query is needed. Most of the settings needed
- * for rendering normal pages are set in the cookie to minimize use
- * of the database.
- */
- class User {
- /**
- * \type{\arrayof{\string}} A list of default user toggles, i.e., boolean user
- * preferences that are displayed by Special:Preferences as checkboxes.
- * This list can be extended via the UserToggles hook or by
- * $wgContLang::getExtraUserToggles().
- * @showinitializer
- */
- public static $mToggles = array(
- 'highlightbroken',
- 'justify',
- 'hideminor',
- 'extendwatchlist',
- 'usenewrc',
- 'numberheadings',
- 'showtoolbar',
- 'editondblclick',
- 'editsection',
- 'editsectiononrightclick',
- 'showtoc',
- 'rememberpassword',
- 'editwidth',
- 'watchcreations',
- 'watchdefault',
- 'watchmoves',
- 'watchdeletion',
- 'minordefault',
- 'previewontop',
- 'previewonfirst',
- 'nocache',
- 'enotifwatchlistpages',
- 'enotifusertalkpages',
- 'enotifminoredits',
- 'enotifrevealaddr',
- 'shownumberswatching',
- 'fancysig',
- 'externaleditor',
- 'externaldiff',
- 'showjumplinks',
- 'uselivepreview',
- 'forceeditsummary',
- 'watchlisthideminor',
- 'watchlisthidebots',
- 'watchlisthideown',
- 'watchlisthideanons',
- 'watchlisthideliu',
- 'ccmeonemails',
- 'diffonly',
- 'showhiddencats',
- 'noconvertlink',
- 'norollbackdiff',
- );
- /**
- * \type{\arrayof{\string}} 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(
- // user table
- 'mId',
- 'mName',
- 'mRealName',
- 'mPassword',
- 'mNewpassword',
- 'mNewpassTime',
- 'mEmail',
- 'mOptions',
- 'mTouched',
- 'mToken',
- 'mEmailAuthenticated',
- 'mEmailToken',
- 'mEmailTokenExpires',
- 'mRegistration',
- 'mEditCount',
- // user_group table
- 'mGroups',
- );
- /**
- * \type{\arrayof{\string}} Core rights.
- * Each of these should have a corresponding message of the form
- * "right-$right".
- * @showinitializer
- */
- static $mCoreRights = array(
- 'apihighlimits',
- 'autoconfirmed',
- 'autopatrol',
- 'bigdelete',
- 'block',
- 'blockemail',
- 'bot',
- 'browsearchive',
- 'createaccount',
- 'createpage',
- 'createtalk',
- 'delete',
- 'deletedhistory',
- 'deleterevision',
- 'edit',
- 'editinterface',
- 'editusercssjs',
- 'hideuser',
- 'import',
- 'importupload',
- 'ipblock-exempt',
- 'markbotedits',
- 'minoredit',
- 'move',
- 'movefile',
- 'move-rootuserpages',
- 'move-subpages',
- 'nominornewtalk',
- 'noratelimit',
- 'override-export-depth',
- 'patrol',
- 'protect',
- 'proxyunbannable',
- 'purge',
- 'read',
- 'reupload',
- 'reupload-shared',
- 'rollback',
- 'siteadmin',
- 'suppressionlog',
- 'suppressredirect',
- 'suppressrevision',
- 'trackback',
- 'undelete',
- 'unwatchedpages',
- 'upload',
- 'upload_by_url',
- 'userrights',
- 'userrights-interwiki',
- 'writeapi',
- );
- /**
- * \string Cached results of getAllRights()
- */
- static $mAllRights = false;
- /** @name Cache variables */
- //@{
- var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
- $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
- $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
- //@}
- /**
- * \bool Whether the cache variables have been loaded.
- */
- var $mDataLoaded, $mAuthLoaded;
- /**
- * \string Initialization data source if mDataLoaded==false. May be one of:
- * - 'defaults' anonymous user initialised from class defaults
- * - 'name' initialise from mName
- * - 'id' initialise from mId
- * - 'session' log in from cookies or session if possible
- *
- * Use the User::newFrom*() family of functions to set this.
- */
- var $mFrom;
- /** @name Lazy-initialized variables, invalidated with clearInstanceCache */
- //@{
- var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
- $mBlockreason, $mBlock, $mEffectiveGroups, $mBlockedGlobally,
- $mLocked, $mHideName;
- //@}
- /**
- * Lightweight constructor for an anonymous user.
- * Use the User::newFrom* factory functions for other kinds of users.
- *
- * @see newFromName()
- * @see newFromId()
- * @see newFromConfirmationCode()
- * @see newFromSession()
- * @see newFromRow()
- */
- function User() {
- $this->clearInstanceCache( 'defaults' );
- }
- /**
- * Load the user table data for this object from the source given by mFrom.
- */
- function load() {
- if ( $this->mDataLoaded ) {
- return;
- }
- wfProfileIn( __METHOD__ );
- # Set it now to avoid infinite recursion in accessors
- $this->mDataLoaded = true;
- switch ( $this->mFrom ) {
- case 'defaults':
- $this->loadDefaults();
- break;
- case 'name':
- $this->mId = self::idFromName( $this->mName );
- if ( !$this->mId ) {
- # Nonexistent user placeholder object
- $this->loadDefaults( $this->mName );
- } else {
- $this->loadFromId();
- }
- break;
- case 'id':
- $this->loadFromId();
- break;
- case 'session':
- $this->loadFromSession();
- wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
- break;
- default:
- throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
- }
- wfProfileOut( __METHOD__ );
- }
- /**
- * Load user table data, given mId has already been set.
- * @return \bool false if the ID does not exist, true otherwise
- * @private
- */
- function loadFromId() {
- global $wgMemc;
- if ( $this->mId == 0 ) {
- $this->loadDefaults();
- return false;
- }
- # 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
- $data = false;
- }
- if ( !$data ) {
- wfDebug( "Cache miss for user {$this->mId}\n" );
- # Load from DB
- if ( !$this->loadFromDatabase() ) {
- # Can't load from ID, user is anonymous
- return false;
- }
- $this->saveToCache();
- } else {
- wfDebug( "Got user {$this->mId} from cache\n" );
- # Restore from cache
- foreach ( self::$mCacheVars as $name ) {
- $this->$name = $data[$name];
- }
- }
- return true;
- }
- /**
- * Save user data to the shared cache
- */
- function saveToCache() {
- $this->load();
- $this->loadGroups();
- if ( $this->isAnon() ) {
- // Anonymous users are uncached
- return;
- }
- $data = array();
- foreach ( self::$mCacheVars as $name ) {
- $data[$name] = $this->$name;
- }
- $data['mVersion'] = MW_USER_VERSION;
- $key = wfMemcKey( 'user', 'id', $this->mId );
- global $wgMemc;
- $wgMemc->set( $key, $data );
- }
-
-
- /** @name newFrom*() static factory methods */
- //@{
- /**
- * Static factory method for creation from username.
- *
- * This is slightly less efficient than newFromId(), so use newFromId() if
- * you have both an ID and a name handy.
- *
- * @param $name \string Username, validated by Title::newFromText()
- * @param $validate \mixed Validate username. Takes the same parameters as
- * User::getCanonicalName(), except that true is accepted as an alias
- * for 'valid', for BC.
- *
- * @return \type{User} The User object, or null if the username is invalid. If the
- * username is not present in the database, the result will be a user object
- * with a name, zero user ID and default settings.
- */
- static function newFromName( $name, $validate = 'valid' ) {
- if ( $validate === true ) {
- $validate = 'valid';
- }
- $name = self::getCanonicalName( $name, $validate );
- if ( $name === false ) {
- return null;
- } else {
- # Create unloaded user object
- $u = new User;
- $u->mName = $name;
- $u->mFrom = 'name';
- return $u;
- }
- }
- /**
- * Static factory method for creation from a given user ID.
- *
- * @param $id \int Valid user ID
- * @return \type{User} The corresponding User object
- */
- static function newFromId( $id ) {
- $u = new User;
- $u->mId = $id;
- $u->mFrom = 'id';
- return $u;
- }
- /**
- * Factory method to fetch whichever user has a given email confirmation code.
- * This code is generated when an account is created or its e-mail address
- * has changed.
- *
- * If the code is invalid or has expired, returns NULL.
- *
- * @param $code \string Confirmation code
- * @return \type{User}
- */
- static function newFromConfirmationCode( $code ) {
- $dbr = wfGetDB( DB_SLAVE );
- $id = $dbr->selectField( 'user', 'user_id', array(
- 'user_email_token' => md5( $code ),
- 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
- ) );
- if( $id !== false ) {
- return User::newFromId( $id );
- } else {
- return null;
- }
- }
- /**
- * Create a new user object using data from session or cookies. If the
- * login credentials are invalid, the result is an anonymous user.
- *
- * @return \type{User}
- */
- static function newFromSession() {
- $user = new User;
- $user->mFrom = 'session';
- return $user;
- }
- /**
- * Create a new user object from a user row.
- * The row should have all fields from the user table in it.
- * @param $row array A row from the user table
- * @return \type{User}
- */
- static function newFromRow( $row ) {
- $user = new User;
- $user->loadFromRow( $row );
- return $user;
- }
-
- //@}
-
- /**
- * Get the username corresponding to a given user ID
- * @param $id \int User ID
- * @return \string The corresponding username
- */
- static function whoIs( $id ) {
- $dbr = wfGetDB( DB_SLAVE );
- return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
- }
- /**
- * Get the real name of a user given their user ID
- *
- * @param $id \int User ID
- * @return \string The corresponding user's real name
- */
- static function whoIsReal( $id ) {
- $dbr = wfGetDB( DB_SLAVE );
- return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__ );
- }
- /**
- * Get database id given a user name
- * @param $name \string Username
- * @return \types{\int,\null} The corresponding user's ID, or null if user is nonexistent
- */
- static function idFromName( $name ) {
- $nt = Title::makeTitleSafe( NS_USER, $name );
- if( is_null( $nt ) ) {
- # Illegal name
- return null;
- }
- $dbr = wfGetDB( DB_SLAVE );
- $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
- if ( $s === false ) {
- return 0;
- } else {
- return $s->user_id;
- }
- }
- /**
- * Does the string match an anonymous IPv4 address?
- *
- * This function exists for username validation, in order to reject
- * usernames which are similar in form to IP addresses. Strings such
- * as 300.300.300.300 will return true because it looks like an IP
- * address, despite not being strictly valid.
- *
- * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
- * address because the usemod software would "cloak" anonymous IP
- * addresses like this, if we allowed accounts like this to be created
- * new users could get the old edits of these anonymous users.
- *
- * @param $name \string String to match
- * @return \bool True or false
- */
- static function isIP( $name ) {
- return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP::isIPv6($name);
- }
- /**
- * Is the input a valid username?
- *
- * Checks if the input is a valid username, we don't want an empty string,
- * an IP address, anything that containins slashes (would mess up subpages),
- * is longer than the maximum allowed username size or doesn't begin with
- * a capital letter.
- *
- * @param $name \string String to match
- * @return \bool True or false
- */
- static function isValidUserName( $name ) {
- global $wgContLang, $wgMaxNameChars;
- if ( $name == ''
- || User::isIP( $name )
- || strpos( $name, '/' ) !== false
- || strlen( $name ) > $wgMaxNameChars
- || $name != $wgContLang->ucfirst( $name ) ) {
- wfDebugLog( 'username', __METHOD__ .
- ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
- return false;
- }
- // Ensure that the name can't be misresolved as a different title,
- // such as with extra namespace keys at the start.
- $parsed = Title::newFromText( $name );
- if( is_null( $parsed )
- || $parsed->getNamespace()
- || strcmp( $name, $parsed->getPrefixedText() ) ) {
- wfDebugLog( 'username', __METHOD__ .
- ": '$name' invalid due to ambiguous prefixes" );
- return false;
- }
- // Check an additional blacklist of troublemaker characters.
- // Should these be merged into the title char list?
- $unicodeBlacklist = '/[' .
- '\x{0080}-\x{009f}' . # iso-8859-1 control chars
- '\x{00a0}' . # non-breaking space
- '\x{2000}-\x{200f}' . # various whitespace
- '\x{2028}-\x{202f}' . # breaks and control chars
- '\x{3000}' . # ideographic space
- '\x{e000}-\x{f8ff}' . # private use
- ']/u';
- if( preg_match( $unicodeBlacklist, $name ) ) {
- wfDebugLog( 'username', __METHOD__ .
- ": '$name' invalid due to blacklisted characters" );
- return false;
- }
- return true;
- }
- /**
- * Usernames which fail to pass this function will be blocked
- * from user login and new account registrations, but may be used
- * internally by batch processes.
- *
- * If an account already exists in this form, login will be blocked
- * by a failure to pass this function.
- *
- * @param $name \string String to match
- * @return \bool True or false
- */
- static function isUsableName( $name ) {
- global $wgReservedUsernames;
- // Must be a valid username, obviously ;)
- if ( !self::isValidUserName( $name ) ) {
- return false;
- }
- static $reservedUsernames = false;
- if ( !$reservedUsernames ) {
- $reservedUsernames = $wgReservedUsernames;
- wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
- }
- // Certain names may be reserved for batch processes.
- foreach ( $reservedUsernames as $reserved ) {
- if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
- $reserved = wfMsgForContent( substr( $reserved, 4 ) );
- }
- if ( $reserved == $name ) {
- return false;
- }
- }
- return true;
- }
- /**
- * Usernames which fail to pass this function will be blocked
- * from new account registrations, but may be used internally
- * either by batch processes or by user accounts which have
- * already been created.
- *
- * Additional character blacklisting may be added here
- * rather than in isValidUserName() to avoid disrupting
- * existing accounts.
- *
- * @param $name \string String to match
- * @return \bool True or false
- */
- static function isCreatableName( $name ) {
- global $wgInvalidUsernameCharacters;
- return
- self::isUsableName( $name ) &&
- // Registration-time character blacklisting...
- !preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name );
- }
- /**
- * Is the input a valid password for this user?
- *
- * @param $password \string Desired password
- * @return \bool True or false
- */
- function isValidPassword( $password ) {
- global $wgMinimalPasswordLength, $wgContLang;
- $result = null;
- if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
- return $result;
- if( $result === false )
- return false;
- // Password needs to be long enough, and can't be the same as the username
- return strlen( $password ) >= $wgMinimalPasswordLength
- && $wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName );
- }
- /**
- * Does a string look like an e-mail address?
- *
- * There used to be a regular expression here, it got removed because it
- * rejected valid addresses. Actually just check if there is '@' somewhere
- * in the given address.
- *
- * @todo Check for RFC 2822 compilance (bug 959)
- *
- * @param $addr \string E-mail address
- * @return \bool True or false
- */
- public static function isValidEmailAddr( $addr ) {
- $result = null;
- if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
- return $result;
- }
- return strpos( $addr, '@' ) !== false;
- }
- /**
- * Given unvalidated user input, return a canonical username, or false if
- * the username is invalid.
- * @param $name \string User input
- * @param $validate \types{\string,\bool} Type of validation to use:
- * - false No validation
- * - 'valid' Valid for batch processes
- * - 'usable' Valid for batch processes and login
- * - 'creatable' Valid for batch processes, login and account creation
- */
- static function getCanonicalName( $name, $validate = 'valid' ) {
- # Force usernames to capital
- global $wgContLang;
- $name = $wgContLang->ucfirst( $name );
- # Reject names containing '#'; these will be cleaned up
- # with title normalisation, but then it's too late to
- # check elsewhere
- if( strpos( $name, '#' ) !== false )
- return false;
- # Clean up name according to title rules
- $t = ($validate === 'valid') ?
- Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
- # Check for invalid titles
- if( is_null( $t ) ) {
- return false;
- }
- # Reject various classes of invalid names
- $name = $t->getText();
- global $wgAuth;
- $name = $wgAuth->getCanonicalName( $t->getText() );
- switch ( $validate ) {
- case false:
- break;
- case 'valid':
- if ( !User::isValidUserName( $name ) ) {
- $name = false;
- }
- break;
- case 'usable':
- if ( !User::isUsableName( $name ) ) {
- $name = false;
- }
- break;
- case 'creatable':
- if ( !User::isCreatableName( $name ) ) {
- $name = false;
- }
- break;
- default:
- throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__ );
- }
- return $name;
- }
- /**
- * Count the number of edits of a user
- * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
- *
- * @param $uid \int User ID to check
- * @return \int The user's edit count
- */
- static function edits( $uid ) {
- wfProfileIn( __METHOD__ );
- $dbr = wfGetDB( DB_SLAVE );
- // check if the user_editcount field has been initialized
- $field = $dbr->selectField(
- 'user', 'user_editcount',
- array( 'user_id' => $uid ),
- __METHOD__
- );
- if( $field === null ) { // it has not been initialized. do so.
- $dbw = wfGetDB( DB_MASTER );
- $count = $dbr->selectField(
- 'revision', 'count(*)',
- array( 'rev_user' => $uid ),
- __METHOD__
- );
- $dbw->update(
- 'user',
- array( 'user_editcount' => $count ),
- array( 'user_id' => $uid ),
- __METHOD__
- );
- } else {
- $count = $field;
- }
- wfProfileOut( __METHOD__ );
- return $count;
- }
- /**
- * Return a random password. Sourced from mt_rand, so it's not particularly secure.
- * @todo hash random numbers to improve security, like generateToken()
- *
- * @return \string New random password
- */
- static function randomPassword() {
- global $wgMinimalPasswordLength;
- $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
- $l = strlen( $pwchars ) - 1;
- $pwlength = max( 7, $wgMinimalPasswordLength );
- $digit = mt_rand(0, $pwlength - 1);
- $np = '';
- for ( $i = 0; $i < $pwlength; $i++ ) {
- $np .= $i == $digit ? chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
- }
- return $np;
- }
- /**
- * Set cached properties to default.
- *
- * @note This no longer clears uncached lazy-initialised properties;
- * the constructor does that instead.
- * @private
- */
- function loadDefaults( $name = false ) {
- wfProfileIn( __METHOD__ );
- global $wgCookiePrefix;
- $this->mId = 0;
- $this->mName = $name;
- $this->mRealName = '';
- $this->mPassword = $this->mNewpassword = '';
- $this->mNewpassTime = null;
- $this->mEmail = '';
- $this->mOptions = null; # Defer init
- if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
- $this->mTouched = wfTimestamp( TS_MW, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
- } else {
- $this->mTouched = '0'; # Allow any pages to be cached
- }
- $this->setToken(); # Random
- $this->mEmailAuthenticated = null;
- $this->mEmailToken = '';
- $this->mEmailTokenExpires = null;
- $this->mRegistration = wfTimestamp( TS_MW );
- $this->mGroups = array();
- wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
- wfProfileOut( __METHOD__ );
- }
- /**
- * @deprecated Use wfSetupSession().
- */
- function SetupSession() {
- wfDeprecated( __METHOD__ );
- wfSetupSession();
- }
- /**
- * Load user data from the session or login cookie. If there are no valid
- * credentials, initialises the user as an anonymous user.
- * @return \bool True if the user is logged in, false otherwise.
- */
- private function loadFromSession() {
- global $wgMemc, $wgCookiePrefix;
- $result = null;
- wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
- if ( $result !== null ) {
- return $result;
- }
- if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
- $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
- if( isset( $_SESSION['wsUserID'] ) && $sId != $_SESSION['wsUserID'] ) {
- $this->loadDefaults(); // Possible collision!
- wfDebugLog( 'loginSessions', "Session user ID ({$_SESSION['wsUserID']}) and
- cookie user ID ($sId) don't match!" );
- return false;
- }
- $_SESSION['wsUserID'] = $sId;
- } else if ( isset( $_SESSION['wsUserID'] ) ) {
- if ( $_SESSION['wsUserID'] != 0 ) {
- $sId = $_SESSION['wsUserID'];
- } else {
- $this->loadDefaults();
- return false;
- }
- } else {
- $this->loadDefaults();
- return false;
- }
- if ( isset( $_SESSION['wsUserName'] ) ) {
- $sName = $_SESSION['wsUserName'];
- } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
- $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
- $_SESSION['wsUserName'] = $sName;
- } else {
- $this->loadDefaults();
- return false;
- }
- $passwordCorrect = FALSE;
- $this->mId = $sId;
- if ( !$this->loadFromId() ) {
- # Not a valid ID, loadFromId has switched the object to anon for us
- return false;
- }
- if ( isset( $_SESSION['wsToken'] ) ) {
- $passwordCorrect = $_SESSION['wsToken'] == $this->mToken;
- $from = 'session';
- } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
- $passwordCorrect = $this->mToken == $_COOKIE["{$wgCookiePrefix}Token"];
- $from = 'cookie';
- } else {
- # No session or persistent login cookie
- $this->loadDefaults();
- return false;
- }
- if ( ( $sName == $this->mName ) && $passwordCorrect ) {
- $_SESSION['wsToken'] = $this->mToken;
- wfDebug( "Logged in from $from\n" );
- return true;
- } else {
- # Invalid credentials
- wfDebug( "Can't log in from $from, invalid credentials\n" );
- $this->loadDefaults();
- return false;
- }
- }
- /**
- * 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
- * @private
- */
- function loadFromDatabase() {
- # Paranoia
- $this->mId = intval( $this->mId );
- /** Anonymous user */
- if( !$this->mId ) {
- $this->loadDefaults();
- return false;
- }
- $dbr = wfGetDB( DB_MASTER );
- $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId ), __METHOD__ );
- wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
- if ( $s !== false ) {
- # Initialise user table data
- $this->loadFromRow( $s );
- $this->mGroups = null; // deferred
- $this->getEditCount(); // revalidation for nulls
- return true;
- } else {
- # Invalid user_id
- $this->mId = 0;
- $this->loadDefaults();
- return false;
- }
- }
- /**
- * Initialize this object from a row from the user table.
- *
- * @param $row \type{\arrayof{\mixed}} Row from the user table to load.
- */
- function loadFromRow( $row ) {
- $this->mDataLoaded = true;
- if ( isset( $row->user_id ) ) {
- $this->mId = intval( $row->user_id );
- }
- $this->mName = $row->user_name;
- $this->mRealName = $row->user_real_name;
- $this->mPassword = $row->user_password;
- $this->mNewpassword = $row->user_newpassword;
- $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
- $this->mEmail = $row->user_email;
- $this->decodeOptions( $row->user_options );
- $this->mTouched = wfTimestamp(TS_MW,$row->user_touched);
- $this->mToken = $row->user_token;
- $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
- $this->mEmailToken = $row->user_email_token;
- $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
- $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
- $this->mEditCount = $row->user_editcount;
- }
- /**
- * Load the groups from the database if they aren't already loaded.
- * @private
- */
- function loadGroups() {
- if ( is_null( $this->mGroups ) ) {
- $dbr = wfGetDB( DB_MASTER );
- $res = $dbr->select( 'user_groups',
- array( 'ug_group' ),
- array( 'ug_user' => $this->mId ),
- __METHOD__ );
- $this->mGroups = array();
- while( $row = $dbr->fetchObject( $res ) ) {
- $this->mGroups[] = $row->ug_group;
- }
- }
- }
- /**
- * Clear various cached data stored in this object.
- * @param $reloadFrom \string Reload user and user_groups table data from a
- * given source. May be "name", "id", "defaults", "session", or false for
- * no reload.
- */
- function clearInstanceCache( $reloadFrom = false ) {
- $this->mNewtalk = -1;
- $this->mDatePreference = null;
- $this->mBlockedby = -1; # Unset
- $this->mHash = false;
- $this->mSkin = null;
- $this->mRights = null;
- $this->mEffectiveGroups = null;
- if ( $reloadFrom ) {
- $this->mDataLoaded = false;
- $this->mFrom = $reloadFrom;
- }
- }
- /**
- * Combine the language default options with any site-specific options
- * and add the default language variants.
- *
- * @return \type{\arrayof{\string}} Array of options
- */
- static function getDefaultOptions() {
- global $wgNamespacesToBeSearchedDefault;
- /**
- * Site defaults will override the global/language defaults
- */
- global $wgDefaultUserOptions, $wgContLang;
- $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptionOverrides();
- /**
- * default language setting
- */
- $variant = $wgContLang->getPreferredVariant( false );
- $defOpt['variant'] = $variant;
- $defOpt['language'] = $variant;
- foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
- $defOpt['searchNs'.$nsnum] = $val;
- }
- return $defOpt;
- }
- /**
- * Get a given default option value.
- *
- * @param $opt \string Name of option to retrieve
- * @return \string Default option value
- */
- public static function getDefaultOption( $opt ) {
- $defOpts = self::getDefaultOptions();
- if( isset( $defOpts[$opt] ) ) {
- return $defOpts[$opt];
- } else {
- return '';
- }
- }
- /**
- * Get a list of user toggle names
- * @return \type{\arrayof{\string}} Array of user toggle names
- */
- static function getToggles() {
- global $wgContLang, $wgUseRCPatrol;
- $extraToggles = array();
- wfRunHooks( 'UserToggles', array( &$extraToggles ) );
- if( $wgUseRCPatrol ) {
- $extraToggles[] = 'hidepatrolled';
- $extraToggles[] = 'newpageshidepatrolled';
- $extraToggles[] = 'watchlisthidepatrolled';
- }
- return array_merge( self::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
- }
- /**
- * Get blocking information
- * @private
- * @param $bFromSlave \bool 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.
- */
- function getBlockedStatus( $bFromSlave = true ) {
- global $wgEnableSorbs, $wgProxyWhitelist;
- if ( -1 != $this->mBlockedby ) {
- wfDebug( "User::getBlockedStatus: already loaded.\n" );
- return;
- }
- wfProfileIn( __METHOD__ );
- wfDebug( __METHOD__.": checking...\n" );
- // Initialize data...
- // Otherwise something ends up stomping on $this->mBlockedby when
- // things get lazy-loaded later, causing false positive block hits
- // due to -1 !== 0. Probably session-related... Nothing should be
- // overwriting mBlockedby, surely?
- $this->load();
-
- $this->mBlockedby = 0;
- $this->mHideName = 0;
- $this->mAllowUsertalk = 0;
- $ip = wfGetIP();
- if ($this->isAllowed( 'ipblock-exempt' ) ) {
- # Exempt from all types of IP-block
- $ip = '';
- }
- # User/IP blocking
- $this->mBlock = new Block();
- $this->mBlock->fromMaster( !$bFromSlave );
- if ( $this->mBlock->load( $ip , $this->mId ) ) {
- wfDebug( __METHOD__.": Found block.\n" );
- $this->mBlockedby = $this->mBlock->mBy;
- $this->mBlockreason = $this->mBlock->mReason;
- $this->mHideName = $this->mBlock->mHideName;
- $this->mAllowUsertalk = $this->mBlock->mAllowUsertalk;
- if ( $this->isLoggedIn() ) {
- $this->spreadBlock();
- }
- } else {
- // Bug 13611: don't remove mBlock here, to allow account creation blocks to
- // apply to users. Note that the existence of $this->mBlock is not used to
- // check for edit blocks, $this->mBlockedby is instead.
- }
- # Proxy blocking
- if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
- # Local list
- if ( wfIsLocallyBlockedProxy( $ip ) ) {
- $this->mBlockedby = wfMsg( 'proxyblocker' );
- $this->mBlockreason = wfMsg( 'proxyblockreason' );
- }
- # DNSBL
- if ( !$this->mBlockedby && $wgEnableSorbs && !$this->getID() ) {
- if ( $this->inSorbsBlacklist( $ip ) ) {
- $this->mBlockedby = wfMsg( 'sorbs' );
- $this->mBlockreason = wfMsg( 'sorbsreason' );
- }
- }
- }
- # Extensions
- wfRunHooks( 'GetBlockedStatus', array( &$this ) );
- wfProfileOut( __METHOD__ );
- }
- /**
- * Whether the given IP is in the SORBS blacklist.
- *
- * @param $ip \string IP to check
- * @return \bool True if blacklisted.
- */
- function inSorbsBlacklist( $ip ) {
- global $wgEnableSorbs, $wgSorbsUrl;
- return $wgEnableSorbs &&
- $this->inDnsBlacklist( $ip, $wgSorbsUrl );
- }
- /**
- * Whether the given IP is in a given DNS blacklist.
- *
- * @param $ip \string IP to check
- * @param $base \string URL of the DNS blacklist
- * @return \bool True if blacklisted.
- */
- function inDnsBlacklist( $ip, $base ) {
- wfProfileIn( __METHOD__ );
- $found = false;
- $host = '';
- // FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
- if( IP::isIPv4($ip) ) {
- # Make hostname
- $host = "$ip.$base";
- # Send query
- $ipList = gethostbynamel( $host );
- if( $ipList ) {
- wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
- $found = true;
- } else {
- wfDebug( "Requested $host, not found in $base.\n" );
- }
- }
- wfProfileOut( __METHOD__ );
- return $found;
- }
- /**
- * Is this user subject to rate limiting?
- *
- * @return \bool True if rate limited
- */
- public function isPingLimitable() {
- global $wgRateLimitsExcludedGroups;
- global $wgRateLimitsExcludedIPs;
- if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
- // Deprecated, but kept for backwards-compatibility config
- return false;
- }
- if( in_array( wfGetIP(), $wgRateLimitsExcludedIPs ) ) {
- // No other good way currently to disable rate limits
- // for specific IPs. :P
- // But this is a crappy hack and should die.
- return false;
- }
- return !$this->isAllowed('noratelimit');
- }
- /**
- * Primitive rate limits: enforce maximum actions per time period
- * to put a brake on flooding.
- *
- * @note When using a shared cache like memcached, IP-address
- * last-hit counters will be shared across wikis.
- *
- * @param $action \string Action to enforce; 'edit' if unspecified
- * @return \bool True if a rate limiter was tripped
- */
- function pingLimiter( $action='edit' ) {
- # Call the 'PingLimiter' hook
- $result = false;
- if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
- return $result;
- }
- global $wgRateLimits;
- if( !isset( $wgRateLimits[$action] ) ) {
- return false;
- }
- # Some groups shouldn't trigger the ping limiter, ever
- if( !$this->isPingLimitable() )
- return false;
- global $wgMemc, $wgRateLimitLog;
- wfProfileIn( __METHOD__ );
- $limits = $wgRateLimits[$action];
- $keys = array();
- $id = $this->getId();
- $ip = wfGetIP();
- $userLimit = false;
- if( isset( $limits['anon'] ) && $id == 0 ) {
- $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
- }
- if( isset( $limits['user'] ) && $id != 0 ) {
- $userLimit = $limits['user'];
- }
- if( $this->isNewbie() ) {
- if( isset( $limits['newbie'] ) && $id != 0 ) {
- $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
- }
- if( isset( $limits['ip'] ) ) {
- $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'];
- }
- }
- // Check for group-specific permissions
- // If more than one group applies, use the group with the highest limit
- foreach ( $this->getGroups() as $group ) {
- if ( isset( $limits[$group] ) ) {
- if ( $userLimit === false || $limits[$group] > $userLimit ) {
- $userLimit = $limits[$group];
- }
- }
- }
- // Set the user limit key
- if ( $userLimit !== false ) {
- wfDebug( __METHOD__.": effective user limit: $userLimit\n" );
- $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
- }
- $triggered = false;
- foreach( $keys as $key => $limit ) {
- list( $max, $period ) = $limit;
- $summary = "(limit $max in {$period}s)";
- $count = $wgMemc->get( $key );
- if( $count ) {
- if( $count > $max ) {
- wfDebug( __METHOD__.": tripped! $key at $count $summary\n" );
- if( $wgRateLimitLog ) {
- @error_log( wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
- }
- $triggered = true;
- } else {
- wfDebug( __METHOD__.": ok. $key at $count $summary\n" );
- }
- } else {
- wfDebug( __METHOD__.": adding record for $key $summary\n" );
- $wgMemc->add( $key, 1, intval( $period ) );
- }
- $wgMemc->incr( $key );
- }
- wfProfileOut( __METHOD__ );
- return $triggered;
- }
- /**
- * Check if user is blocked
- *
- * @param $bFromSlave \bool Whether to check the slave database instead of the master
- * @return \bool True if blocked, false otherwise
- */
- function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
- wfDebug( "User::isBlocked: enter\n" );
- $this->getBlockedStatus( $bFromSlave );
- return $this->mBlockedby !== 0;
- }
- /**
- * Check if user is blocked from editing a particular article
- *
- * @param $title \string Title to check
- * @param $bFromSlave \bool Whether to check the slave database instead of the master
- * @return \bool True if blocked, false otherwise
- */
- function isBlockedFrom( $title, $bFromSlave = false ) {
- global $wgBlockAllowsUTEdit;
- wfProfileIn( __METHOD__ );
- wfDebug( __METHOD__.": enter\n" );
- wfDebug( __METHOD__.": asking isBlocked()\n" );
- $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 ) {
- $blocked = false;
- wfDebug( __METHOD__.": self-talk page, ignoring any blocks\n" );
- }
- wfProfileOut( __METHOD__ );
- return $blocked;
- }
- /**
- * If user is blocked, return the name of the user who placed the block
- * @return \string name of blocker
- */
- function blockedBy() {
- $this->getBlockedStatus();
- return $this->mBlockedby;
- }
- /**
- * If user is blocked, return the specified reason for the block
- * @return \string Blocking reason
- */
- function blockedFor() {
- $this->getBlockedStatus();
- return $this->mBlockreason;
- }
-
- /**
- * If user is blocked, return the ID for the block
- * @return \int Block ID
- */
- function getBlockId() {
- $this->getBlockedStatus();
- return ($this->mBlock ? $this->mBlock->mId : false);
- }
-
- /**
- * Check if user is blocked on all wikis.
- * Do not use for actual edit permission checks!
- * This is intented for quick UI checks.
- *
- * @param $ip \type{\string} IP address, uses current client if none given
- * @return \type{\bool} True if blocked, false otherwise
- */
- function isBlockedGlobally( $ip = '' ) {
- if( $this->mBlockedGlobally !== null ) {
- return $this->mBlockedGlobally;
- }
- // User is already an IP?
- if( IP::isIPAddress( $this->getName() ) ) {
- $ip = $this->getName();
- } else if( !$ip ) {
- $ip = wfGetIP();
- }
- $blocked = false;
- wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
- $this->mBlockedGlobally = (bool)$blocked;
- return $this->mBlockedGlobally;
- }
-
- /**
- * Check if user account is locked
- *
- * @return \type{\bool} True if locked, false otherwise
- */
- function isLocked() {
- if( $this->mLocked !== null ) {
- return $this->mLocked;
- }
- global $wgAuth;
- $authUser = $wgAuth->getUserInstance( $this );
- $this->mLocked = (bool)$authUser->isLocked();
- return $this->mLocked;
- }
-
- /**
- * Check if user account is hidden
- *
- * @return \type{\bool} True if hidden, false otherwise
- */
- function isHidden() {
- if( $this->mHideName !== null ) {
- return $this->mHideName;
- }
- $this->getBlockedStatus();
- if( !$this->mHideName ) {
- global $wgAuth;
- $authUser = $wgAuth->getUserInstance( $this );
- $this->mHideName = (bool)$authUser->isHidden();
- }
- return $this->mHideName;
- }
- /**
- * Get the user's ID.
- * @return \int The user's ID; 0 if the user is anonymous or nonexistent
- */
- function getId() {
- if( $this->mId === null and $this->mName !== null
- and User::isIP( $this->mName ) ) {
- // Special case, we know the user is anonymous
- return 0;
- } elseif( $this->mId === null ) {
- // Don't load if this was initialized from an ID
- $this->load();
- }
- return $this->mId;
- }
- /**
- * Set the user and reload all fields according to a given ID
- * @param $v \int User ID to reload
- */
- function setId( $v ) {
- $this->mId = $v;
- $this->clearInstanceCache( 'id' );
- }
- /**
- * Get the user name, or the IP of an anonymous user
- * @return \string User's name or IP address
- */
- function getName() {
- if ( !$this->mDataLoaded && $this->mFrom == 'name' ) {
- # Special case optimisation
- return $this->mName;
- } else {
- $this->load();
- if ( $this->mName === false ) {
- # Clean up IPs
- $this->mName = IP::sanitizeIP( wfGetIP() );
- }
- return $this->mName;
- }
- }
- /**
- * Set the user name.
- *
- * This does not reload fields from the database according to the given
- * name. Rather, it is used to create a temporary "nonexistent user" for
- * later addition to the database. It can also be used to set the IP
- * address for an anonymous user to something other than the current
- * remote IP.
- *
- * @note User::newFromName() has rougly the same function, when the named user
- * does not exist.
- * @param $str \string New user name to set
- */
- function setName( $str ) {
- $this->load();
- $this->mName = $str;
- }
- /**
- * Get the user's name escaped by underscores.
- * @return \string Username escaped by underscores.
- */
- function getTitleKey() {
- return str_replace( ' ', '_', $this->getName() );
- }
- /**
- * Check if the user has new messages.
- * @return \bool True if the user has new messages
- */
- function getNewtalk() {
- $this->load();
- # 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.
- if( !$this->mId ) {
- global $wgMemc;
- $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
- $newtalk = $wgMemc->get( $key );
- if( strval( $newtalk ) !== '' ) {
- $this->mNewtalk = (bool)$newtalk;
- } else {
- // Since we are caching this, make sure it is up to date by getting it
- // from the master
- $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
- $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
- }
- } else {
- $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
- }
- }
- return (bool)$this->mNewtalk;
- }
- /**
- * Return the talk page(s) this user has new messages on.
- * @return \type{\arrayof{\string}} Array of page URLs
- */
- function getNewMessageLinks() {
- $talks = array();
- if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
- return $talks;
- if (!$this->getNewtalk())
- return array();
- $up = $this->getUserPage();
- $utp = $up->getTalkPage();
- return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
- }
- /**
- * Internal uncached check for new messages
- *
- * @see getNewtalk()
- * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
- * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
- * @param $fromMaster \bool true to fetch from the master, false for a slave
- * @return \bool True if the user has new messages
- * @private
- */
- function checkNewtalk( $field, $id, $fromMaster = false ) {
- if ( $fromMaster ) {
- $db = wfGetDB( DB_MASTER );
- } else {
- $db = wfGetDB( DB_SLAVE );
- }
- $ok = $db->selectField( 'user_newtalk', $field,
- array( $field => $id ), __METHOD__ );
- return $ok !== false;
- }
- /**
- * Add or update the new messages flag
- * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
- * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
- * @return \bool True if successful, false otherwise
- * @private
- */
- function updateNewtalk( $field, $id ) {
- $dbw = wfGetDB( DB_MASTER );
- $dbw->insert( 'user_newtalk',
- array( $field => $id ),
- __METHOD__,
- 'IGNORE' );
- if ( $dbw->affectedRows() ) {
- wfDebug( __METHOD__.": set on ($field, $id)\n" );
- return true;
- } else {
- wfDebug( __METHOD__." already set ($field, $id)\n" );
- return false;
- }
- }
- /**
- * Clear the new messages flag for the given user
- * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
- * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
- * @return \bool True if successful, false otherwise
- * @private
- */
- function deleteNewtalk( $field, $id ) {
- $dbw = wfGetDB( DB_MASTER );
- $dbw->delete( 'user_newtalk',
- array( $field => $id ),
- __METHOD__ );
- if ( $dbw->affectedRows() ) {
- wfDebug( __METHOD__.": killed on ($field, $id)\n" );
- return true;
- } else {
- wfDebug( __METHOD__.": already gone ($field, $id)\n" );
- return false;
- }
- }
- /**
- * Update the 'You have new messages!' status.
- * @param $val \bool Whether the user has new messages
- */
- function setNewtalk( $val ) {
- if( wfReadOnly() ) {
- return;
- }
- $this->load();
- $this->mNewtalk = $val;
- if( $this->isAnon() ) {
- $field = 'user_ip';
- $id = $this->getName();
- } else {
- $field = 'user_id';
- $id = $this->getId();
- }
- global $wgMemc;
- if( $val ) {
- $changed = $this->updateNewtalk( $field, $id );
- } else {
- $changed = $this->deleteNewtalk( $field, $id );
- }
- if( $this->isAnon() ) {
- // Anons have a separate memcached space, since
- // user records aren't kept for them.
- $key = wfMemcKey( 'newtalk', 'ip', $id );
- $wgMemc->set( $key, $val ? 1 : 0, 1800 );
- }
- if ( $changed ) {
- $this->invalidateCache();
- }
- }
- /**
- * 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
- */
- private static function newTouchedTimestamp() {
- global $wgClockSkewFudge;
- return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
- }
- /**
- * Clear user data from memcached.
- * Use after applying fun updates to the database; caller's
- * responsibility to update user_touched if appropriate.
- *
- * Called implicitly from invalidateCache() and saveSettings().
- */
- private function clearSharedCache() {
- $this->load();
- if( $this->mId ) {
- global $wgMemc;
- $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
- }
- }
- /**
- * Immediately touch the user data cache for this account.
- * Updates user_touched field, and removes account data from memcached
- * for reload on the next hit.
- */
- function invalidateCache() {
- $this->load();
- if( $this->mId ) {
- $this->mTouched = self::newTouchedTimestamp();
- $dbw = wfGetDB( DB_MASTER );
- $dbw->update( 'user',
- array( 'user_touched' => $dbw->timestamp( $this->mTouched ) ),
- array( 'user_id' => $this->mId ),
- __METHOD__ );
- $this->clearSharedCache();
- }
- }
- /**
- * Validate the cache for this account.
- * @param $timestamp \string A timestamp in TS_MW format
- */
- function validateCache( $timestamp ) {
- $this->load();
- return ($timestamp >= $this->mTouched);
- }
- /**
- * Get the user touched timestamp
- */
- function getTouched() {
- $this->load();
- return $this->mTouched;
- }
- /**
- * Set the password and reset the random token.
- * Calls through to authentication plugin if necessary;
- * will have no effect if the auth plugin refuses to
- * pass the change through or if the legal password
- * checks fail.
- *
- * As a special case, setting the password to null
- * wipes it, so the account cannot be logged in until
- * a new password is set, for instance via e-mail.
- *
- * @param $str \string New password to set
- * @throws PasswordError on failure
- */
- function setPassword( $str ) {
- global $wgAuth;
- if( $str !== null ) {
- if( !$wgAuth->allowPasswordChange() ) {
- throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
- }
- if( !$this->isValidPassword( $str ) ) {
- global $wgMinimalPasswordLength;
- throw new PasswordError( wfMsgExt( 'passwordtooshort', array( 'parsemag' ),
- $wgMinimalPasswordLength ) );
- }
- }
- if( !$wgAuth->setPassword( $this, $str ) ) {
- throw new PasswordError( wfMsg( 'externaldberror' ) );
- }
- $this->setInternalPassword( $str );
- return true;
- }
- /**
- * Set the password and reset the random token unconditionally.
- *
- * @param $str \string New password to set
- */
- function setInternalPassword( $str ) {
- $this->load();
- $this->setToken();
- if( $str === null ) {
- // Save an invalid hash...
- $this->mPassword = '';
- } else {
- $this->mPassword = self::crypt( $str );
- }
- $this->mNewpassword = '';
- $this->mNewpassTime = null;
- }
-
- /**
- * Get the user's current token.
- * @return \string Token
- */
- function getToken() {
- $this->load();
- return $this->mToken;
- }
-
- /**
- * Set the random token (used for persistent authentication)
- * Called from loadDefaults() among other places.
- *
- * @param $token \string If specified, set the token to this value
- * @private
- */
- function setToken( $token = false ) {
- global $wgSecretKey, $wgProxyKey;
- $this->load();
- if ( !$token ) {
- if ( $wgSecretKey ) {
- $key = $wgSecretKey;
- } elseif ( $wgProxyKey ) {
- $key = $wgProxyKey;
- } else {
- $key = microtime();
- }
- $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId );
- } else {
- $this->mToken = $token;
- }
- }
-
- /**
- * Set the cookie password
- *
- * @param $str \string New cookie password
- * @private
- */
- function setCookiePassword( $str ) {
- $this->load();
- $this->mCookiePassword = md5( $str );
- }
- /**
- * Set the password for a password reminder or new account email
- *
- * @param $str \string New password to set
- * @param $throttle \bool If true, reset the throttle timestamp to the present
- */
- function setNewpassword( $str, $throttle = true ) {
- $this->load();
- $this->mNewpassword = self::crypt( $str );
- if ( $throttle ) {
- $this->mNewpassTime = wfTimestampNow();
- }
- }
- /**
- * Has password reminder email been sent within the last
- * $wgPasswordReminderResendTime hours?
- * @return \bool True or false
- */
- function isPasswordReminderThrottled() {
- global $wgPasswordReminderResendTime;
- $this->load();
- if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
- return false;
- }
- $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
- return time() < $expiry;
- }
- /**
- * Get the user's e-mail address
- * @return \string User's email address
- */
- function getEmail() {
- $this->load();
- wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
- return $this->mEmail;
- }
- /**
- * Get the timestamp of the user's e-mail authentication
- * @return \string TS_MW timestamp
- */
- function getEmailAuthenticationTimestamp() {
- $this->load();
- wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
- return $this->mEmailAuthenticated;
- }
- /**
- * Set the user's e-mail address
- * @param $str \string New e-mail address
- */
- function setEmail( $str ) {
- $this->load();
- $this->mEmail = $str;
- wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
- }
- /**
- * Get the user's real name
- * @return \string User's real name
- */
- function getRealName() {
- $this->load();
- return $this->mRealName;
- }
- /**
- * Set the user's real name
- * @param $str \string New real name
- */
- function setRealName( $str ) {
- $this->load();
- …
Large files files are truncated, but you can click here to view the full file