/includes/User.php
PHP | 4224 lines | 2552 code | 348 blank | 1324 comment | 386 complexity | 047c26b9c0b2fb034bde9e14b2271929 MD5 | raw file
Possible License(s): GPL-2.0, Apache-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.
- *
- * This program is free software; you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation; either version 2 of the License, or
- * (at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License along
- * with this program; if not, write to the Free Software Foundation, Inc.,
- * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- * http://www.gnu.org/copyleft/gpl.html
- *
- * @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;
- /**
- * Maximum items in $mWatchedItems
- */
- const MAX_WATCHED_ITEMS_CACHE = 100;
- /**
- * 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_groups 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',
- 'deletelogentry',
- 'deleterevision',
- 'edit',
- 'editinterface',
- 'editprotected',
- 'editusercssjs', #deprecated
- 'editusercss',
- 'edituserjs',
- 'hideuser',
- 'import',
- 'importupload',
- 'ipblock-exempt',
- 'markbotedits',
- 'mergehistory',
- 'minoredit',
- 'move',
- 'movefile',
- 'move-rootuserpages',
- 'move-subpages',
- 'nominornewtalk',
- 'noratelimit',
- 'override-export-depth',
- 'passwordreset',
- 'patrol',
- 'patrolmarks',
- 'protect',
- 'proxyunbannable',
- 'purge',
- 'read',
- 'reupload',
- 'reupload-own',
- 'reupload-shared',
- 'rollback',
- 'sendemail',
- 'siteadmin',
- 'suppressionlog',
- 'suppressredirect',
- 'suppressrevision',
- 'unblockself',
- '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, $mEditCount,
- $mGroups, $mOptionOverrides;
- //@}
- /**
- * Bool Whether the cache variables have been loaded.
- */
- //@{
- var $mOptionsLoaded;
- /**
- * Array with already loaded items or true if all items have been loaded.
- */
- private $mLoadedItems = array();
- //@}
- /**
- * String Initialization data source if mLoadedItems!==true. 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, $mRights,
- $mBlockreason, $mEffectiveGroups, $mImplicitGroups, $mFormerGroups, $mBlockedGlobally,
- $mLocked, $mHideName, $mOptions;
- /**
- * @var WebRequest
- */
- private $mRequest;
- /**
- * @var Block
- */
- var $mBlock;
- /**
- * @var bool
- */
- var $mAllowUsertalk;
- /**
- * @var Block
- */
- private $mBlockedFromCreateAccount = false;
- /**
- * @var Array
- */
- private $mWatchedItems = array();
- 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' );
- }
- /**
- * @return String
- */
- function __toString(){
- return $this->getName();
- }
- /**
- * Load the user table data for this object from the source given by mFrom.
- */
- public function load() {
- if ( $this->mLoadedItems === true ) {
- return;
- }
- wfProfileIn( __METHOD__ );
- # Set it now to avoid infinite recursion in accessors
- $this->mLoadedItems = 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
- */
- public 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
- */
- public 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.
- */
- public 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';
- $u->setItemLoaded( '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
- */
- public static function newFromId( $id ) {
- $u = new User;
- $u->mId = $id;
- $u->mFrom = 'id';
- $u->setItemLoaded( '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 object, or null
- */
- public 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.
- *
- * @param $request WebRequest object to use; $wgRequest will be used if
- * ommited.
- * @return User object
- */
- public static function newFromSession( WebRequest $request = null ) {
- $user = new User;
- $user->mFrom = 'session';
- $user->mRequest = $request;
- return $user;
- }
- /**
- * Create a new user object from a user row.
- * The row should have the following fields from the user table in it:
- * - either user_name or user_id to load further data if needed (or both)
- * - user_real_name
- * - all other fields (email, password, etc.)
- * It is useless to provide the remaining fields if either user_id,
- * user_name and user_real_name are not provided because the whole row
- * will be loaded once more from the database when accessing them.
- *
- * @param $row Array A row from the user table
- * @return User
- */
- public 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|bool The corresponding username
- */
- public static function whoIs( $id ) {
- return UserCache::singleton()->getProp( $id, 'name' );
- }
- /**
- * Get the real name of a user given their user ID
- *
- * @param $id Int User ID
- * @return String|bool The corresponding user's real name
- */
- public static function whoIsReal( $id ) {
- return UserCache::singleton()->getProp( $id, 'real_name' );
- }
- /**
- * 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
- */
- public 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
- */
- public static function isIP( $name ) {
- return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP::isIPv6($name);
- }
- /**
- * 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
- */
- public 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
- */
- public 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 = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
- }
- 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
- */
- public 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;
- }
- // Preg yells if you try to give it an empty string
- if( $wgInvalidUsernameCharacters !== '' ) {
- 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
- */
- public 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
- */
- public 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
- * @deprecated since 1.18 call Sanitizer::isValidEmail() directly
- */
- public static function isValidEmailAddr( $addr ) {
- wfDeprecated( __METHOD__, '1.18' );
- return Sanitizer::validateEmail( $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
- *
- * @return bool|string
- */
- public 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
- */
- public 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.
- *
- * @return String new random password
- */
- public static function randomPassword() {
- global $wgMinimalPasswordLength;
- // Decide the final password length based on our min password length, stopping at a minimum of 10 chars
- $length = max( 10, $wgMinimalPasswordLength );
- // Multiply by 1.25 to get the number of hex characters we need
- $length = $length * 1.25;
- // Generate random hex chars
- $hex = MWCryptRand::generateHex( $length );
- // Convert from base 16 to base 32 to get a proper password like string
- return wfBaseConvert( $hex, 16, 32 );
- }
- /**
- * Set cached properties to default.
- *
- * @note This no longer clears uncached lazy-initialised properties;
- * the constructor does that instead.
- *
- * @param $name string
- */
- public function loadDefaults( $name = false ) {
- wfProfileIn( __METHOD__ );
- $this->mId = 0;
- $this->mName = $name;
- $this->mRealName = '';
- $this->mPassword = $this->mNewpassword = '';
- $this->mNewpassTime = null;
- $this->mEmail = '';
- $this->mOptionOverrides = null;
- $this->mOptionsLoaded = false;
- $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
- if( $loggedOut !== null ) {
- $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
- } else {
- $this->mTouched = '0'; # Allow any pages to be cached
- }
- $this->mToken = null; // Don't run cryptographic functions till we need a token
- $this->mEmailAuthenticated = null;
- $this->mEmailToken = '';
- $this->mEmailTokenExpires = null;
- $this->mRegistration = wfTimestamp( TS_MW );
- $this->mGroups = array();
- wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
- wfProfileOut( __METHOD__ );
- }
- /**
- * Return whether an item has been loaded.
- *
- * @param $item String: item to check. Current possibilities:
- * - id
- * - name
- * - realname
- * @param $all String: 'all' to check if the whole object has been loaded
- * or any other string to check if only the item is available (e.g.
- * for optimisation)
- * @return Boolean
- */
- public function isItemLoaded( $item, $all = 'all' ) {
- return ( $this->mLoadedItems === true && $all === 'all' ) ||
- ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
- }
- /**
- * Set that an item has been loaded
- *
- * @param $item String
- */
- private function setItemLoaded( $item ) {
- if ( is_array( $this->mLoadedItems ) ) {
- $this->mLoadedItems[$item] = true;
- }
- }
- /**
- * 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 $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)
- }
- }
- $request = $this->getRequest();
- $cookieId = $request->getCookie( 'UserID' );
- $sessId = $request->getSessionData( 'wsUserID' );
- if ( $cookieId !== null ) {
- $sId = intval( $cookieId );
- if( $sessId !== null && $cookieId != $sessId ) {
- $this->loadDefaults(); // Possible collision!
- wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
- cookie user ID ($sId) don't match!" );
- return false;
- }
- $request->setSessionData( 'wsUserID', $sId );
- } elseif ( $sessId !== null && $sessId != 0 ) {
- $sId = $sessId;
- } else {
- $this->loadDefaults();
- return false;
- }
- if ( $request->getSessionData( 'wsUserName' ) !== null ) {
- $sName = $request->getSessionData( 'wsUserName' );
- } elseif ( $request->getCookie( 'UserName' ) !== null ) {
- $sName = $request->getCookie( 'UserName' );
- $request->setSessionData( 'wsUserName', $sName );
- } else {
- $this->loadDefaults();
- return false;
- }
- $proposedUser = User::newFromId( $sId );
- if ( !$proposedUser->isLoggedIn() ) {
- # Not a valid ID
- $this->loadDefaults();
- return false;
- }
- global $wgBlockDisablesLogin;
- if( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
- # User blocked and we've disabled blocked user logins
- $this->loadDefaults();
- return false;
- }
- if ( $request->getSessionData( 'wsToken' ) ) {
- $passwordCorrect = $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' );
- $from = 'session';
- } elseif ( $request->getCookie( 'Token' ) ) {
- $passwordCorrect = $proposedUser->getToken( false ) === $request->getCookie( 'Token' );
- $from = 'cookie';
- } else {
- # No session or persistent login cookie
- $this->loadDefaults();
- return false;
- }
- if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
- $this->loadFromUserObject( $proposedUser );
- $request->setSessionData( '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
- */
- public 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', self::selectFields(), 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.
- */
- public function loadFromRow( $row ) {
- $all = true;
- $this->mGroups = null; // deferred
- if ( isset( $row->user_name ) ) {
- $this->mName = $row->user_name;
- $this->mFrom = 'name';
- $this->setItemLoaded( 'name' );
- } else {
- $all = false;
- }
- if ( isset( $row->user_real_name ) ) {
- $this->mRealName = $row->user_real_name;
- $this->setItemLoaded( 'realname' );
- } else {
- $all = false;
- }
- if ( isset( $row->user_id ) ) {
- $this->mId = intval( $row->user_id );
- $this->mFrom = 'id';
- $this->setItemLoaded( 'id' );
- } else {
- $all = false;
- }
- if ( isset( $row->user_editcount ) ) {
- $this->mEditCount = $row->user_editcount;
- } else {
- $all = false;
- }
- if ( isset( $row->user_password ) ) {
- $this->mPassword = $row->user_password;
- $this->mNewpassword = $row->user_newpassword;
- $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
- $this->mEmail = $row->user_email;
- if ( isset( $row->user_options ) ) {
- $this->decodeOptions( $row->user_options );
- }
- $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
- $this->mToken = $row->user_token;
- if ( $this->mToken == '' ) {
- $this->mToken = null;
- }
- $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 );
- } else {
- $all = false;
- }
- if ( $all ) {
- $this->mLoadedItems = true;
- }
- }
- /**
- * Load the data for this user object from another user object.
- *
- * @param $user User
- */
- protected function loadFromUserObject( $user ) {
- $user->load();
- $user->loadGroups();
- $user->loadOptions();
- foreach ( self::$mCacheVars as $var ) {
- $this->$var = $user->$var;
- }
- }
- /**
- * 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;
- }
- }
- }
- /**
- * Add the user to the group if he/she meets given criteria.
- *
- * Contrary to autopromotion by \ref $wgAutopromote, the group will be
- * possible to remove manually via Special:UserRights. In such case it
- * will not be re-added automatically. The user will also not lose the
- * group if they no longer meet the criteria.
- *
- * @param $event String key in $wgAutopromoteOnce (each one has groups/criteria)
- *
- * @return array Array of groups the user has been promoted to.
- *
- * @see $wgAutopromoteOnce
- */
- public function addAutopromoteOnceGroups( $event ) {
- global $wgAutopromoteOnceLogInRC;
- $toPromote = array();
- if ( $this->getId() ) {
- $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
- if ( count( $toPromote ) ) {
- $oldGroups = $this->getGroups(); // previous groups
- foreach ( $toPromote as $group ) {
- $this->addGroup( $group );
- }
- $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
- $log = new LogPage( 'rights', $wgAutopromoteOnceLogInRC /* in RC? */ );
- $log->addEntry( 'autopromote',
- $this->getUserPage(),
- '', // no comment
- // These group names are "list to texted"-ed in class LogPage.
- array( implode( ', ', $oldGroups ), implode( ', ', $newGroups ) )
- );
- }
- }
- return $toPromote;
- }
- /**
- * Clear various cached data stored in this object.
- * @param $reloadFrom bool|String Reload user and user_groups table data from a
- * given source. May be "name", "id", "defaults", "session", or false for
- * no reload.
- */
- public function clearInstanceCache( $reloadFrom = false ) {
- $this->mNewtalk = -1;
- $this->mDatePreference = null;
- $this->mBlockedby = -1; # Unset
- $this->mHash = false;
- $this->mRights = null;
- $this->mEffectiveGroups = null;
- $this->mImplicitGroups = null;
- $this->mOptions = null;
- if ( $reloadFrom ) {
- $this->mLoadedItems = array();
- $this->mFrom = $reloadFrom;
- }
- }
- /**
- * Combine the language default options with any site-specific options
- * and add the default language variants.
- *
- * @return Array of String options
- */
- public static function getDefaultOptions() {
- global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
- $defOpt = $wgDefaultUserOptions;
- # 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;
- // FIXME: Ideally we'd cache the results of this function so the hook is only run once,
- // but that breaks the parser tests because they rely on being able to change $wgContLang
- // mid-request and see that change reflected in the return value of this function.
- // Which is insane and would never happen during normal MW operation, but is also not
- // likely to get fixed unless and until we context-ify everything.
- // See also https://www.mediawiki.org/wiki/Special:Code/MediaWiki/101488#c25275
- wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
- 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
- * @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.
- */
- private 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();
- # We only need to worry about passing the IP address to the Block generator if the
- # user is not immune to autoblocks/hardblocks, and they are the current user so we
- # know which IP address they're actually coming from
- if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
- $ip = $this->getRequest()->getIP();
- } else {
- $ip = null;
- }
- # User/IP blocking
- $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
- # Proxy blocking
- if ( !$block instanceof Block && $ip !== null && !$this->isAllowed( 'proxyunbannable' )
- && !in_array( $ip, $wgProxyWhitelist ) )
- {
- # Local list
- if ( self::isLocallyBlockedProxy( $ip ) ) {
- $block = new Block;
- $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
- $block->mReason = wfMessage( 'proxyblockreason' )->text();
- $block->setTarget( $ip );
- } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
- $block = new Block;
- $block->setBlocker( wfMessage( 'sorbs' )->text() );
- $block->mReason = wfMessage( 'sorbsreason' )->text();
- $block->setTarget( $ip );
- }
- }
- if ( $block instanceof Block ) {
- wfDebug( __METHOD__ . ": Found block.\n" );
- $this->mBlock = $block;
- $this->mBlockedby = $block->getByName();
- $this->mBlockreason = $block->mReason;
- $this->mHideName = $block->mHideName;
- $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
- } else {
- $this->mBlockedby = '';
- $this->mHideName = 0;
- $this->mAllowUsertalk = false;
- }
- # 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.
- */
- public 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.
- */
- public function inDnsBlacklist( $ip, $bases ) {
- wfProfileIn( __METHOD__ );
- $found = false;
- // @todo 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
- # If we have an access key, use that too (ProjectHoneypot, etc.)
- if( is_array( $base ) ) {
- if( count( $base ) >= 2 ) {
- # Access key is 1, base URL is 0
- $host = "{$base[1]}.$ipReversed.{$base[0]}";
- } else {
- $host = "$ipReversed.{$base[0]}";
- }
- } else {
- $host = "$ipReversed.$base";
- }
- # Send query
- $ipList = gethostbynamel( $host );
- if( $ipList ) {
- wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
- $found = true;
- break;
- } else {
- wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base.\n" );
- }
- }
- }
- wfProfileOut( __METHOD__ );
- return $found;
- }
- /**
- * Check if an IP address is in the local proxy list
- *
- * @param $ip string
- *
- * @return bool
- */
- public static function isLocallyBlockedProxy( $ip ) {
- global $wgProxyList;
- if ( !$wgProxyList ) {
- return false;
- }
- wfProfileIn( __METHOD__ );
- if ( !is_array( $wgProxyList ) ) {
- # Load from the specified file
- $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
- }
- if ( !is_array( $wgProxyList ) ) {
- $ret = false;
- } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
- $ret = true;
- } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
- # Old-style flipped proxy list
- $ret = true;
- } else {
- $ret = false;
- }
- wfProfileOut( __METHOD__ );
- return $ret;
- }
- /**
- * Is this user subject to rate limiting?
- *
- * @return Bool True if rate limited
- */
- public function isPingLimitable() {
- global $wgRateLimitsExcludedIPs;
- if( in_array( $this->getRequest()->getIP(), $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
- */
- public 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 = $this->getRequest()->getIP();
- $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 ) {
- wfSuppressWarnings();
- file_put_contents( $wgRateLimitLog, wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", FILE_APPEND );
- wfRestoreWarnings();
- }
- $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
- */
- public function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
- return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
- }
- /**
- * Get the block affecting the user, or null if the user is not blocked
- *
- * @param $bFromSlave Bool Whether to check the slave database instead of the master
- * @return Block|null
- */
- public function getBlock( $bFromSlave = true ){
- $this->getBlockedStatus( $bFromSlave );
- return $this->mBlock instanceof Block ? $this->mBlock : null;
- }
- /**
- * 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
- */
- public function blockedBy() {
- $this->getBlockedStatus();
- return $this->mBlockedby;
- }
- /**
- * If user is blocked, return the specified reason for the block
- * @return String Blocking reason
- */
- public function blockedFor() {
- $this->getBlockedStatus();
- return $this->mBlockreason;
- }
- /**
- * If user is blocked, return the ID for the block
- * @return Int Block ID
- */
- public function getBlockId() {
- $this->getBlockedStatus();
- return ( $this->mBlock ? $this->mBlock->getId() : 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
- */
- public function isBlockedGlobally( $ip = '' ) {
- if( $this->mBlockedGlobally !== null ) {
- return $this->mBlockedGlobally;
- }
- // User is already an IP?
- if( IP::isIPAddress( $this->getName() ) ) {
- $ip = $this->getName();
- } elseif( !$ip ) {
- $ip = $this->getRequest()->getIP();
- }
- $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
- */
- public 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
- */
- public 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
- */
- public function getId() {
- if( $this->mId === null && $this->mName !== null
- && User::isIP( $this->mName ) ) {
- // Special case, we know the user is anonymous
- return 0;
- } elseif( !$this->isItemLoaded( 'id' ) ) {
- // 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
- */
- public 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
- */
- public function getName() {
- if ( $this->isItemLoaded( 'name', 'only' ) ) {
- # Special case optimisation
- return $this->mName;
- } else {
- $this->load();
- if ( $this->mName === false ) {
- # Clean up IPs
- $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
- }
- 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
- */
- public function setName( $str ) {
- $this->load();
- $this->mName = $str;
- }
- /**
- * Get the user's name escaped by underscores.
- * @return String Username escaped by underscores.
- */
- public function getTitleKey() {
- return str_replace( ' ', '_', $this->getName() );
- }
- /**
- * Check if the user has new messages.
- * @return Bool True if the user has new messages
- */
- public function getNewtalk() {
- $this->load();
- # Load the newtalk status if it is unloaded (mNewtalk=-1)
- 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 $wgDi…
Large files files are truncated, but you can click here to view the full file