/package/app/html5/html5lib/v1.5.9a/tests/selenium_framework/includes/User.php
PHP | 3854 lines | 2333 code | 345 blank | 1176 comment | 386 complexity | 928781cef81b367ef32bd22e70e3b2e2 MD5 | raw file
Possible License(s): AGPL-3.0, GPL-3.0, BSD-3-Clause, LGPL-2.1, GPL-2.0, LGPL-3.0, JSON, MPL-2.0-no-copyleft-exception, Apache-2.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', 8 );
- /**
- * 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 {
- /**
- * Global constants made accessible as class constants so that autoloader
- * magic can be used.
- */
- const USER_TOKEN_LENGTH = USER_TOKEN_LENGTH;
- const MW_USER_VERSION = MW_USER_VERSION;
- const EDIT_TOKEN_SUFFIX = EDIT_TOKEN_SUFFIX;
- /**
- * 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(
- // user table
- 'mId',
- 'mName',
- 'mRealName',
- 'mPassword',
- 'mNewpassword',
- 'mNewpassTime',
- 'mEmail',
- 'mTouched',
- 'mToken',
- 'mEmailAuthenticated',
- 'mEmailToken',
- 'mEmailTokenExpires',
- 'mRegistration',
- 'mEditCount',
- // user_group table
- 'mGroups',
- // user_properties table
- 'mOptionOverrides',
- );
- /**
- * Array of Strings 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',
- 'deletedtext',
- 'deleterevision',
- 'disableaccount',
- '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',
- 'selenium',
- 'sendemail',
- '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, $mTouched, $mToken, $mEmailAuthenticated,
- $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups, $mOptionOverrides;
- //@}
- /**
- * Bool Whether the cache variables have been loaded.
- */
- var $mDataLoaded, $mAuthLoaded, $mOptionsLoaded;
- /**
- * 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;
- /**
- * Lazy-initialized variables, invalidated with clearInstanceCache
- */
- var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
- $mBlockreason, $mBlock, $mEffectiveGroups, $mBlockedGlobally,
- $mLocked, $mHideName, $mOptions;
- static $idCacheByName = array();
- /**
- * 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 __construct() {
- $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( "User: 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( "User: 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();
- $this->loadOptions();
- 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 String|Bool Validate username. Takes the same parameters as
- * User::getCanonicalName(), except that true is accepted as an alias
- * for 'valid', for BC.
- *
- * @return User object, or 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.
- */
- static function newFromName( $name, $validate = 'valid' ) {
- if ( $validate === true ) {
- $validate = 'valid';
- }
- $name = self::getCanonicalName( $name, $validate );
- if ( $name === false ) {
- return false;
- } 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 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 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 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 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 ), __METHOD__ );
- }
- /**
- * 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 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;
- }
- if ( isset( self::$idCacheByName[$name] ) ) {
- return self::$idCacheByName[$name];
- }
- $dbr = wfGetDB( DB_SLAVE );
- $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
- if ( $s === false ) {
- $result = null;
- } else {
- $result = $s->user_id;
- }
- self::$idCacheByName[$name] = $result;
- if ( count( self::$idCacheByName ) > 1000 ) {
- self::$idCacheByName = array();
- }
- return $result;
- }
- /**
- * Reset the cache used in idFromName(). For use in tests.
- */
- public static function resetIdByNameCache() {
- self::$idCacheByName = array();
- }
- /**
- * 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 to match
- * @return Bool
- */
- 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 to match
- * @return Bool
- */
- 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 to match
- * @return Bool
- */
- 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 blacklisting may be added here rather than in
- * isValidUserName() to avoid disrupting existing accounts.
- *
- * @param $name String to match
- * @return Bool
- */
- static function isCreatableName( $name ) {
- global $wgInvalidUsernameCharacters;
- // Ensure that the username isn't longer than 235 bytes, so that
- // (at least for the builtin skins) user javascript and css files
- // will work. (bug 23080)
- if( strlen( $name ) > 235 ) {
- wfDebugLog( 'username', __METHOD__ .
- ": '$name' invalid due to length" );
- return false;
- }
- if( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
- wfDebugLog( 'username', __METHOD__ .
- ": '$name' invalid due to wgInvalidUsernameCharacters" );
- return false;
- }
- return self::isUsableName( $name );
- }
- /**
- * Is the input a valid password for this user?
- *
- * @param $password String Desired password
- * @return Bool
- */
- function isValidPassword( $password ) {
- //simple boolean wrapper for getPasswordValidity
- return $this->getPasswordValidity( $password ) === true;
- }
- /**
- * Given unvalidated password input, return error message on failure.
- *
- * @param $password String Desired password
- * @return mixed: true on success, string or array of error message on failure
- */
- function getPasswordValidity( $password ) {
- global $wgMinimalPasswordLength, $wgContLang;
- static $blockedLogins = array(
- 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
- 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
- );
- $result = false; //init $result to false for the internal checks
- if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
- return $result;
- if ( $result === false ) {
- if( strlen( $password ) < $wgMinimalPasswordLength ) {
- return 'passwordtooshort';
- } 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';
- } else {
- //it seems weird returning true 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;
- }
- } elseif( $result === true ) {
- return true;
- } else {
- return $result; //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 $addr String E-mail address
- * @return Bool
- */
- public static function isValidEmailAddr( $addr ) {
- $result = null;
- if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
- return $result;
- }
- // Please note strings below are enclosed in brackets [], this make the
- // hyphen "-" a range indicator. Hence it is double backslashed below.
- // See bug 26948
- $rfc5322_atext = "a-z0-9!#$%&'*+\\-\/=?^_`{|}~" ;
- $rfc1034_ldh_str = "a-z0-9\\-" ;
- $HTML5_email_regexp = "/
- ^ # start of string
- [$rfc5322_atext\\.]+ # user part which is liberal :p
- @ # 'apostrophe'
- [$rfc1034_ldh_str]+ # First domain part
- (\\.[$rfc1034_ldh_str]+)* # Following part prefixed with a dot
- $ # End of string
- /ix" ; // case Insensitive, eXtended
- return (bool) preg_match( $HTML5_email_regexp, $addr );
- }
- /**
- * Given unvalidated user input, return a canonical username, or false if
- * the username is invalid.
- * @param $name String User input
- * @param $validate 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
- 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 $wgRequest;
- $this->mId = 0;
- $this->mName = $name;
- $this->mRealName = '';
- $this->mPassword = $this->mNewpassword = '';
- $this->mNewpassTime = null;
- $this->mEmail = '';
- $this->mOptionOverrides = null;
- $this->mOptionsLoaded = false;
- if( $wgRequest->getCookie( 'LoggedOut' ) !== null ) {
- $this->mTouched = wfTimestamp( TS_MW, $wgRequest->getCookie( '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__ );
- }
- /**
- * 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 $wgRequest, $wgExternalAuthType, $wgAutocreatePolicy;
- $result = null;
- wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
- if ( $result !== null ) {
- return $result;
- }
- if ( $wgExternalAuthType && $wgAutocreatePolicy == 'view' ) {
- $extUser = ExternalUser::newFromCookie();
- if ( $extUser ) {
- # TODO: Automatically create the user here (or probably a bit
- # lower down, in fact)
- }
- }
- if ( $wgRequest->getCookie( 'UserID' ) !== null ) {
- $sId = intval( $wgRequest->getCookie( '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 ( $wgRequest->getCookie('UserName') !== null ) {
- $sName = $wgRequest->getCookie('UserName');
- $_SESSION['wsUserName'] = $sName;
- } else {
- $this->loadDefaults();
- return false;
- }
- $this->mId = $sId;
- if ( !$this->loadFromId() ) {
- # Not a valid ID, loadFromId has switched the object to anon for us
- return false;
- }
- global $wgBlockDisablesLogin;
- if( $wgBlockDisablesLogin && $this->isBlocked() ) {
- # User blocked and we've disabled blocked user logins
- $this->loadDefaults();
- return false;
- }
- if ( isset( $_SESSION['wsToken'] ) ) {
- $passwordCorrect = $_SESSION['wsToken'] == $this->mToken;
- $from = 'session';
- } else if ( $wgRequest->getCookie( 'Token' ) !== null ) {
- $passwordCorrect = $this->mToken == $wgRequest->getCookie( 'Token' );
- $from = 'cookie';
- } else {
- # No session or persistent login cookie
- $this->loadDefaults();
- return false;
- }
- if ( ( $sName == $this->mName ) && $passwordCorrect ) {
- $_SESSION['wsToken'] = $this->mToken;
- wfDebug( "User: logged in from $from\n" );
- return true;
- } else {
- # Invalid credentials
- wfDebug( "User: 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 Array 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();
- foreach ( $res as $row ) {
- $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;
- $this->mOptions = 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 Array of String options
- */
- static function getDefaultOptions() {
- global $wgNamespacesToBeSearchedDefault;
- /**
- * Site defaults will override the global/language defaults
- */
- global $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
- $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptionOverrides();
- /**
- * default language setting
- */
- $variant = $wgContLang->getDefaultVariant();
- $defOpt['variant'] = $variant;
- $defOpt['language'] = $variant;
- foreach( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
- $defOpt['searchNs'.$nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
- }
- $defOpt['skin'] = $wgDefaultSkin;
- 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 null;
- }
- }
- /**
- * 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 $wgProxyWhitelist, $wgUser;
- if ( -1 != $this->mBlockedby ) {
- 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;
- # Check if we are looking at an IP or a logged-in user
- if ( $this->isIP( $this->getName() ) ) {
- $ip = $this->getName();
- } else {
- # Check if we are looking at the current user
- # If we don't, and the user is logged in, we don't know about
- # his IP / autoblock status, so ignore autoblock of current user's IP
- if ( $this->getID() != $wgUser->getID() ) {
- $ip = '';
- } else {
- # Get IP of current user
- $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;
- if( $this->mBlockedby == 0 )
- $this->mBlockedby = $this->mBlock->mByName;
- $this->mBlockreason = $this->mBlock->mReason;
- $this->mHideName = $this->mBlock->mHideName;
- $this->mAllowUsertalk = $this->mBlock->mAllowUsertalk;
- if ( $this->isLoggedIn() && $wgUser->getID() == $this->getID() ) {
- $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 && !$this->getID() ) {
- if ( $this->isDnsBlacklisted( $ip ) ) {
- $this->mBlockedby = wfMsg( 'sorbs' );
- $this->mBlockreason = wfMsg( 'sorbsreason' );
- }
- }
- }
- # Extensions
- wfRunHooks( 'GetBlockedStatus', array( &$this ) );
- wfProfileOut( __METHOD__ );
- }
- /**
- * Whether the given IP is in a DNS blacklist.
- *
- * @param $ip String IP to check
- * @param $checkWhitelist Bool: whether to check the whitelist first
- * @return Bool True if blacklisted.
- */
- function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
- global $wgEnableSorbs, $wgEnableDnsBlacklist,
- $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
- if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs )
- return false;
- if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) )
- return false;
- $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
- return $this->inDnsBlacklist( $ip, $urls );
- }
- /**
- * Whether the given IP is in a given DNS blacklist.
- *
- * @param $ip String IP to check
- * @param $bases String|Array of Strings: URL of the DNS blacklist
- * @return Bool True if blacklisted.
- */
- function inDnsBlacklist( $ip, $bases ) {
- wfProfileIn( __METHOD__ );
- $found = false;
- // FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
- if( IP::isIPv4( $ip ) ) {
- # Reverse IP, bug 21255
- $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
- foreach( (array)$bases as $base ) {
- # Make hostname
- $host = "$ipReversed.$base";
- # Send query
- $ipList = gethostbynamel( $host );
- if( $ipList ) {
- wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
- $found = true;
- break;
- } 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 );
- // Already pinged?
- 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, 0, intval( $period ) ); // first ping
- }
- $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
- $this->getBlockedStatus( $bFromSlave );
- return $this->mBlockedby !== 0;
- }
- /**
- * Check if user is blocked from editing a particular article
- *
- * @param $title Title to check
- * @param $bFromSlave Bool whether to check the slave database instead of the master
- * @return Bool
- */
- 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 ) {
- $blocked = false;
- wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
- }
- wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
- 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 String IP address, uses current client if none given
- * @return 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 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 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 Array of String 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 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 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 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() {
- if( wfReadOnly() ) {
- return;
- }
- $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
- * @return String 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;
- $valid = $this->getPasswordValidity( $str );
- if ( is_array( $valid ) ) {
- $message = array_shift( $valid );
- $params = $valid;
- } else {
- $message = $valid;
- $params = array( $wgMinimalPasswordLength );
- }
- throw new PasswordError( wfMsgExt( $message, array( 'parsemag' ), $params ) );…
Large files files are truncated, but you can click here to view the full file