When serializing Message, don't try to unstub StubUserLang
[mediawiki.git] / includes / user / User.php
blob6ec0ff0071a68ff42bccf9011fdd1db6cd6b75a0
1 <?php
2 /**
3 * Implements the User class for the %MediaWiki software.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
23 use MediaWiki\Session\SessionManager;
25 /**
26 * String Some punctuation to prevent editing from broken text-mangling proxies.
27 * @ingroup Constants
29 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
31 /**
32 * The User object encapsulates all of the user-specific settings (user_id,
33 * name, rights, email address, options, last login time). Client
34 * classes use the getXXX() functions to access these fields. These functions
35 * do all the work of determining whether the user is logged in,
36 * whether the requested option can be satisfied from cookies or
37 * whether a database query is needed. Most of the settings needed
38 * for rendering normal pages are set in the cookie to minimize use
39 * of the database.
41 class User implements IDBAccessObject {
42 /**
43 * @const int Number of characters in user_token field.
45 const TOKEN_LENGTH = 32;
47 /**
48 * Global constant made accessible as class constants so that autoloader
49 * magic can be used.
51 const EDIT_TOKEN_SUFFIX = EDIT_TOKEN_SUFFIX;
53 /**
54 * @const int Serialized record version.
56 const VERSION = 10;
58 /**
59 * Maximum items in $mWatchedItems
61 const MAX_WATCHED_ITEMS_CACHE = 100;
63 /**
64 * Exclude user options that are set to their default value.
65 * @since 1.25
67 const GETOPTIONS_EXCLUDE_DEFAULTS = 1;
69 /**
70 * Array of Strings List of member variables which are saved to the
71 * shared cache (memcached). Any operation which changes the
72 * corresponding database fields must call a cache-clearing function.
73 * @showinitializer
75 protected static $mCacheVars = array(
76 // user table
77 'mId',
78 'mName',
79 'mRealName',
80 'mEmail',
81 'mTouched',
82 'mToken',
83 'mEmailAuthenticated',
84 'mEmailToken',
85 'mEmailTokenExpires',
86 'mRegistration',
87 'mEditCount',
88 // user_groups table
89 'mGroups',
90 // user_properties table
91 'mOptionOverrides',
94 /**
95 * Array of Strings Core rights.
96 * Each of these should have a corresponding message of the form
97 * "right-$right".
98 * @showinitializer
100 protected static $mCoreRights = array(
101 'apihighlimits',
102 'applychangetags',
103 'autoconfirmed',
104 'autocreateaccount',
105 'autopatrol',
106 'bigdelete',
107 'block',
108 'blockemail',
109 'bot',
110 'browsearchive',
111 'changetags',
112 'createaccount',
113 'createpage',
114 'createtalk',
115 'delete',
116 'deletedhistory',
117 'deletedtext',
118 'deletelogentry',
119 'deleterevision',
120 'edit',
121 'editcontentmodel',
122 'editinterface',
123 'editprotected',
124 'editmyoptions',
125 'editmyprivateinfo',
126 'editmyusercss',
127 'editmyuserjs',
128 'editmywatchlist',
129 'editsemiprotected',
130 'editusercssjs', # deprecated
131 'editusercss',
132 'edituserjs',
133 'hideuser',
134 'import',
135 'importupload',
136 'ipblock-exempt',
137 'managechangetags',
138 'markbotedits',
139 'mergehistory',
140 'minoredit',
141 'move',
142 'movefile',
143 'move-categorypages',
144 'move-rootuserpages',
145 'move-subpages',
146 'nominornewtalk',
147 'noratelimit',
148 'override-export-depth',
149 'pagelang',
150 'passwordreset',
151 'patrol',
152 'patrolmarks',
153 'protect',
154 'purge',
155 'read',
156 'reupload',
157 'reupload-own',
158 'reupload-shared',
159 'rollback',
160 'sendemail',
161 'siteadmin',
162 'suppressionlog',
163 'suppressredirect',
164 'suppressrevision',
165 'unblockself',
166 'undelete',
167 'unwatchedpages',
168 'upload',
169 'upload_by_url',
170 'userrights',
171 'userrights-interwiki',
172 'viewmyprivateinfo',
173 'viewmywatchlist',
174 'viewsuppressed',
175 'writeapi',
179 * String Cached results of getAllRights()
181 protected static $mAllRights = false;
183 /** Cache variables */
184 // @{
185 public $mId;
186 /** @var string */
187 public $mName;
188 /** @var string */
189 public $mRealName;
191 /** @var string */
192 public $mEmail;
193 /** @var string TS_MW timestamp from the DB */
194 public $mTouched;
195 /** @var string TS_MW timestamp from cache */
196 protected $mQuickTouched;
197 /** @var string */
198 protected $mToken;
199 /** @var string */
200 public $mEmailAuthenticated;
201 /** @var string */
202 protected $mEmailToken;
203 /** @var string */
204 protected $mEmailTokenExpires;
205 /** @var string */
206 protected $mRegistration;
207 /** @var int */
208 protected $mEditCount;
209 /** @var array */
210 public $mGroups;
211 /** @var array */
212 protected $mOptionOverrides;
213 // @}
216 * Bool Whether the cache variables have been loaded.
218 // @{
219 public $mOptionsLoaded;
222 * Array with already loaded items or true if all items have been loaded.
224 protected $mLoadedItems = array();
225 // @}
228 * String Initialization data source if mLoadedItems!==true. May be one of:
229 * - 'defaults' anonymous user initialised from class defaults
230 * - 'name' initialise from mName
231 * - 'id' initialise from mId
232 * - 'session' log in from session if possible
234 * Use the User::newFrom*() family of functions to set this.
236 public $mFrom;
239 * Lazy-initialized variables, invalidated with clearInstanceCache
241 protected $mNewtalk;
242 /** @var string */
243 protected $mDatePreference;
244 /** @var string */
245 public $mBlockedby;
246 /** @var string */
247 protected $mHash;
248 /** @var array */
249 public $mRights;
250 /** @var string */
251 protected $mBlockreason;
252 /** @var array */
253 protected $mEffectiveGroups;
254 /** @var array */
255 protected $mImplicitGroups;
256 /** @var array */
257 protected $mFormerGroups;
258 /** @var bool */
259 protected $mBlockedGlobally;
260 /** @var bool */
261 protected $mLocked;
262 /** @var bool */
263 public $mHideName;
264 /** @var array */
265 public $mOptions;
268 * @var WebRequest
270 private $mRequest;
272 /** @var Block */
273 public $mBlock;
275 /** @var bool */
276 protected $mAllowUsertalk;
278 /** @var Block */
279 private $mBlockedFromCreateAccount = false;
281 /** @var array */
282 private $mWatchedItems = array();
284 /** @var integer User::READ_* constant bitfield used to load data */
285 protected $queryFlagsUsed = self::READ_NORMAL;
287 public static $idCacheByName = array();
290 * Lightweight constructor for an anonymous user.
291 * Use the User::newFrom* factory functions for other kinds of users.
293 * @see newFromName()
294 * @see newFromId()
295 * @see newFromConfirmationCode()
296 * @see newFromSession()
297 * @see newFromRow()
299 public function __construct() {
300 $this->clearInstanceCache( 'defaults' );
304 * @return string
306 public function __toString() {
307 return $this->getName();
311 * Load the user table data for this object from the source given by mFrom.
313 * @param integer $flags User::READ_* constant bitfield
315 public function load( $flags = self::READ_NORMAL ) {
316 global $wgFullyInitialised;
318 if ( $this->mLoadedItems === true ) {
319 return;
322 // Set it now to avoid infinite recursion in accessors
323 $oldLoadedItems = $this->mLoadedItems;
324 $this->mLoadedItems = true;
325 $this->queryFlagsUsed = $flags;
327 // If this is called too early, things are likely to break.
328 if ( $this->mFrom === 'session' && empty( $wgFullyInitialised ) ) {
329 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
330 ->warning( 'User::loadFromSession called before the end of Setup.php' );
331 $this->loadDefaults();
332 $this->mLoadedItems = $oldLoadedItems;
333 return;
336 switch ( $this->mFrom ) {
337 case 'defaults':
338 $this->loadDefaults();
339 break;
340 case 'name':
341 // Make sure this thread sees its own changes
342 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
343 $flags |= self::READ_LATEST;
344 $this->queryFlagsUsed = $flags;
347 $this->mId = self::idFromName( $this->mName, $flags );
348 if ( !$this->mId ) {
349 // Nonexistent user placeholder object
350 $this->loadDefaults( $this->mName );
351 } else {
352 $this->loadFromId( $flags );
354 break;
355 case 'id':
356 $this->loadFromId( $flags );
357 break;
358 case 'session':
359 if ( !$this->loadFromSession() ) {
360 // Loading from session failed. Load defaults.
361 $this->loadDefaults();
363 Hooks::run( 'UserLoadAfterLoadFromSession', array( $this ) );
364 break;
365 default:
366 throw new UnexpectedValueException(
367 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
372 * Load user table data, given mId has already been set.
373 * @param integer $flags User::READ_* constant bitfield
374 * @return bool False if the ID does not exist, true otherwise
376 public function loadFromId( $flags = self::READ_NORMAL ) {
377 if ( $this->mId == 0 ) {
378 $this->loadDefaults();
379 return false;
382 // Try cache (unless this needs data from the master DB).
383 // NOTE: if this thread called saveSettings(), the cache was cleared.
384 $latest = DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST );
385 if ( $latest || !$this->loadFromCache() ) {
386 wfDebug( "User: cache miss for user {$this->mId}\n" );
387 // Load from DB (make sure this thread sees its own changes)
388 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
389 $flags |= self::READ_LATEST;
391 if ( !$this->loadFromDatabase( $flags ) ) {
392 // Can't load from ID, user is anonymous
393 return false;
395 $this->saveToCache();
398 $this->mLoadedItems = true;
399 $this->queryFlagsUsed = $flags;
401 return true;
405 * @since 1.27
406 * @param string $wikiId
407 * @param integer $userId
409 public static function purge( $wikiId, $userId ) {
410 $cache = ObjectCache::getMainWANInstance();
411 $cache->delete( $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId ) );
415 * @since 1.27
416 * @param WANObjectCache $cache
417 * @return string
419 protected function getCacheKey( WANObjectCache $cache ) {
420 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId );
424 * Load user data from shared cache, given mId has already been set.
426 * @return bool false if the ID does not exist or data is invalid, true otherwise
427 * @since 1.25
429 protected function loadFromCache() {
430 if ( $this->mId == 0 ) {
431 $this->loadDefaults();
432 return false;
435 $cache = ObjectCache::getMainWANInstance();
436 $data = $cache->get( $this->getCacheKey( $cache ) );
437 if ( !is_array( $data ) || $data['mVersion'] < self::VERSION ) {
438 // Object is expired
439 return false;
442 wfDebug( "User: got user {$this->mId} from cache\n" );
444 // Restore from cache
445 foreach ( self::$mCacheVars as $name ) {
446 $this->$name = $data[$name];
449 return true;
453 * Save user data to the shared cache
455 * This method should not be called outside the User class
457 public function saveToCache() {
458 $this->load();
459 $this->loadGroups();
460 $this->loadOptions();
462 if ( $this->isAnon() ) {
463 // Anonymous users are uncached
464 return;
467 $data = array();
468 foreach ( self::$mCacheVars as $name ) {
469 $data[$name] = $this->$name;
471 $data['mVersion'] = self::VERSION;
472 $opts = Database::getCacheSetOptions( wfGetDB( DB_SLAVE ) );
474 $cache = ObjectCache::getMainWANInstance();
475 $key = $this->getCacheKey( $cache );
476 $cache->set( $key, $data, $cache::TTL_HOUR, $opts );
479 /** @name newFrom*() static factory methods */
480 // @{
483 * Static factory method for creation from username.
485 * This is slightly less efficient than newFromId(), so use newFromId() if
486 * you have both an ID and a name handy.
488 * @param string $name Username, validated by Title::newFromText()
489 * @param string|bool $validate Validate username. Takes the same parameters as
490 * User::getCanonicalName(), except that true is accepted as an alias
491 * for 'valid', for BC.
493 * @return User|bool User object, or false if the username is invalid
494 * (e.g. if it contains illegal characters or is an IP address). If the
495 * username is not present in the database, the result will be a user object
496 * with a name, zero user ID and default settings.
498 public static function newFromName( $name, $validate = 'valid' ) {
499 if ( $validate === true ) {
500 $validate = 'valid';
502 $name = self::getCanonicalName( $name, $validate );
503 if ( $name === false ) {
504 return false;
505 } else {
506 // Create unloaded user object
507 $u = new User;
508 $u->mName = $name;
509 $u->mFrom = 'name';
510 $u->setItemLoaded( 'name' );
511 return $u;
516 * Static factory method for creation from a given user ID.
518 * @param int $id Valid user ID
519 * @return User The corresponding User object
521 public static function newFromId( $id ) {
522 $u = new User;
523 $u->mId = $id;
524 $u->mFrom = 'id';
525 $u->setItemLoaded( 'id' );
526 return $u;
530 * Factory method to fetch whichever user has a given email confirmation code.
531 * This code is generated when an account is created or its e-mail address
532 * has changed.
534 * If the code is invalid or has expired, returns NULL.
536 * @param string $code Confirmation code
537 * @param int $flags User::READ_* bitfield
538 * @return User|null
540 public static function newFromConfirmationCode( $code, $flags = 0 ) {
541 $db = ( $flags & self::READ_LATEST ) == self::READ_LATEST
542 ? wfGetDB( DB_MASTER )
543 : wfGetDB( DB_SLAVE );
545 $id = $db->selectField(
546 'user',
547 'user_id',
548 array(
549 'user_email_token' => md5( $code ),
550 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
554 return $id ? User::newFromId( $id ) : null;
558 * Create a new user object using data from session. If the login
559 * credentials are invalid, the result is an anonymous user.
561 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
562 * @return User
564 public static function newFromSession( WebRequest $request = null ) {
565 $user = new User;
566 $user->mFrom = 'session';
567 $user->mRequest = $request;
568 return $user;
572 * Create a new user object from a user row.
573 * The row should have the following fields from the user table in it:
574 * - either user_name or user_id to load further data if needed (or both)
575 * - user_real_name
576 * - all other fields (email, etc.)
577 * It is useless to provide the remaining fields if either user_id,
578 * user_name and user_real_name are not provided because the whole row
579 * will be loaded once more from the database when accessing them.
581 * @param stdClass $row A row from the user table
582 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
583 * @return User
585 public static function newFromRow( $row, $data = null ) {
586 $user = new User;
587 $user->loadFromRow( $row, $data );
588 return $user;
592 * Static factory method for creation of a "system" user from username.
594 * A "system" user is an account that's used to attribute logged actions
595 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
596 * might include the 'Maintenance script' or 'Conversion script' accounts
597 * used by various scripts in the maintenance/ directory or accounts such
598 * as 'MediaWiki message delivery' used by the MassMessage extension.
600 * This can optionally create the user if it doesn't exist, and "steal" the
601 * account if it does exist.
603 * @param string $name Username
604 * @param array $options Options are:
605 * - validate: As for User::getCanonicalName(), default 'valid'
606 * - create: Whether to create the user if it doesn't already exist, default true
607 * - steal: Whether to reset the account's password and email if it
608 * already exists, default false
609 * @return User|null
611 public static function newSystemUser( $name, $options = array() ) {
612 $options += array(
613 'validate' => 'valid',
614 'create' => true,
615 'steal' => false,
618 $name = self::getCanonicalName( $name, $options['validate'] );
619 if ( $name === false ) {
620 return null;
623 $dbw = wfGetDB( DB_MASTER );
624 $row = $dbw->selectRow(
625 'user',
626 array_merge(
627 self::selectFields(),
628 array( 'user_password', 'user_newpassword' )
630 array( 'user_name' => $name ),
631 __METHOD__
633 if ( !$row ) {
634 // No user. Create it?
635 return $options['create'] ? self::createNew( $name ) : null;
637 $user = self::newFromRow( $row );
639 // A user is considered to exist as a non-system user if it has a
640 // password set, or a temporary password set, or an email set.
641 $passwordFactory = new PasswordFactory();
642 $passwordFactory->init( RequestContext::getMain()->getConfig() );
643 try {
644 $password = $passwordFactory->newFromCiphertext( $row->user_password );
645 } catch ( PasswordError $e ) {
646 wfDebug( 'Invalid password hash found in database.' );
647 $password = PasswordFactory::newInvalidPassword();
649 try {
650 $newpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword );
651 } catch ( PasswordError $e ) {
652 wfDebug( 'Invalid password hash found in database.' );
653 $newpassword = PasswordFactory::newInvalidPassword();
655 if ( !$password instanceof InvalidPassword || !$newpassword instanceof InvalidPassword
656 || $user->mEmail
658 // User exists. Steal it?
659 if ( !$options['steal'] ) {
660 return null;
663 $nopass = PasswordFactory::newInvalidPassword()->toString();
665 $dbw->update(
666 'user',
667 array(
668 'user_password' => $nopass,
669 'user_newpassword' => $nopass,
670 'user_newpass_time' => null,
672 array( 'user_id' => $user->getId() ),
673 __METHOD__
675 $user->invalidateEmail();
676 $user->saveSettings();
679 SessionManager::singleton()->preventSessionsForUser( $user->getName() );
681 return $user;
684 // @}
687 * Get the username corresponding to a given user ID
688 * @param int $id User ID
689 * @return string|bool The corresponding username
691 public static function whoIs( $id ) {
692 return UserCache::singleton()->getProp( $id, 'name' );
696 * Get the real name of a user given their user ID
698 * @param int $id User ID
699 * @return string|bool The corresponding user's real name
701 public static function whoIsReal( $id ) {
702 return UserCache::singleton()->getProp( $id, 'real_name' );
706 * Get database id given a user name
707 * @param string $name Username
708 * @param integer $flags User::READ_* constant bitfield
709 * @return int|null The corresponding user's ID, or null if user is nonexistent
711 public static function idFromName( $name, $flags = self::READ_NORMAL ) {
712 $nt = Title::makeTitleSafe( NS_USER, $name );
713 if ( is_null( $nt ) ) {
714 // Illegal name
715 return null;
718 if ( !( $flags & self::READ_LATEST ) && isset( self::$idCacheByName[$name] ) ) {
719 return self::$idCacheByName[$name];
722 $db = ( $flags & self::READ_LATEST )
723 ? wfGetDB( DB_MASTER )
724 : wfGetDB( DB_SLAVE );
726 $s = $db->selectRow(
727 'user',
728 array( 'user_id' ),
729 array( 'user_name' => $nt->getText() ),
730 __METHOD__
733 if ( $s === false ) {
734 $result = null;
735 } else {
736 $result = $s->user_id;
739 self::$idCacheByName[$name] = $result;
741 if ( count( self::$idCacheByName ) > 1000 ) {
742 self::$idCacheByName = array();
745 return $result;
749 * Reset the cache used in idFromName(). For use in tests.
751 public static function resetIdByNameCache() {
752 self::$idCacheByName = array();
756 * Does the string match an anonymous IPv4 address?
758 * This function exists for username validation, in order to reject
759 * usernames which are similar in form to IP addresses. Strings such
760 * as 300.300.300.300 will return true because it looks like an IP
761 * address, despite not being strictly valid.
763 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
764 * address because the usemod software would "cloak" anonymous IP
765 * addresses like this, if we allowed accounts like this to be created
766 * new users could get the old edits of these anonymous users.
768 * @param string $name Name to match
769 * @return bool
771 public static function isIP( $name ) {
772 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
773 || IP::isIPv6( $name );
777 * Is the input a valid username?
779 * Checks if the input is a valid username, we don't want an empty string,
780 * an IP address, anything that contains slashes (would mess up subpages),
781 * is longer than the maximum allowed username size or doesn't begin with
782 * a capital letter.
784 * @param string $name Name to match
785 * @return bool
787 public static function isValidUserName( $name ) {
788 global $wgContLang, $wgMaxNameChars;
790 if ( $name == ''
791 || User::isIP( $name )
792 || strpos( $name, '/' ) !== false
793 || strlen( $name ) > $wgMaxNameChars
794 || $name != $wgContLang->ucfirst( $name )
796 wfDebugLog( 'username', __METHOD__ .
797 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
798 return false;
801 // Ensure that the name can't be misresolved as a different title,
802 // such as with extra namespace keys at the start.
803 $parsed = Title::newFromText( $name );
804 if ( is_null( $parsed )
805 || $parsed->getNamespace()
806 || strcmp( $name, $parsed->getPrefixedText() ) ) {
807 wfDebugLog( 'username', __METHOD__ .
808 ": '$name' invalid due to ambiguous prefixes" );
809 return false;
812 // Check an additional blacklist of troublemaker characters.
813 // Should these be merged into the title char list?
814 $unicodeBlacklist = '/[' .
815 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
816 '\x{00a0}' . # non-breaking space
817 '\x{2000}-\x{200f}' . # various whitespace
818 '\x{2028}-\x{202f}' . # breaks and control chars
819 '\x{3000}' . # ideographic space
820 '\x{e000}-\x{f8ff}' . # private use
821 ']/u';
822 if ( preg_match( $unicodeBlacklist, $name ) ) {
823 wfDebugLog( 'username', __METHOD__ .
824 ": '$name' invalid due to blacklisted characters" );
825 return false;
828 return true;
832 * Usernames which fail to pass this function will be blocked
833 * from user login and new account registrations, but may be used
834 * internally by batch processes.
836 * If an account already exists in this form, login will be blocked
837 * by a failure to pass this function.
839 * @param string $name Name to match
840 * @return bool
842 public static function isUsableName( $name ) {
843 global $wgReservedUsernames;
844 // Must be a valid username, obviously ;)
845 if ( !self::isValidUserName( $name ) ) {
846 return false;
849 static $reservedUsernames = false;
850 if ( !$reservedUsernames ) {
851 $reservedUsernames = $wgReservedUsernames;
852 Hooks::run( 'UserGetReservedNames', array( &$reservedUsernames ) );
855 // Certain names may be reserved for batch processes.
856 foreach ( $reservedUsernames as $reserved ) {
857 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
858 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
860 if ( $reserved == $name ) {
861 return false;
864 return true;
868 * Usernames which fail to pass this function will be blocked
869 * from new account registrations, but may be used internally
870 * either by batch processes or by user accounts which have
871 * already been created.
873 * Additional blacklisting may be added here rather than in
874 * isValidUserName() to avoid disrupting existing accounts.
876 * @param string $name String to match
877 * @return bool
879 public static function isCreatableName( $name ) {
880 global $wgInvalidUsernameCharacters;
882 // Ensure that the username isn't longer than 235 bytes, so that
883 // (at least for the builtin skins) user javascript and css files
884 // will work. (bug 23080)
885 if ( strlen( $name ) > 235 ) {
886 wfDebugLog( 'username', __METHOD__ .
887 ": '$name' invalid due to length" );
888 return false;
891 // Preg yells if you try to give it an empty string
892 if ( $wgInvalidUsernameCharacters !== '' ) {
893 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
894 wfDebugLog( 'username', __METHOD__ .
895 ": '$name' invalid due to wgInvalidUsernameCharacters" );
896 return false;
900 return self::isUsableName( $name );
904 * Is the input a valid password for this user?
906 * @param string $password Desired password
907 * @return bool
909 public function isValidPassword( $password ) {
910 // simple boolean wrapper for getPasswordValidity
911 return $this->getPasswordValidity( $password ) === true;
915 * Given unvalidated password input, return error message on failure.
917 * @param string $password Desired password
918 * @return bool|string|array True on success, string or array of error message on failure
920 public function getPasswordValidity( $password ) {
921 $result = $this->checkPasswordValidity( $password );
922 if ( $result->isGood() ) {
923 return true;
924 } else {
925 $messages = array();
926 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
927 $messages[] = $error['message'];
929 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
930 $messages[] = $warning['message'];
932 if ( count( $messages ) === 1 ) {
933 return $messages[0];
935 return $messages;
940 * Check if this is a valid password for this user
942 * Create a Status object based on the password's validity.
943 * The Status should be set to fatal if the user should not
944 * be allowed to log in, and should have any errors that
945 * would block changing the password.
947 * If the return value of this is not OK, the password
948 * should not be checked. If the return value is not Good,
949 * the password can be checked, but the user should not be
950 * able to set their password to this.
952 * @param string $password Desired password
953 * @param string $purpose one of 'login', 'create', 'reset'
954 * @return Status
955 * @since 1.23
957 public function checkPasswordValidity( $password, $purpose = 'login' ) {
958 global $wgPasswordPolicy;
960 $upp = new UserPasswordPolicy(
961 $wgPasswordPolicy['policies'],
962 $wgPasswordPolicy['checks']
965 $status = Status::newGood();
966 $result = false; // init $result to false for the internal checks
968 if ( !Hooks::run( 'isValidPassword', array( $password, &$result, $this ) ) ) {
969 $status->error( $result );
970 return $status;
973 if ( $result === false ) {
974 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
975 return $status;
976 } elseif ( $result === true ) {
977 return $status;
978 } else {
979 $status->error( $result );
980 return $status; // the isValidPassword hook set a string $result and returned true
985 * Given unvalidated user input, return a canonical username, or false if
986 * the username is invalid.
987 * @param string $name User input
988 * @param string|bool $validate Type of validation to use:
989 * - false No validation
990 * - 'valid' Valid for batch processes
991 * - 'usable' Valid for batch processes and login
992 * - 'creatable' Valid for batch processes, login and account creation
994 * @throws InvalidArgumentException
995 * @return bool|string
997 public static function getCanonicalName( $name, $validate = 'valid' ) {
998 // Force usernames to capital
999 global $wgContLang;
1000 $name = $wgContLang->ucfirst( $name );
1002 # Reject names containing '#'; these will be cleaned up
1003 # with title normalisation, but then it's too late to
1004 # check elsewhere
1005 if ( strpos( $name, '#' ) !== false ) {
1006 return false;
1009 // Clean up name according to title rules,
1010 // but only when validation is requested (bug 12654)
1011 $t = ( $validate !== false ) ?
1012 Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
1013 // Check for invalid titles
1014 if ( is_null( $t ) ) {
1015 return false;
1018 // Reject various classes of invalid names
1019 global $wgAuth;
1020 $name = $wgAuth->getCanonicalName( $t->getText() );
1022 switch ( $validate ) {
1023 case false:
1024 break;
1025 case 'valid':
1026 if ( !User::isValidUserName( $name ) ) {
1027 $name = false;
1029 break;
1030 case 'usable':
1031 if ( !User::isUsableName( $name ) ) {
1032 $name = false;
1034 break;
1035 case 'creatable':
1036 if ( !User::isCreatableName( $name ) ) {
1037 $name = false;
1039 break;
1040 default:
1041 throw new InvalidArgumentException(
1042 'Invalid parameter value for $validate in ' . __METHOD__ );
1044 return $name;
1048 * Count the number of edits of a user
1050 * @param int $uid User ID to check
1051 * @return int The user's edit count
1053 * @deprecated since 1.21 in favour of User::getEditCount
1055 public static function edits( $uid ) {
1056 wfDeprecated( __METHOD__, '1.21' );
1057 $user = self::newFromId( $uid );
1058 return $user->getEditCount();
1062 * Return a random password.
1064 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1065 * @return string New random password
1067 public static function randomPassword() {
1068 global $wgMinimalPasswordLength;
1069 return PasswordFactory::generateRandomPasswordString( $wgMinimalPasswordLength );
1073 * Set cached properties to default.
1075 * @note This no longer clears uncached lazy-initialised properties;
1076 * the constructor does that instead.
1078 * @param string|bool $name
1080 public function loadDefaults( $name = false ) {
1081 $this->mId = 0;
1082 $this->mName = $name;
1083 $this->mRealName = '';
1084 $this->mEmail = '';
1085 $this->mOptionOverrides = null;
1086 $this->mOptionsLoaded = false;
1088 $request = $this->getRequest();
1089 $loggedOut = $request ? $request->getSession()->getLoggedOutTimestamp() : 0;
1090 if ( $loggedOut !== 0 ) {
1091 $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
1092 } else {
1093 $this->mTouched = '1'; # Allow any pages to be cached
1096 $this->mToken = null; // Don't run cryptographic functions till we need a token
1097 $this->mEmailAuthenticated = null;
1098 $this->mEmailToken = '';
1099 $this->mEmailTokenExpires = null;
1100 $this->mRegistration = wfTimestamp( TS_MW );
1101 $this->mGroups = array();
1103 Hooks::run( 'UserLoadDefaults', array( $this, $name ) );
1107 * Return whether an item has been loaded.
1109 * @param string $item Item to check. Current possibilities:
1110 * - id
1111 * - name
1112 * - realname
1113 * @param string $all 'all' to check if the whole object has been loaded
1114 * or any other string to check if only the item is available (e.g.
1115 * for optimisation)
1116 * @return bool
1118 public function isItemLoaded( $item, $all = 'all' ) {
1119 return ( $this->mLoadedItems === true && $all === 'all' ) ||
1120 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
1124 * Set that an item has been loaded
1126 * @param string $item
1128 protected function setItemLoaded( $item ) {
1129 if ( is_array( $this->mLoadedItems ) ) {
1130 $this->mLoadedItems[$item] = true;
1135 * Load user data from the session.
1137 * @return bool True if the user is logged in, false otherwise.
1139 private function loadFromSession() {
1140 // Deprecated hook
1141 $result = null;
1142 Hooks::run( 'UserLoadFromSession', array( $this, &$result ), '1.27' );
1143 if ( $result !== null ) {
1144 return $result;
1147 // MediaWiki\Session\Session already did the necessary authentication of the user
1148 // returned here, so just use it if applicable.
1149 $session = $this->getRequest()->getSession();
1150 $user = $session->getUser();
1151 if ( $user->isLoggedIn() ) {
1152 $this->loadFromUserObject( $user );
1153 // Other code expects these to be set in the session, so set them.
1154 $session->set( 'wsUserID', $this->getId() );
1155 $session->set( 'wsUserName', $this->getName() );
1156 $session->set( 'wsToken', $this->mToken );
1157 return true;
1160 return false;
1164 * Load user and user_group data from the database.
1165 * $this->mId must be set, this is how the user is identified.
1167 * @param integer $flags User::READ_* constant bitfield
1168 * @return bool True if the user exists, false if the user is anonymous
1170 public function loadFromDatabase( $flags = self::READ_LATEST ) {
1171 // Paranoia
1172 $this->mId = intval( $this->mId );
1174 // Anonymous user
1175 if ( !$this->mId ) {
1176 $this->loadDefaults();
1177 return false;
1180 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
1181 $db = wfGetDB( $index );
1183 $s = $db->selectRow(
1184 'user',
1185 self::selectFields(),
1186 array( 'user_id' => $this->mId ),
1187 __METHOD__,
1188 $options
1191 $this->queryFlagsUsed = $flags;
1192 Hooks::run( 'UserLoadFromDatabase', array( $this, &$s ) );
1194 if ( $s !== false ) {
1195 // Initialise user table data
1196 $this->loadFromRow( $s );
1197 $this->mGroups = null; // deferred
1198 $this->getEditCount(); // revalidation for nulls
1199 return true;
1200 } else {
1201 // Invalid user_id
1202 $this->mId = 0;
1203 $this->loadDefaults();
1204 return false;
1209 * Initialize this object from a row from the user table.
1211 * @param stdClass $row Row from the user table to load.
1212 * @param array $data Further user data to load into the object
1214 * user_groups Array with groups out of the user_groups table
1215 * user_properties Array with properties out of the user_properties table
1217 protected function loadFromRow( $row, $data = null ) {
1218 $all = true;
1220 $this->mGroups = null; // deferred
1222 if ( isset( $row->user_name ) ) {
1223 $this->mName = $row->user_name;
1224 $this->mFrom = 'name';
1225 $this->setItemLoaded( 'name' );
1226 } else {
1227 $all = false;
1230 if ( isset( $row->user_real_name ) ) {
1231 $this->mRealName = $row->user_real_name;
1232 $this->setItemLoaded( 'realname' );
1233 } else {
1234 $all = false;
1237 if ( isset( $row->user_id ) ) {
1238 $this->mId = intval( $row->user_id );
1239 $this->mFrom = 'id';
1240 $this->setItemLoaded( 'id' );
1241 } else {
1242 $all = false;
1245 if ( isset( $row->user_id ) && isset( $row->user_name ) ) {
1246 self::$idCacheByName[$row->user_name] = $row->user_id;
1249 if ( isset( $row->user_editcount ) ) {
1250 $this->mEditCount = $row->user_editcount;
1251 } else {
1252 $all = false;
1255 if ( isset( $row->user_email ) ) {
1256 $this->mEmail = $row->user_email;
1257 $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1258 $this->mToken = $row->user_token;
1259 if ( $this->mToken == '' ) {
1260 $this->mToken = null;
1262 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1263 $this->mEmailToken = $row->user_email_token;
1264 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1265 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1266 } else {
1267 $all = false;
1270 if ( $all ) {
1271 $this->mLoadedItems = true;
1274 if ( is_array( $data ) ) {
1275 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1276 $this->mGroups = $data['user_groups'];
1278 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1279 $this->loadOptions( $data['user_properties'] );
1285 * Load the data for this user object from another user object.
1287 * @param User $user
1289 protected function loadFromUserObject( $user ) {
1290 $user->load();
1291 $user->loadGroups();
1292 $user->loadOptions();
1293 foreach ( self::$mCacheVars as $var ) {
1294 $this->$var = $user->$var;
1299 * Load the groups from the database if they aren't already loaded.
1301 private function loadGroups() {
1302 if ( is_null( $this->mGroups ) ) {
1303 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
1304 ? wfGetDB( DB_MASTER )
1305 : wfGetDB( DB_SLAVE );
1306 $res = $db->select( 'user_groups',
1307 array( 'ug_group' ),
1308 array( 'ug_user' => $this->mId ),
1309 __METHOD__ );
1310 $this->mGroups = array();
1311 foreach ( $res as $row ) {
1312 $this->mGroups[] = $row->ug_group;
1318 * Add the user to the group if he/she meets given criteria.
1320 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1321 * possible to remove manually via Special:UserRights. In such case it
1322 * will not be re-added automatically. The user will also not lose the
1323 * group if they no longer meet the criteria.
1325 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1327 * @return array Array of groups the user has been promoted to.
1329 * @see $wgAutopromoteOnce
1331 public function addAutopromoteOnceGroups( $event ) {
1332 global $wgAutopromoteOnceLogInRC, $wgAuth;
1334 if ( wfReadOnly() || !$this->getId() ) {
1335 return array();
1338 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1339 if ( !count( $toPromote ) ) {
1340 return array();
1343 if ( !$this->checkAndSetTouched() ) {
1344 return array(); // raced out (bug T48834)
1347 $oldGroups = $this->getGroups(); // previous groups
1348 foreach ( $toPromote as $group ) {
1349 $this->addGroup( $group );
1351 // update groups in external authentication database
1352 Hooks::run( 'UserGroupsChanged', array( $this, $toPromote, array(), false ) );
1353 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1355 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1357 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1358 $logEntry->setPerformer( $this );
1359 $logEntry->setTarget( $this->getUserPage() );
1360 $logEntry->setParameters( array(
1361 '4::oldgroups' => $oldGroups,
1362 '5::newgroups' => $newGroups,
1363 ) );
1364 $logid = $logEntry->insert();
1365 if ( $wgAutopromoteOnceLogInRC ) {
1366 $logEntry->publish( $logid );
1369 return $toPromote;
1373 * Bump user_touched if it didn't change since this object was loaded
1375 * On success, the mTouched field is updated.
1376 * The user serialization cache is always cleared.
1378 * @return bool Whether user_touched was actually updated
1379 * @since 1.26
1381 protected function checkAndSetTouched() {
1382 $this->load();
1384 if ( !$this->mId ) {
1385 return false; // anon
1388 // Get a new user_touched that is higher than the old one
1389 $oldTouched = $this->mTouched;
1390 $newTouched = $this->newTouchedTimestamp();
1392 $dbw = wfGetDB( DB_MASTER );
1393 $dbw->update( 'user',
1394 array( 'user_touched' => $dbw->timestamp( $newTouched ) ),
1395 array(
1396 'user_id' => $this->mId,
1397 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1399 __METHOD__
1401 $success = ( $dbw->affectedRows() > 0 );
1403 if ( $success ) {
1404 $this->mTouched = $newTouched;
1405 $this->clearSharedCache();
1406 } else {
1407 // Clears on failure too since that is desired if the cache is stale
1408 $this->clearSharedCache( 'refresh' );
1411 return $success;
1415 * Clear various cached data stored in this object. The cache of the user table
1416 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1418 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1419 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1421 public function clearInstanceCache( $reloadFrom = false ) {
1422 $this->mNewtalk = -1;
1423 $this->mDatePreference = null;
1424 $this->mBlockedby = -1; # Unset
1425 $this->mHash = false;
1426 $this->mRights = null;
1427 $this->mEffectiveGroups = null;
1428 $this->mImplicitGroups = null;
1429 $this->mGroups = null;
1430 $this->mOptions = null;
1431 $this->mOptionsLoaded = false;
1432 $this->mEditCount = null;
1434 if ( $reloadFrom ) {
1435 $this->mLoadedItems = array();
1436 $this->mFrom = $reloadFrom;
1441 * Combine the language default options with any site-specific options
1442 * and add the default language variants.
1444 * @return array Array of String options
1446 public static function getDefaultOptions() {
1447 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1449 static $defOpt = null;
1450 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1451 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1452 // mid-request and see that change reflected in the return value of this function.
1453 // Which is insane and would never happen during normal MW operation
1454 return $defOpt;
1457 $defOpt = $wgDefaultUserOptions;
1458 // Default language setting
1459 $defOpt['language'] = $wgContLang->getCode();
1460 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
1461 $defOpt[$langCode == $wgContLang->getCode() ? 'variant' : "variant-$langCode"] = $langCode;
1463 foreach ( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1464 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1466 $defOpt['skin'] = Skin::normalizeKey( $wgDefaultSkin );
1468 Hooks::run( 'UserGetDefaultOptions', array( &$defOpt ) );
1470 return $defOpt;
1474 * Get a given default option value.
1476 * @param string $opt Name of option to retrieve
1477 * @return string Default option value
1479 public static function getDefaultOption( $opt ) {
1480 $defOpts = self::getDefaultOptions();
1481 if ( isset( $defOpts[$opt] ) ) {
1482 return $defOpts[$opt];
1483 } else {
1484 return null;
1489 * Get blocking information
1490 * @param bool $bFromSlave Whether to check the slave database first.
1491 * To improve performance, non-critical checks are done against slaves.
1492 * Check when actually saving should be done against master.
1494 private function getBlockedStatus( $bFromSlave = true ) {
1495 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1497 if ( -1 != $this->mBlockedby ) {
1498 return;
1501 wfDebug( __METHOD__ . ": checking...\n" );
1503 // Initialize data...
1504 // Otherwise something ends up stomping on $this->mBlockedby when
1505 // things get lazy-loaded later, causing false positive block hits
1506 // due to -1 !== 0. Probably session-related... Nothing should be
1507 // overwriting mBlockedby, surely?
1508 $this->load();
1510 # We only need to worry about passing the IP address to the Block generator if the
1511 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1512 # know which IP address they're actually coming from
1513 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->equals( $wgUser ) ) {
1514 $ip = $this->getRequest()->getIP();
1515 } else {
1516 $ip = null;
1519 // User/IP blocking
1520 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1522 // Proxy blocking
1523 if ( !$block instanceof Block && $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1524 // Local list
1525 if ( self::isLocallyBlockedProxy( $ip ) ) {
1526 $block = new Block;
1527 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1528 $block->mReason = wfMessage( 'proxyblockreason' )->text();
1529 $block->setTarget( $ip );
1530 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1531 $block = new Block;
1532 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1533 $block->mReason = wfMessage( 'sorbsreason' )->text();
1534 $block->setTarget( $ip );
1538 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1539 if ( !$block instanceof Block
1540 && $wgApplyIpBlocksToXff
1541 && $ip !== null
1542 && !in_array( $ip, $wgProxyWhitelist )
1544 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1545 $xff = array_map( 'trim', explode( ',', $xff ) );
1546 $xff = array_diff( $xff, array( $ip ) );
1547 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1548 $block = Block::chooseBlock( $xffblocks, $xff );
1549 if ( $block instanceof Block ) {
1550 # Mangle the reason to alert the user that the block
1551 # originated from matching the X-Forwarded-For header.
1552 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->text();
1556 if ( $block instanceof Block ) {
1557 wfDebug( __METHOD__ . ": Found block.\n" );
1558 $this->mBlock = $block;
1559 $this->mBlockedby = $block->getByName();
1560 $this->mBlockreason = $block->mReason;
1561 $this->mHideName = $block->mHideName;
1562 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1563 } else {
1564 $this->mBlockedby = '';
1565 $this->mHideName = 0;
1566 $this->mAllowUsertalk = false;
1569 // Extensions
1570 Hooks::run( 'GetBlockedStatus', array( &$this ) );
1575 * Whether the given IP is in a DNS blacklist.
1577 * @param string $ip IP to check
1578 * @param bool $checkWhitelist Whether to check the whitelist first
1579 * @return bool True if blacklisted.
1581 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1582 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1584 if ( !$wgEnableDnsBlacklist ) {
1585 return false;
1588 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1589 return false;
1592 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1596 * Whether the given IP is in a given DNS blacklist.
1598 * @param string $ip IP to check
1599 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1600 * @return bool True if blacklisted.
1602 public function inDnsBlacklist( $ip, $bases ) {
1604 $found = false;
1605 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1606 if ( IP::isIPv4( $ip ) ) {
1607 // Reverse IP, bug 21255
1608 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1610 foreach ( (array)$bases as $base ) {
1611 // Make hostname
1612 // If we have an access key, use that too (ProjectHoneypot, etc.)
1613 $basename = $base;
1614 if ( is_array( $base ) ) {
1615 if ( count( $base ) >= 2 ) {
1616 // Access key is 1, base URL is 0
1617 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1618 } else {
1619 $host = "$ipReversed.{$base[0]}";
1621 $basename = $base[0];
1622 } else {
1623 $host = "$ipReversed.$base";
1626 // Send query
1627 $ipList = gethostbynamel( $host );
1629 if ( $ipList ) {
1630 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1631 $found = true;
1632 break;
1633 } else {
1634 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1639 return $found;
1643 * Check if an IP address is in the local proxy list
1645 * @param string $ip
1647 * @return bool
1649 public static function isLocallyBlockedProxy( $ip ) {
1650 global $wgProxyList;
1652 if ( !$wgProxyList ) {
1653 return false;
1656 if ( !is_array( $wgProxyList ) ) {
1657 // Load from the specified file
1658 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1661 if ( !is_array( $wgProxyList ) ) {
1662 $ret = false;
1663 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1664 $ret = true;
1665 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1666 // Old-style flipped proxy list
1667 $ret = true;
1668 } else {
1669 $ret = false;
1671 return $ret;
1675 * Is this user subject to rate limiting?
1677 * @return bool True if rate limited
1679 public function isPingLimitable() {
1680 global $wgRateLimitsExcludedIPs;
1681 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1682 // No other good way currently to disable rate limits
1683 // for specific IPs. :P
1684 // But this is a crappy hack and should die.
1685 return false;
1687 return !$this->isAllowed( 'noratelimit' );
1691 * Primitive rate limits: enforce maximum actions per time period
1692 * to put a brake on flooding.
1694 * The method generates both a generic profiling point and a per action one
1695 * (suffix being "-$action".
1697 * @note When using a shared cache like memcached, IP-address
1698 * last-hit counters will be shared across wikis.
1700 * @param string $action Action to enforce; 'edit' if unspecified
1701 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1702 * @return bool True if a rate limiter was tripped
1704 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1705 // Call the 'PingLimiter' hook
1706 $result = false;
1707 if ( !Hooks::run( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1708 return $result;
1711 global $wgRateLimits;
1712 if ( !isset( $wgRateLimits[$action] ) ) {
1713 return false;
1716 // Some groups shouldn't trigger the ping limiter, ever
1717 if ( !$this->isPingLimitable() ) {
1718 return false;
1721 $limits = $wgRateLimits[$action];
1722 $keys = array();
1723 $id = $this->getId();
1724 $userLimit = false;
1726 if ( isset( $limits['anon'] ) && $id == 0 ) {
1727 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1730 if ( isset( $limits['user'] ) && $id != 0 ) {
1731 $userLimit = $limits['user'];
1733 if ( $this->isNewbie() ) {
1734 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1735 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1737 if ( isset( $limits['ip'] ) ) {
1738 $ip = $this->getRequest()->getIP();
1739 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1741 if ( isset( $limits['subnet'] ) ) {
1742 $ip = $this->getRequest()->getIP();
1743 $matches = array();
1744 $subnet = false;
1745 if ( IP::isIPv6( $ip ) ) {
1746 $parts = IP::parseRange( "$ip/64" );
1747 $subnet = $parts[0];
1748 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1749 // IPv4
1750 $subnet = $matches[1];
1752 if ( $subnet !== false ) {
1753 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1757 // Check for group-specific permissions
1758 // If more than one group applies, use the group with the highest limit
1759 foreach ( $this->getGroups() as $group ) {
1760 if ( isset( $limits[$group] ) ) {
1761 if ( $userLimit === false
1762 || $limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1764 $userLimit = $limits[$group];
1768 // Set the user limit key
1769 if ( $userLimit !== false ) {
1770 list( $max, $period ) = $userLimit;
1771 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
1772 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1775 $cache = ObjectCache::getLocalClusterInstance();
1777 $triggered = false;
1778 foreach ( $keys as $key => $limit ) {
1779 list( $max, $period ) = $limit;
1780 $summary = "(limit $max in {$period}s)";
1781 $count = $cache->get( $key );
1782 // Already pinged?
1783 if ( $count ) {
1784 if ( $count >= $max ) {
1785 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1786 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1787 $triggered = true;
1788 } else {
1789 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1791 } else {
1792 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1793 if ( $incrBy > 0 ) {
1794 $cache->add( $key, 0, intval( $period ) ); // first ping
1797 if ( $incrBy > 0 ) {
1798 $cache->incr( $key, $incrBy );
1802 return $triggered;
1806 * Check if user is blocked
1808 * @param bool $bFromSlave Whether to check the slave database instead of
1809 * the master. Hacked from false due to horrible probs on site.
1810 * @return bool True if blocked, false otherwise
1812 public function isBlocked( $bFromSlave = true ) {
1813 return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
1817 * Get the block affecting the user, or null if the user is not blocked
1819 * @param bool $bFromSlave Whether to check the slave database instead of the master
1820 * @return Block|null
1822 public function getBlock( $bFromSlave = true ) {
1823 $this->getBlockedStatus( $bFromSlave );
1824 return $this->mBlock instanceof Block ? $this->mBlock : null;
1828 * Check if user is blocked from editing a particular article
1830 * @param Title $title Title to check
1831 * @param bool $bFromSlave Whether to check the slave database instead of the master
1832 * @return bool
1834 public function isBlockedFrom( $title, $bFromSlave = false ) {
1835 global $wgBlockAllowsUTEdit;
1837 $blocked = $this->isBlocked( $bFromSlave );
1838 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1839 // If a user's name is suppressed, they cannot make edits anywhere
1840 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName()
1841 && $title->getNamespace() == NS_USER_TALK ) {
1842 $blocked = false;
1843 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1846 Hooks::run( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1848 return $blocked;
1852 * If user is blocked, return the name of the user who placed the block
1853 * @return string Name of blocker
1855 public function blockedBy() {
1856 $this->getBlockedStatus();
1857 return $this->mBlockedby;
1861 * If user is blocked, return the specified reason for the block
1862 * @return string Blocking reason
1864 public function blockedFor() {
1865 $this->getBlockedStatus();
1866 return $this->mBlockreason;
1870 * If user is blocked, return the ID for the block
1871 * @return int Block ID
1873 public function getBlockId() {
1874 $this->getBlockedStatus();
1875 return ( $this->mBlock ? $this->mBlock->getId() : false );
1879 * Check if user is blocked on all wikis.
1880 * Do not use for actual edit permission checks!
1881 * This is intended for quick UI checks.
1883 * @param string $ip IP address, uses current client if none given
1884 * @return bool True if blocked, false otherwise
1886 public function isBlockedGlobally( $ip = '' ) {
1887 if ( $this->mBlockedGlobally !== null ) {
1888 return $this->mBlockedGlobally;
1890 // User is already an IP?
1891 if ( IP::isIPAddress( $this->getName() ) ) {
1892 $ip = $this->getName();
1893 } elseif ( !$ip ) {
1894 $ip = $this->getRequest()->getIP();
1896 $blocked = false;
1897 Hooks::run( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1898 $this->mBlockedGlobally = (bool)$blocked;
1899 return $this->mBlockedGlobally;
1903 * Check if user account is locked
1905 * @return bool True if locked, false otherwise
1907 public function isLocked() {
1908 if ( $this->mLocked !== null ) {
1909 return $this->mLocked;
1911 global $wgAuth;
1912 $authUser = $wgAuth->getUserInstance( $this );
1913 $this->mLocked = (bool)$authUser->isLocked();
1914 Hooks::run( 'UserIsLocked', array( $this, &$this->mLocked ) );
1915 return $this->mLocked;
1919 * Check if user account is hidden
1921 * @return bool True if hidden, false otherwise
1923 public function isHidden() {
1924 if ( $this->mHideName !== null ) {
1925 return $this->mHideName;
1927 $this->getBlockedStatus();
1928 if ( !$this->mHideName ) {
1929 global $wgAuth;
1930 $authUser = $wgAuth->getUserInstance( $this );
1931 $this->mHideName = (bool)$authUser->isHidden();
1932 Hooks::run( 'UserIsHidden', array( $this, &$this->mHideName ) );
1934 return $this->mHideName;
1938 * Get the user's ID.
1939 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1941 public function getId() {
1942 if ( $this->mId === null && $this->mName !== null && User::isIP( $this->mName ) ) {
1943 // Special case, we know the user is anonymous
1944 return 0;
1945 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1946 // Don't load if this was initialized from an ID
1947 $this->load();
1949 return $this->mId;
1953 * Set the user and reload all fields according to a given ID
1954 * @param int $v User ID to reload
1956 public function setId( $v ) {
1957 $this->mId = $v;
1958 $this->clearInstanceCache( 'id' );
1962 * Get the user name, or the IP of an anonymous user
1963 * @return string User's name or IP address
1965 public function getName() {
1966 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1967 // Special case optimisation
1968 return $this->mName;
1969 } else {
1970 $this->load();
1971 if ( $this->mName === false ) {
1972 // Clean up IPs
1973 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
1975 return $this->mName;
1980 * Set the user name.
1982 * This does not reload fields from the database according to the given
1983 * name. Rather, it is used to create a temporary "nonexistent user" for
1984 * later addition to the database. It can also be used to set the IP
1985 * address for an anonymous user to something other than the current
1986 * remote IP.
1988 * @note User::newFromName() has roughly the same function, when the named user
1989 * does not exist.
1990 * @param string $str New user name to set
1992 public function setName( $str ) {
1993 $this->load();
1994 $this->mName = $str;
1998 * Get the user's name escaped by underscores.
1999 * @return string Username escaped by underscores.
2001 public function getTitleKey() {
2002 return str_replace( ' ', '_', $this->getName() );
2006 * Check if the user has new messages.
2007 * @return bool True if the user has new messages
2009 public function getNewtalk() {
2010 $this->load();
2012 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2013 if ( $this->mNewtalk === -1 ) {
2014 $this->mNewtalk = false; # reset talk page status
2016 // Check memcached separately for anons, who have no
2017 // entire User object stored in there.
2018 if ( !$this->mId ) {
2019 global $wgDisableAnonTalk;
2020 if ( $wgDisableAnonTalk ) {
2021 // Anon newtalk disabled by configuration.
2022 $this->mNewtalk = false;
2023 } else {
2024 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName() );
2026 } else {
2027 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
2031 return (bool)$this->mNewtalk;
2035 * Return the data needed to construct links for new talk page message
2036 * alerts. If there are new messages, this will return an associative array
2037 * with the following data:
2038 * wiki: The database name of the wiki
2039 * link: Root-relative link to the user's talk page
2040 * rev: The last talk page revision that the user has seen or null. This
2041 * is useful for building diff links.
2042 * If there are no new messages, it returns an empty array.
2043 * @note This function was designed to accomodate multiple talk pages, but
2044 * currently only returns a single link and revision.
2045 * @return array
2047 public function getNewMessageLinks() {
2048 $talks = array();
2049 if ( !Hooks::run( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2050 return $talks;
2051 } elseif ( !$this->getNewtalk() ) {
2052 return array();
2054 $utp = $this->getTalkPage();
2055 $dbr = wfGetDB( DB_SLAVE );
2056 // Get the "last viewed rev" timestamp from the oldest message notification
2057 $timestamp = $dbr->selectField( 'user_newtalk',
2058 'MIN(user_last_timestamp)',
2059 $this->isAnon() ? array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2060 __METHOD__ );
2061 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2062 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2066 * Get the revision ID for the last talk page revision viewed by the talk
2067 * page owner.
2068 * @return int|null Revision ID or null
2070 public function getNewMessageRevisionId() {
2071 $newMessageRevisionId = null;
2072 $newMessageLinks = $this->getNewMessageLinks();
2073 if ( $newMessageLinks ) {
2074 // Note: getNewMessageLinks() never returns more than a single link
2075 // and it is always for the same wiki, but we double-check here in
2076 // case that changes some time in the future.
2077 if ( count( $newMessageLinks ) === 1
2078 && $newMessageLinks[0]['wiki'] === wfWikiID()
2079 && $newMessageLinks[0]['rev']
2081 /** @var Revision $newMessageRevision */
2082 $newMessageRevision = $newMessageLinks[0]['rev'];
2083 $newMessageRevisionId = $newMessageRevision->getId();
2086 return $newMessageRevisionId;
2090 * Internal uncached check for new messages
2092 * @see getNewtalk()
2093 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2094 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2095 * @return bool True if the user has new messages
2097 protected function checkNewtalk( $field, $id ) {
2098 $dbr = wfGetDB( DB_SLAVE );
2100 $ok = $dbr->selectField( 'user_newtalk', $field, array( $field => $id ), __METHOD__ );
2102 return $ok !== false;
2106 * Add or update the new messages flag
2107 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2108 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2109 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2110 * @return bool True if successful, false otherwise
2112 protected function updateNewtalk( $field, $id, $curRev = null ) {
2113 // Get timestamp of the talk page revision prior to the current one
2114 $prevRev = $curRev ? $curRev->getPrevious() : false;
2115 $ts = $prevRev ? $prevRev->getTimestamp() : null;
2116 // Mark the user as having new messages since this revision
2117 $dbw = wfGetDB( DB_MASTER );
2118 $dbw->insert( 'user_newtalk',
2119 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2120 __METHOD__,
2121 'IGNORE' );
2122 if ( $dbw->affectedRows() ) {
2123 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
2124 return true;
2125 } else {
2126 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
2127 return false;
2132 * Clear the new messages flag for the given user
2133 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2134 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2135 * @return bool True if successful, false otherwise
2137 protected function deleteNewtalk( $field, $id ) {
2138 $dbw = wfGetDB( DB_MASTER );
2139 $dbw->delete( 'user_newtalk',
2140 array( $field => $id ),
2141 __METHOD__ );
2142 if ( $dbw->affectedRows() ) {
2143 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
2144 return true;
2145 } else {
2146 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
2147 return false;
2152 * Update the 'You have new messages!' status.
2153 * @param bool $val Whether the user has new messages
2154 * @param Revision $curRev New, as yet unseen revision of the user talk
2155 * page. Ignored if null or !$val.
2157 public function setNewtalk( $val, $curRev = null ) {
2158 if ( wfReadOnly() ) {
2159 return;
2162 $this->load();
2163 $this->mNewtalk = $val;
2165 if ( $this->isAnon() ) {
2166 $field = 'user_ip';
2167 $id = $this->getName();
2168 } else {
2169 $field = 'user_id';
2170 $id = $this->getId();
2173 if ( $val ) {
2174 $changed = $this->updateNewtalk( $field, $id, $curRev );
2175 } else {
2176 $changed = $this->deleteNewtalk( $field, $id );
2179 if ( $changed ) {
2180 $this->invalidateCache();
2185 * Generate a current or new-future timestamp to be stored in the
2186 * user_touched field when we update things.
2187 * @return string Timestamp in TS_MW format
2189 private function newTouchedTimestamp() {
2190 global $wgClockSkewFudge;
2192 $time = wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
2193 if ( $this->mTouched && $time <= $this->mTouched ) {
2194 $time = wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $this->mTouched ) + 1 );
2197 return $time;
2201 * Clear user data from memcached
2203 * Use after applying updates to the database; caller's
2204 * responsibility to update user_touched if appropriate.
2206 * Called implicitly from invalidateCache() and saveSettings().
2208 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2210 public function clearSharedCache( $mode = 'changed' ) {
2211 if ( !$this->getId() ) {
2212 return;
2215 $cache = ObjectCache::getMainWANInstance();
2216 $key = $this->getCacheKey( $cache );
2217 if ( $mode === 'refresh' ) {
2218 $cache->delete( $key, 1 );
2219 } else {
2220 wfGetDB( DB_MASTER )->onTransactionPreCommitOrIdle( function() use ( $cache, $key ) {
2221 $cache->delete( $key );
2222 } );
2227 * Immediately touch the user data cache for this account
2229 * Calls touch() and removes account data from memcached
2231 public function invalidateCache() {
2232 $this->touch();
2233 $this->clearSharedCache();
2237 * Update the "touched" timestamp for the user
2239 * This is useful on various login/logout events when making sure that
2240 * a browser or proxy that has multiple tenants does not suffer cache
2241 * pollution where the new user sees the old users content. The value
2242 * of getTouched() is checked when determining 304 vs 200 responses.
2243 * Unlike invalidateCache(), this preserves the User object cache and
2244 * avoids database writes.
2246 * @since 1.25
2248 public function touch() {
2249 $id = $this->getId();
2250 if ( $id ) {
2251 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2252 ObjectCache::getMainWANInstance()->touchCheckKey( $key );
2253 $this->mQuickTouched = null;
2258 * Validate the cache for this account.
2259 * @param string $timestamp A timestamp in TS_MW format
2260 * @return bool
2262 public function validateCache( $timestamp ) {
2263 return ( $timestamp >= $this->getTouched() );
2267 * Get the user touched timestamp
2269 * Use this value only to validate caches via inequalities
2270 * such as in the case of HTTP If-Modified-Since response logic
2272 * @return string TS_MW Timestamp
2274 public function getTouched() {
2275 $this->load();
2277 if ( $this->mId ) {
2278 if ( $this->mQuickTouched === null ) {
2279 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId );
2280 $cache = ObjectCache::getMainWANInstance();
2282 $this->mQuickTouched = wfTimestamp( TS_MW, $cache->getCheckKeyTime( $key ) );
2285 return max( $this->mTouched, $this->mQuickTouched );
2288 return $this->mTouched;
2292 * Get the user_touched timestamp field (time of last DB updates)
2293 * @return string TS_MW Timestamp
2294 * @since 1.26
2296 public function getDBTouched() {
2297 $this->load();
2299 return $this->mTouched;
2303 * @deprecated Removed in 1.27.
2304 * @return Password
2305 * @since 1.24
2307 public function getPassword() {
2308 throw new BadMethodCallException( __METHOD__ . ' has been removed in 1.27' );
2312 * @deprecated Removed in 1.27.
2313 * @return Password
2314 * @since 1.24
2316 public function getTemporaryPassword() {
2317 throw new BadMethodCallException( __METHOD__ . ' has been removed in 1.27' );
2321 * Set the password and reset the random token.
2322 * Calls through to authentication plugin if necessary;
2323 * will have no effect if the auth plugin refuses to
2324 * pass the change through or if the legal password
2325 * checks fail.
2327 * As a special case, setting the password to null
2328 * wipes it, so the account cannot be logged in until
2329 * a new password is set, for instance via e-mail.
2331 * @deprecated since 1.27. AuthManager is coming.
2332 * @param string $str New password to set
2333 * @throws PasswordError On failure
2334 * @return bool
2336 public function setPassword( $str ) {
2337 global $wgAuth;
2339 if ( $str !== null ) {
2340 if ( !$wgAuth->allowPasswordChange() ) {
2341 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2344 $status = $this->checkPasswordValidity( $str );
2345 if ( !$status->isGood() ) {
2346 throw new PasswordError( $status->getMessage()->text() );
2350 if ( !$wgAuth->setPassword( $this, $str ) ) {
2351 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2354 $this->setToken();
2355 $this->setOption( 'watchlisttoken', false );
2356 $this->setPasswordInternal( $str );
2358 return true;
2362 * Set the password and reset the random token unconditionally.
2364 * @deprecated since 1.27. AuthManager is coming.
2365 * @param string|null $str New password to set or null to set an invalid
2366 * password hash meaning that the user will not be able to log in
2367 * through the web interface.
2369 public function setInternalPassword( $str ) {
2370 global $wgAuth;
2372 if ( $wgAuth->allowSetLocalPassword() ) {
2373 $this->setToken();
2374 $this->setOption( 'watchlisttoken', false );
2375 $this->setPasswordInternal( $str );
2380 * Actually set the password and such
2381 * @since 1.27 cannot set a password for a user not in the database
2382 * @param string|null $str New password to set or null to set an invalid
2383 * password hash meaning that the user will not be able to log in
2384 * through the web interface.
2386 private function setPasswordInternal( $str ) {
2387 $id = self::idFromName( $this->getName(), self::READ_LATEST );
2388 if ( $id == 0 ) {
2389 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2392 $passwordFactory = new PasswordFactory();
2393 $passwordFactory->init( RequestContext::getMain()->getConfig() );
2394 $dbw = wfGetDB( DB_MASTER );
2395 $dbw->update(
2396 'user',
2397 array(
2398 'user_password' => $passwordFactory->newFromPlaintext( $str )->toString(),
2399 'user_newpassword' => PasswordFactory::newInvalidPassword()->toString(),
2400 'user_newpass_time' => $dbw->timestampOrNull( null ),
2402 array(
2403 'user_id' => $id,
2405 __METHOD__
2408 // When the main password is changed, invalidate all bot passwords too
2409 BotPassword::invalidateAllPasswordsForUser( $this->getName() );
2413 * Get the user's current token.
2414 * @param bool $forceCreation Force the generation of a new token if the
2415 * user doesn't have one (default=true for backwards compatibility).
2416 * @return string Token
2418 public function getToken( $forceCreation = true ) {
2419 $this->load();
2420 if ( !$this->mToken && $forceCreation ) {
2421 $this->setToken();
2423 return $this->mToken;
2427 * Set the random token (used for persistent authentication)
2428 * Called from loadDefaults() among other places.
2430 * @param string|bool $token If specified, set the token to this value
2432 public function setToken( $token = false ) {
2433 $this->load();
2434 if ( !$token ) {
2435 $this->mToken = MWCryptRand::generateHex( self::TOKEN_LENGTH );
2436 } else {
2437 $this->mToken = $token;
2442 * Set the password for a password reminder or new account email
2444 * @deprecated since 1.27, AuthManager is coming
2445 * @param string $str New password to set or null to set an invalid
2446 * password hash meaning that the user will not be able to use it
2447 * @param bool $throttle If true, reset the throttle timestamp to the present
2449 public function setNewpassword( $str, $throttle = true ) {
2450 $id = $this->getId();
2451 if ( $id == 0 ) {
2452 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2455 $dbw = wfGetDB( DB_MASTER );
2457 $passwordFactory = new PasswordFactory();
2458 $passwordFactory->init( RequestContext::getMain()->getConfig() );
2459 $update = array(
2460 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2463 if ( $str === null ) {
2464 $update['user_newpass_time'] = null;
2465 } elseif ( $throttle ) {
2466 $update['user_newpass_time'] = $dbw->timestamp();
2469 $dbw->update( 'user', $update, array( 'user_id' => $id ), __METHOD__ );
2473 * Has password reminder email been sent within the last
2474 * $wgPasswordReminderResendTime hours?
2475 * @return bool
2477 public function isPasswordReminderThrottled() {
2478 global $wgPasswordReminderResendTime;
2480 if ( !$wgPasswordReminderResendTime ) {
2481 return false;
2484 $this->load();
2486 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
2487 ? wfGetDB( DB_MASTER )
2488 : wfGetDB( DB_SLAVE );
2489 $newpassTime = $db->selectField(
2490 'user',
2491 'user_newpass_time',
2492 array( 'user_id' => $this->getId() ),
2493 __METHOD__
2496 if ( $newpassTime === null ) {
2497 return false;
2499 $expiry = wfTimestamp( TS_UNIX, $newpassTime ) + $wgPasswordReminderResendTime * 3600;
2500 return time() < $expiry;
2504 * Get the user's e-mail address
2505 * @return string User's email address
2507 public function getEmail() {
2508 $this->load();
2509 Hooks::run( 'UserGetEmail', array( $this, &$this->mEmail ) );
2510 return $this->mEmail;
2514 * Get the timestamp of the user's e-mail authentication
2515 * @return string TS_MW timestamp
2517 public function getEmailAuthenticationTimestamp() {
2518 $this->load();
2519 Hooks::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2520 return $this->mEmailAuthenticated;
2524 * Set the user's e-mail address
2525 * @param string $str New e-mail address
2527 public function setEmail( $str ) {
2528 $this->load();
2529 if ( $str == $this->mEmail ) {
2530 return;
2532 $this->invalidateEmail();
2533 $this->mEmail = $str;
2534 Hooks::run( 'UserSetEmail', array( $this, &$this->mEmail ) );
2538 * Set the user's e-mail address and a confirmation mail if needed.
2540 * @since 1.20
2541 * @param string $str New e-mail address
2542 * @return Status
2544 public function setEmailWithConfirmation( $str ) {
2545 global $wgEnableEmail, $wgEmailAuthentication;
2547 if ( !$wgEnableEmail ) {
2548 return Status::newFatal( 'emaildisabled' );
2551 $oldaddr = $this->getEmail();
2552 if ( $str === $oldaddr ) {
2553 return Status::newGood( true );
2556 $this->setEmail( $str );
2558 if ( $str !== '' && $wgEmailAuthentication ) {
2559 // Send a confirmation request to the new address if needed
2560 $type = $oldaddr != '' ? 'changed' : 'set';
2561 $result = $this->sendConfirmationMail( $type );
2562 if ( $result->isGood() ) {
2563 // Say to the caller that a confirmation mail has been sent
2564 $result->value = 'eauth';
2566 } else {
2567 $result = Status::newGood( true );
2570 return $result;
2574 * Get the user's real name
2575 * @return string User's real name
2577 public function getRealName() {
2578 if ( !$this->isItemLoaded( 'realname' ) ) {
2579 $this->load();
2582 return $this->mRealName;
2586 * Set the user's real name
2587 * @param string $str New real name
2589 public function setRealName( $str ) {
2590 $this->load();
2591 $this->mRealName = $str;
2595 * Get the user's current setting for a given option.
2597 * @param string $oname The option to check
2598 * @param string $defaultOverride A default value returned if the option does not exist
2599 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2600 * @return string User's current value for the option
2601 * @see getBoolOption()
2602 * @see getIntOption()
2604 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2605 global $wgHiddenPrefs;
2606 $this->loadOptions();
2608 # We want 'disabled' preferences to always behave as the default value for
2609 # users, even if they have set the option explicitly in their settings (ie they
2610 # set it, and then it was disabled removing their ability to change it). But
2611 # we don't want to erase the preferences in the database in case the preference
2612 # is re-enabled again. So don't touch $mOptions, just override the returned value
2613 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2614 return self::getDefaultOption( $oname );
2617 if ( array_key_exists( $oname, $this->mOptions ) ) {
2618 return $this->mOptions[$oname];
2619 } else {
2620 return $defaultOverride;
2625 * Get all user's options
2627 * @param int $flags Bitwise combination of:
2628 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2629 * to the default value. (Since 1.25)
2630 * @return array
2632 public function getOptions( $flags = 0 ) {
2633 global $wgHiddenPrefs;
2634 $this->loadOptions();
2635 $options = $this->mOptions;
2637 # We want 'disabled' preferences to always behave as the default value for
2638 # users, even if they have set the option explicitly in their settings (ie they
2639 # set it, and then it was disabled removing their ability to change it). But
2640 # we don't want to erase the preferences in the database in case the preference
2641 # is re-enabled again. So don't touch $mOptions, just override the returned value
2642 foreach ( $wgHiddenPrefs as $pref ) {
2643 $default = self::getDefaultOption( $pref );
2644 if ( $default !== null ) {
2645 $options[$pref] = $default;
2649 if ( $flags & self::GETOPTIONS_EXCLUDE_DEFAULTS ) {
2650 $options = array_diff_assoc( $options, self::getDefaultOptions() );
2653 return $options;
2657 * Get the user's current setting for a given option, as a boolean value.
2659 * @param string $oname The option to check
2660 * @return bool User's current value for the option
2661 * @see getOption()
2663 public function getBoolOption( $oname ) {
2664 return (bool)$this->getOption( $oname );
2668 * Get the user's current setting for a given option, as an integer value.
2670 * @param string $oname The option to check
2671 * @param int $defaultOverride A default value returned if the option does not exist
2672 * @return int User's current value for the option
2673 * @see getOption()
2675 public function getIntOption( $oname, $defaultOverride = 0 ) {
2676 $val = $this->getOption( $oname );
2677 if ( $val == '' ) {
2678 $val = $defaultOverride;
2680 return intval( $val );
2684 * Set the given option for a user.
2686 * You need to call saveSettings() to actually write to the database.
2688 * @param string $oname The option to set
2689 * @param mixed $val New value to set
2691 public function setOption( $oname, $val ) {
2692 $this->loadOptions();
2694 // Explicitly NULL values should refer to defaults
2695 if ( is_null( $val ) ) {
2696 $val = self::getDefaultOption( $oname );
2699 $this->mOptions[$oname] = $val;
2703 * Get a token stored in the preferences (like the watchlist one),
2704 * resetting it if it's empty (and saving changes).
2706 * @param string $oname The option name to retrieve the token from
2707 * @return string|bool User's current value for the option, or false if this option is disabled.
2708 * @see resetTokenFromOption()
2709 * @see getOption()
2710 * @deprecated 1.26 Applications should use the OAuth extension
2712 public function getTokenFromOption( $oname ) {
2713 global $wgHiddenPrefs;
2715 $id = $this->getId();
2716 if ( !$id || in_array( $oname, $wgHiddenPrefs ) ) {
2717 return false;
2720 $token = $this->getOption( $oname );
2721 if ( !$token ) {
2722 // Default to a value based on the user token to avoid space
2723 // wasted on storing tokens for all users. When this option
2724 // is set manually by the user, only then is it stored.
2725 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2728 return $token;
2732 * Reset a token stored in the preferences (like the watchlist one).
2733 * *Does not* save user's preferences (similarly to setOption()).
2735 * @param string $oname The option name to reset the token in
2736 * @return string|bool New token value, or false if this option is disabled.
2737 * @see getTokenFromOption()
2738 * @see setOption()
2740 public function resetTokenFromOption( $oname ) {
2741 global $wgHiddenPrefs;
2742 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2743 return false;
2746 $token = MWCryptRand::generateHex( 40 );
2747 $this->setOption( $oname, $token );
2748 return $token;
2752 * Return a list of the types of user options currently returned by
2753 * User::getOptionKinds().
2755 * Currently, the option kinds are:
2756 * - 'registered' - preferences which are registered in core MediaWiki or
2757 * by extensions using the UserGetDefaultOptions hook.
2758 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2759 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2760 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2761 * be used by user scripts.
2762 * - 'special' - "preferences" that are not accessible via User::getOptions
2763 * or User::setOptions.
2764 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2765 * These are usually legacy options, removed in newer versions.
2767 * The API (and possibly others) use this function to determine the possible
2768 * option types for validation purposes, so make sure to update this when a
2769 * new option kind is added.
2771 * @see User::getOptionKinds
2772 * @return array Option kinds
2774 public static function listOptionKinds() {
2775 return array(
2776 'registered',
2777 'registered-multiselect',
2778 'registered-checkmatrix',
2779 'userjs',
2780 'special',
2781 'unused'
2786 * Return an associative array mapping preferences keys to the kind of a preference they're
2787 * used for. Different kinds are handled differently when setting or reading preferences.
2789 * See User::listOptionKinds for the list of valid option types that can be provided.
2791 * @see User::listOptionKinds
2792 * @param IContextSource $context
2793 * @param array $options Assoc. array with options keys to check as keys.
2794 * Defaults to $this->mOptions.
2795 * @return array The key => kind mapping data
2797 public function getOptionKinds( IContextSource $context, $options = null ) {
2798 $this->loadOptions();
2799 if ( $options === null ) {
2800 $options = $this->mOptions;
2803 $prefs = Preferences::getPreferences( $this, $context );
2804 $mapping = array();
2806 // Pull out the "special" options, so they don't get converted as
2807 // multiselect or checkmatrix.
2808 $specialOptions = array_fill_keys( Preferences::getSaveBlacklist(), true );
2809 foreach ( $specialOptions as $name => $value ) {
2810 unset( $prefs[$name] );
2813 // Multiselect and checkmatrix options are stored in the database with
2814 // one key per option, each having a boolean value. Extract those keys.
2815 $multiselectOptions = array();
2816 foreach ( $prefs as $name => $info ) {
2817 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2818 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2819 $opts = HTMLFormField::flattenOptions( $info['options'] );
2820 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2822 foreach ( $opts as $value ) {
2823 $multiselectOptions["$prefix$value"] = true;
2826 unset( $prefs[$name] );
2829 $checkmatrixOptions = array();
2830 foreach ( $prefs as $name => $info ) {
2831 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2832 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2833 $columns = HTMLFormField::flattenOptions( $info['columns'] );
2834 $rows = HTMLFormField::flattenOptions( $info['rows'] );
2835 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2837 foreach ( $columns as $column ) {
2838 foreach ( $rows as $row ) {
2839 $checkmatrixOptions["$prefix$column-$row"] = true;
2843 unset( $prefs[$name] );
2847 // $value is ignored
2848 foreach ( $options as $key => $value ) {
2849 if ( isset( $prefs[$key] ) ) {
2850 $mapping[$key] = 'registered';
2851 } elseif ( isset( $multiselectOptions[$key] ) ) {
2852 $mapping[$key] = 'registered-multiselect';
2853 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2854 $mapping[$key] = 'registered-checkmatrix';
2855 } elseif ( isset( $specialOptions[$key] ) ) {
2856 $mapping[$key] = 'special';
2857 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2858 $mapping[$key] = 'userjs';
2859 } else {
2860 $mapping[$key] = 'unused';
2864 return $mapping;
2868 * Reset certain (or all) options to the site defaults
2870 * The optional parameter determines which kinds of preferences will be reset.
2871 * Supported values are everything that can be reported by getOptionKinds()
2872 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2874 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2875 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2876 * for backwards-compatibility.
2877 * @param IContextSource|null $context Context source used when $resetKinds
2878 * does not contain 'all', passed to getOptionKinds().
2879 * Defaults to RequestContext::getMain() when null.
2881 public function resetOptions(
2882 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2883 IContextSource $context = null
2885 $this->load();
2886 $defaultOptions = self::getDefaultOptions();
2888 if ( !is_array( $resetKinds ) ) {
2889 $resetKinds = array( $resetKinds );
2892 if ( in_array( 'all', $resetKinds ) ) {
2893 $newOptions = $defaultOptions;
2894 } else {
2895 if ( $context === null ) {
2896 $context = RequestContext::getMain();
2899 $optionKinds = $this->getOptionKinds( $context );
2900 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
2901 $newOptions = array();
2903 // Use default values for the options that should be deleted, and
2904 // copy old values for the ones that shouldn't.
2905 foreach ( $this->mOptions as $key => $value ) {
2906 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2907 if ( array_key_exists( $key, $defaultOptions ) ) {
2908 $newOptions[$key] = $defaultOptions[$key];
2910 } else {
2911 $newOptions[$key] = $value;
2916 Hooks::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions, $resetKinds ) );
2918 $this->mOptions = $newOptions;
2919 $this->mOptionsLoaded = true;
2923 * Get the user's preferred date format.
2924 * @return string User's preferred date format
2926 public function getDatePreference() {
2927 // Important migration for old data rows
2928 if ( is_null( $this->mDatePreference ) ) {
2929 global $wgLang;
2930 $value = $this->getOption( 'date' );
2931 $map = $wgLang->getDatePreferenceMigrationMap();
2932 if ( isset( $map[$value] ) ) {
2933 $value = $map[$value];
2935 $this->mDatePreference = $value;
2937 return $this->mDatePreference;
2941 * Determine based on the wiki configuration and the user's options,
2942 * whether this user must be over HTTPS no matter what.
2944 * @return bool
2946 public function requiresHTTPS() {
2947 global $wgSecureLogin;
2948 if ( !$wgSecureLogin ) {
2949 return false;
2950 } else {
2951 $https = $this->getBoolOption( 'prefershttps' );
2952 Hooks::run( 'UserRequiresHTTPS', array( $this, &$https ) );
2953 if ( $https ) {
2954 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2956 return $https;
2961 * Get the user preferred stub threshold
2963 * @return int
2965 public function getStubThreshold() {
2966 global $wgMaxArticleSize; # Maximum article size, in Kb
2967 $threshold = $this->getIntOption( 'stubthreshold' );
2968 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2969 // If they have set an impossible value, disable the preference
2970 // so we can use the parser cache again.
2971 $threshold = 0;
2973 return $threshold;
2977 * Get the permissions this user has.
2978 * @return array Array of String permission names
2980 public function getRights() {
2981 if ( is_null( $this->mRights ) ) {
2982 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2984 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
2985 if ( $allowedRights !== null ) {
2986 $this->mRights = array_intersect( $this->mRights, $allowedRights );
2989 Hooks::run( 'UserGetRights', array( $this, &$this->mRights ) );
2990 // Force reindexation of rights when a hook has unset one of them
2991 $this->mRights = array_values( array_unique( $this->mRights ) );
2993 return $this->mRights;
2997 * Get the list of explicit group memberships this user has.
2998 * The implicit * and user groups are not included.
2999 * @return array Array of String internal group names
3001 public function getGroups() {
3002 $this->load();
3003 $this->loadGroups();
3004 return $this->mGroups;
3008 * Get the list of implicit group memberships this user has.
3009 * This includes all explicit groups, plus 'user' if logged in,
3010 * '*' for all accounts, and autopromoted groups
3011 * @param bool $recache Whether to avoid the cache
3012 * @return array Array of String internal group names
3014 public function getEffectiveGroups( $recache = false ) {
3015 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
3016 $this->mEffectiveGroups = array_unique( array_merge(
3017 $this->getGroups(), // explicit groups
3018 $this->getAutomaticGroups( $recache ) // implicit groups
3019 ) );
3020 // Hook for additional groups
3021 Hooks::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
3022 // Force reindexation of groups when a hook has unset one of them
3023 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
3025 return $this->mEffectiveGroups;
3029 * Get the list of implicit group memberships this user has.
3030 * This includes 'user' if logged in, '*' for all accounts,
3031 * and autopromoted groups
3032 * @param bool $recache Whether to avoid the cache
3033 * @return array Array of String internal group names
3035 public function getAutomaticGroups( $recache = false ) {
3036 if ( $recache || is_null( $this->mImplicitGroups ) ) {
3037 $this->mImplicitGroups = array( '*' );
3038 if ( $this->getId() ) {
3039 $this->mImplicitGroups[] = 'user';
3041 $this->mImplicitGroups = array_unique( array_merge(
3042 $this->mImplicitGroups,
3043 Autopromote::getAutopromoteGroups( $this )
3044 ) );
3046 if ( $recache ) {
3047 // Assure data consistency with rights/groups,
3048 // as getEffectiveGroups() depends on this function
3049 $this->mEffectiveGroups = null;
3052 return $this->mImplicitGroups;
3056 * Returns the groups the user has belonged to.
3058 * The user may still belong to the returned groups. Compare with getGroups().
3060 * The function will not return groups the user had belonged to before MW 1.17
3062 * @return array Names of the groups the user has belonged to.
3064 public function getFormerGroups() {
3065 $this->load();
3067 if ( is_null( $this->mFormerGroups ) ) {
3068 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
3069 ? wfGetDB( DB_MASTER )
3070 : wfGetDB( DB_SLAVE );
3071 $res = $db->select( 'user_former_groups',
3072 array( 'ufg_group' ),
3073 array( 'ufg_user' => $this->mId ),
3074 __METHOD__ );
3075 $this->mFormerGroups = array();
3076 foreach ( $res as $row ) {
3077 $this->mFormerGroups[] = $row->ufg_group;
3081 return $this->mFormerGroups;
3085 * Get the user's edit count.
3086 * @return int|null Null for anonymous users
3088 public function getEditCount() {
3089 if ( !$this->getId() ) {
3090 return null;
3093 if ( $this->mEditCount === null ) {
3094 /* Populate the count, if it has not been populated yet */
3095 $dbr = wfGetDB( DB_SLAVE );
3096 // check if the user_editcount field has been initialized
3097 $count = $dbr->selectField(
3098 'user', 'user_editcount',
3099 array( 'user_id' => $this->mId ),
3100 __METHOD__
3103 if ( $count === null ) {
3104 // it has not been initialized. do so.
3105 $count = $this->initEditCount();
3107 $this->mEditCount = $count;
3109 return (int)$this->mEditCount;
3113 * Add the user to the given group.
3114 * This takes immediate effect.
3115 * @param string $group Name of the group to add
3116 * @return bool
3118 public function addGroup( $group ) {
3119 $this->load();
3121 if ( !Hooks::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3122 return false;
3125 $dbw = wfGetDB( DB_MASTER );
3126 if ( $this->getId() ) {
3127 $dbw->insert( 'user_groups',
3128 array(
3129 'ug_user' => $this->getID(),
3130 'ug_group' => $group,
3132 __METHOD__,
3133 array( 'IGNORE' ) );
3136 $this->loadGroups();
3137 $this->mGroups[] = $group;
3138 // In case loadGroups was not called before, we now have the right twice.
3139 // Get rid of the duplicate.
3140 $this->mGroups = array_unique( $this->mGroups );
3142 // Refresh the groups caches, and clear the rights cache so it will be
3143 // refreshed on the next call to $this->getRights().
3144 $this->getEffectiveGroups( true );
3145 $this->mRights = null;
3147 $this->invalidateCache();
3149 return true;
3153 * Remove the user from the given group.
3154 * This takes immediate effect.
3155 * @param string $group Name of the group to remove
3156 * @return bool
3158 public function removeGroup( $group ) {
3159 $this->load();
3160 if ( !Hooks::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3161 return false;
3164 $dbw = wfGetDB( DB_MASTER );
3165 $dbw->delete( 'user_groups',
3166 array(
3167 'ug_user' => $this->getID(),
3168 'ug_group' => $group,
3169 ), __METHOD__
3171 // Remember that the user was in this group
3172 $dbw->insert( 'user_former_groups',
3173 array(
3174 'ufg_user' => $this->getID(),
3175 'ufg_group' => $group,
3177 __METHOD__,
3178 array( 'IGNORE' )
3181 $this->loadGroups();
3182 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
3184 // Refresh the groups caches, and clear the rights cache so it will be
3185 // refreshed on the next call to $this->getRights().
3186 $this->getEffectiveGroups( true );
3187 $this->mRights = null;
3189 $this->invalidateCache();
3191 return true;
3195 * Get whether the user is logged in
3196 * @return bool
3198 public function isLoggedIn() {
3199 return $this->getID() != 0;
3203 * Get whether the user is anonymous
3204 * @return bool
3206 public function isAnon() {
3207 return !$this->isLoggedIn();
3211 * Check if user is allowed to access a feature / make an action
3213 * @param string ... Permissions to test
3214 * @return bool True if user is allowed to perform *any* of the given actions
3216 public function isAllowedAny() {
3217 $permissions = func_get_args();
3218 foreach ( $permissions as $permission ) {
3219 if ( $this->isAllowed( $permission ) ) {
3220 return true;
3223 return false;
3228 * @param string ... Permissions to test
3229 * @return bool True if the user is allowed to perform *all* of the given actions
3231 public function isAllowedAll() {
3232 $permissions = func_get_args();
3233 foreach ( $permissions as $permission ) {
3234 if ( !$this->isAllowed( $permission ) ) {
3235 return false;
3238 return true;
3242 * Internal mechanics of testing a permission
3243 * @param string $action
3244 * @return bool
3246 public function isAllowed( $action = '' ) {
3247 if ( $action === '' ) {
3248 return true; // In the spirit of DWIM
3250 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3251 // by misconfiguration: 0 == 'foo'
3252 return in_array( $action, $this->getRights(), true );
3256 * Check whether to enable recent changes patrol features for this user
3257 * @return bool True or false
3259 public function useRCPatrol() {
3260 global $wgUseRCPatrol;
3261 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3265 * Check whether to enable new pages patrol features for this user
3266 * @return bool True or false
3268 public function useNPPatrol() {
3269 global $wgUseRCPatrol, $wgUseNPPatrol;
3270 return (
3271 ( $wgUseRCPatrol || $wgUseNPPatrol )
3272 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3277 * Check whether to enable new files patrol features for this user
3278 * @return bool True or false
3280 public function useFilePatrol() {
3281 global $wgUseRCPatrol, $wgUseFilePatrol;
3282 return (
3283 ( $wgUseRCPatrol || $wgUseFilePatrol )
3284 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3289 * Get the WebRequest object to use with this object
3291 * @return WebRequest
3293 public function getRequest() {
3294 if ( $this->mRequest ) {
3295 return $this->mRequest;
3296 } else {
3297 global $wgRequest;
3298 return $wgRequest;
3303 * Get a WatchedItem for this user and $title.
3305 * @since 1.22 $checkRights parameter added
3306 * @param Title $title
3307 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3308 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3309 * @return WatchedItem
3311 public function getWatchedItem( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3312 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3314 if ( isset( $this->mWatchedItems[$key] ) ) {
3315 return $this->mWatchedItems[$key];
3318 if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
3319 $this->mWatchedItems = array();
3322 $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title, $checkRights );
3323 return $this->mWatchedItems[$key];
3327 * Check the watched status of an article.
3328 * @since 1.22 $checkRights parameter added
3329 * @param Title $title Title of the article to look at
3330 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3331 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3332 * @return bool
3334 public function isWatched( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3335 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3339 * Watch an article.
3340 * @since 1.22 $checkRights parameter added
3341 * @param Title $title Title of the article to look at
3342 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3343 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3345 public function addWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3346 $this->getWatchedItem( $title, $checkRights )->addWatch();
3347 $this->invalidateCache();
3351 * Stop watching an article.
3352 * @since 1.22 $checkRights parameter added
3353 * @param Title $title Title of the article to look at
3354 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3355 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3357 public function removeWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3358 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3359 $this->invalidateCache();
3363 * Clear the user's notification timestamp for the given title.
3364 * If e-notif e-mails are on, they will receive notification mails on
3365 * the next change of the page if it's watched etc.
3366 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3367 * @param Title $title Title of the article to look at
3368 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3370 public function clearNotification( &$title, $oldid = 0 ) {
3371 global $wgUseEnotif, $wgShowUpdatedMarker;
3373 // Do nothing if the database is locked to writes
3374 if ( wfReadOnly() ) {
3375 return;
3378 // Do nothing if not allowed to edit the watchlist
3379 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3380 return;
3383 // If we're working on user's talk page, we should update the talk page message indicator
3384 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3385 if ( !Hooks::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3386 return;
3389 $that = $this;
3390 // Try to update the DB post-send and only if needed...
3391 DeferredUpdates::addCallableUpdate( function() use ( $that, $title, $oldid ) {
3392 if ( !$that->getNewtalk() ) {
3393 return; // no notifications to clear
3396 // Delete the last notifications (they stack up)
3397 $that->setNewtalk( false );
3399 // If there is a new, unseen, revision, use its timestamp
3400 $nextid = $oldid
3401 ? $title->getNextRevisionID( $oldid, Title::GAID_FOR_UPDATE )
3402 : null;
3403 if ( $nextid ) {
3404 $that->setNewtalk( true, Revision::newFromId( $nextid ) );
3406 } );
3409 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3410 return;
3413 if ( $this->isAnon() ) {
3414 // Nothing else to do...
3415 return;
3418 // Only update the timestamp if the page is being watched.
3419 // The query to find out if it is watched is cached both in memcached and per-invocation,
3420 // and when it does have to be executed, it can be on a slave
3421 // If this is the user's newtalk page, we always update the timestamp
3422 $force = '';
3423 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3424 $force = 'force';
3427 $this->getWatchedItem( $title )->resetNotificationTimestamp(
3428 $force, $oldid, WatchedItem::DEFERRED
3433 * Resets all of the given user's page-change notification timestamps.
3434 * If e-notif e-mails are on, they will receive notification mails on
3435 * the next change of any watched page.
3436 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3438 public function clearAllNotifications() {
3439 if ( wfReadOnly() ) {
3440 return;
3443 // Do nothing if not allowed to edit the watchlist
3444 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3445 return;
3448 global $wgUseEnotif, $wgShowUpdatedMarker;
3449 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3450 $this->setNewtalk( false );
3451 return;
3453 $id = $this->getId();
3454 if ( $id != 0 ) {
3455 $dbw = wfGetDB( DB_MASTER );
3456 $dbw->update( 'watchlist',
3457 array( /* SET */ 'wl_notificationtimestamp' => null ),
3458 array( /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ),
3459 __METHOD__
3461 // We also need to clear here the "you have new message" notification for the own user_talk page;
3462 // it's cleared one page view later in WikiPage::doViewUpdates().
3467 * Set a cookie on the user's client. Wrapper for
3468 * WebResponse::setCookie
3469 * @deprecated since 1.27
3470 * @param string $name Name of the cookie to set
3471 * @param string $value Value to set
3472 * @param int $exp Expiration time, as a UNIX time value;
3473 * if 0 or not specified, use the default $wgCookieExpiration
3474 * @param bool $secure
3475 * true: Force setting the secure attribute when setting the cookie
3476 * false: Force NOT setting the secure attribute when setting the cookie
3477 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3478 * @param array $params Array of options sent passed to WebResponse::setcookie()
3479 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3480 * is passed.
3482 protected function setCookie(
3483 $name, $value, $exp = 0, $secure = null, $params = array(), $request = null
3485 wfDeprecated( __METHOD__, '1.27' );
3486 if ( $request === null ) {
3487 $request = $this->getRequest();
3489 $params['secure'] = $secure;
3490 $request->response()->setCookie( $name, $value, $exp, $params );
3494 * Clear a cookie on the user's client
3495 * @deprecated since 1.27
3496 * @param string $name Name of the cookie to clear
3497 * @param bool $secure
3498 * true: Force setting the secure attribute when setting the cookie
3499 * false: Force NOT setting the secure attribute when setting the cookie
3500 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3501 * @param array $params Array of options sent passed to WebResponse::setcookie()
3503 protected function clearCookie( $name, $secure = null, $params = array() ) {
3504 wfDeprecated( __METHOD__, '1.27' );
3505 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3509 * Set an extended login cookie on the user's client. The expiry of the cookie
3510 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3511 * variable.
3513 * @see User::setCookie
3515 * @deprecated since 1.27
3516 * @param string $name Name of the cookie to set
3517 * @param string $value Value to set
3518 * @param bool $secure
3519 * true: Force setting the secure attribute when setting the cookie
3520 * false: Force NOT setting the secure attribute when setting the cookie
3521 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3523 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3524 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3526 wfDeprecated( __METHOD__, '1.27' );
3528 $exp = time();
3529 $exp += $wgExtendedLoginCookieExpiration !== null
3530 ? $wgExtendedLoginCookieExpiration
3531 : $wgCookieExpiration;
3533 $this->setCookie( $name, $value, $exp, $secure );
3537 * Persist this user's session (e.g. set cookies)
3539 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3540 * is passed.
3541 * @param bool $secure Whether to force secure/insecure cookies or use default
3542 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3544 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3545 $this->load();
3546 if ( 0 == $this->mId ) {
3547 return;
3550 $session = $this->getRequest()->getSession();
3551 if ( $request && $session->getRequest() !== $request ) {
3552 $session = $session->sessionWithRequest( $request );
3554 $delay = $session->delaySave();
3556 if ( !$session->getUser()->equals( $this ) ) {
3557 if ( !$session->canSetUser() ) {
3558 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
3559 ->warning( __METHOD__ .
3560 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3562 return;
3564 $session->setUser( $this );
3567 $session->setRememberUser( $rememberMe );
3568 if ( $secure !== null ) {
3569 $session->setForceHTTPS( $secure );
3572 $session->persist();
3574 ScopedCallback::consume( $delay );
3578 * Log this user out.
3580 public function logout() {
3581 if ( Hooks::run( 'UserLogout', array( &$this ) ) ) {
3582 $this->doLogout();
3587 * Clear the user's session, and reset the instance cache.
3588 * @see logout()
3590 public function doLogout() {
3591 $session = $this->getRequest()->getSession();
3592 if ( !$session->canSetUser() ) {
3593 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
3594 ->warning( __METHOD__ . ": Cannot log out of an immutable session" );
3595 } elseif ( !$session->getUser()->equals( $this ) ) {
3596 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
3597 ->warning( __METHOD__ .
3598 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3600 // But we still may as well make this user object anon
3601 $this->clearInstanceCache( 'defaults' );
3602 } else {
3603 $this->clearInstanceCache( 'defaults' );
3604 $delay = $session->delaySave();
3605 $session->setLoggedOutTimestamp( time() );
3606 $session->setUser( new User );
3607 $session->set( 'wsUserID', 0 ); // Other code expects this
3608 ScopedCallback::consume( $delay );
3613 * Save this user's settings into the database.
3614 * @todo Only rarely do all these fields need to be set!
3616 public function saveSettings() {
3617 if ( wfReadOnly() ) {
3618 // @TODO: caller should deal with this instead!
3619 // This should really just be an exception.
3620 MWExceptionHandler::logException( new DBExpectedError(
3621 null,
3622 "Could not update user with ID '{$this->mId}'; DB is read-only."
3623 ) );
3624 return;
3627 $this->load();
3628 if ( 0 == $this->mId ) {
3629 return; // anon
3632 // Get a new user_touched that is higher than the old one.
3633 // This will be used for a CAS check as a last-resort safety
3634 // check against race conditions and slave lag.
3635 $oldTouched = $this->mTouched;
3636 $newTouched = $this->newTouchedTimestamp();
3638 $dbw = wfGetDB( DB_MASTER );
3639 $dbw->update( 'user',
3640 array( /* SET */
3641 'user_name' => $this->mName,
3642 'user_real_name' => $this->mRealName,
3643 'user_email' => $this->mEmail,
3644 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3645 'user_touched' => $dbw->timestamp( $newTouched ),
3646 'user_token' => strval( $this->mToken ),
3647 'user_email_token' => $this->mEmailToken,
3648 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3649 ), array( /* WHERE */
3650 'user_id' => $this->mId,
3651 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3652 ), __METHOD__
3655 if ( !$dbw->affectedRows() ) {
3656 // Maybe the problem was a missed cache update; clear it to be safe
3657 $this->clearSharedCache( 'refresh' );
3658 // User was changed in the meantime or loaded with stale data
3659 $from = ( $this->queryFlagsUsed & self::READ_LATEST ) ? 'master' : 'slave';
3660 throw new MWException(
3661 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3662 " the version of the user to be saved is older than the current version."
3666 $this->mTouched = $newTouched;
3667 $this->saveOptions();
3669 Hooks::run( 'UserSaveSettings', array( $this ) );
3670 $this->clearSharedCache();
3671 $this->getUserPage()->invalidateCache();
3675 * If only this user's username is known, and it exists, return the user ID.
3677 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3678 * @return int
3680 public function idForName( $flags = 0 ) {
3681 $s = trim( $this->getName() );
3682 if ( $s === '' ) {
3683 return 0;
3686 $db = ( ( $flags & self::READ_LATEST ) == self::READ_LATEST )
3687 ? wfGetDB( DB_MASTER )
3688 : wfGetDB( DB_SLAVE );
3690 $options = ( ( $flags & self::READ_LOCKING ) == self::READ_LOCKING )
3691 ? array( 'LOCK IN SHARE MODE' )
3692 : array();
3694 $id = $db->selectField( 'user',
3695 'user_id', array( 'user_name' => $s ), __METHOD__, $options );
3697 return (int)$id;
3701 * Add a user to the database, return the user object
3703 * @param string $name Username to add
3704 * @param array $params Array of Strings Non-default parameters to save to
3705 * the database as user_* fields:
3706 * - email: The user's email address.
3707 * - email_authenticated: The email authentication timestamp.
3708 * - real_name: The user's real name.
3709 * - options: An associative array of non-default options.
3710 * - token: Random authentication token. Do not set.
3711 * - registration: Registration timestamp. Do not set.
3713 * @return User|null User object, or null if the username already exists.
3715 public static function createNew( $name, $params = array() ) {
3716 foreach ( array( 'password', 'newpassword', 'newpass_time', 'password_expires' ) as $field ) {
3717 if ( isset( $params[$field] ) ) {
3718 wfDeprecated( __METHOD__ . " with param '$field'", '1.27' );
3719 unset( $params[$field] );
3723 $user = new User;
3724 $user->load();
3725 $user->setToken(); // init token
3726 if ( isset( $params['options'] ) ) {
3727 $user->mOptions = $params['options'] + (array)$user->mOptions;
3728 unset( $params['options'] );
3730 $dbw = wfGetDB( DB_MASTER );
3731 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3733 $noPass = PasswordFactory::newInvalidPassword()->toString();
3735 $fields = array(
3736 'user_id' => $seqVal,
3737 'user_name' => $name,
3738 'user_password' => $noPass,
3739 'user_newpassword' => $noPass,
3740 'user_email' => $user->mEmail,
3741 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3742 'user_real_name' => $user->mRealName,
3743 'user_token' => strval( $user->mToken ),
3744 'user_registration' => $dbw->timestamp( $user->mRegistration ),
3745 'user_editcount' => 0,
3746 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3748 foreach ( $params as $name => $value ) {
3749 $fields["user_$name"] = $value;
3751 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
3752 if ( $dbw->affectedRows() ) {
3753 $newUser = User::newFromId( $dbw->insertId() );
3754 } else {
3755 $newUser = null;
3757 return $newUser;
3761 * Add this existing user object to the database. If the user already
3762 * exists, a fatal status object is returned, and the user object is
3763 * initialised with the data from the database.
3765 * Previously, this function generated a DB error due to a key conflict
3766 * if the user already existed. Many extension callers use this function
3767 * in code along the lines of:
3769 * $user = User::newFromName( $name );
3770 * if ( !$user->isLoggedIn() ) {
3771 * $user->addToDatabase();
3773 * // do something with $user...
3775 * However, this was vulnerable to a race condition (bug 16020). By
3776 * initialising the user object if the user exists, we aim to support this
3777 * calling sequence as far as possible.
3779 * Note that if the user exists, this function will acquire a write lock,
3780 * so it is still advisable to make the call conditional on isLoggedIn(),
3781 * and to commit the transaction after calling.
3783 * @throws MWException
3784 * @return Status
3786 public function addToDatabase() {
3787 $this->load();
3788 if ( !$this->mToken ) {
3789 $this->setToken(); // init token
3792 $this->mTouched = $this->newTouchedTimestamp();
3794 $noPass = PasswordFactory::newInvalidPassword()->toString();
3796 $dbw = wfGetDB( DB_MASTER );
3797 $inWrite = $dbw->writesOrCallbacksPending();
3798 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3799 $dbw->insert( 'user',
3800 array(
3801 'user_id' => $seqVal,
3802 'user_name' => $this->mName,
3803 'user_password' => $noPass,
3804 'user_newpassword' => $noPass,
3805 'user_email' => $this->mEmail,
3806 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3807 'user_real_name' => $this->mRealName,
3808 'user_token' => strval( $this->mToken ),
3809 'user_registration' => $dbw->timestamp( $this->mRegistration ),
3810 'user_editcount' => 0,
3811 'user_touched' => $dbw->timestamp( $this->mTouched ),
3812 ), __METHOD__,
3813 array( 'IGNORE' )
3815 if ( !$dbw->affectedRows() ) {
3816 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3817 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3818 if ( $inWrite ) {
3819 // Can't commit due to pending writes that may need atomicity.
3820 // This may cause some lock contention unlike the case below.
3821 $options = array( 'LOCK IN SHARE MODE' );
3822 $flags = self::READ_LOCKING;
3823 } else {
3824 // Often, this case happens early in views before any writes when
3825 // using CentralAuth. It's should be OK to commit and break the snapshot.
3826 $dbw->commit( __METHOD__, 'flush' );
3827 $options = array();
3828 $flags = self::READ_LATEST;
3830 $this->mId = $dbw->selectField( 'user', 'user_id',
3831 array( 'user_name' => $this->mName ), __METHOD__, $options );
3832 $loaded = false;
3833 if ( $this->mId ) {
3834 if ( $this->loadFromDatabase( $flags ) ) {
3835 $loaded = true;
3838 if ( !$loaded ) {
3839 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
3840 "to insert user '{$this->mName}' row, but it was not present in select!" );
3842 return Status::newFatal( 'userexists' );
3844 $this->mId = $dbw->insertId();
3845 self::$idCacheByName[$this->mName] = $this->mId;
3847 // Clear instance cache other than user table data, which is already accurate
3848 $this->clearInstanceCache();
3850 $this->saveOptions();
3851 return Status::newGood();
3855 * If this user is logged-in and blocked,
3856 * block any IP address they've successfully logged in from.
3857 * @return bool A block was spread
3859 public function spreadAnyEditBlock() {
3860 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3861 return $this->spreadBlock();
3863 return false;
3867 * If this (non-anonymous) user is blocked,
3868 * block the IP address they've successfully logged in from.
3869 * @return bool A block was spread
3871 protected function spreadBlock() {
3872 wfDebug( __METHOD__ . "()\n" );
3873 $this->load();
3874 if ( $this->mId == 0 ) {
3875 return false;
3878 $userblock = Block::newFromTarget( $this->getName() );
3879 if ( !$userblock ) {
3880 return false;
3883 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3887 * Get whether the user is explicitly blocked from account creation.
3888 * @return bool|Block
3890 public function isBlockedFromCreateAccount() {
3891 $this->getBlockedStatus();
3892 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
3893 return $this->mBlock;
3896 # bug 13611: if the IP address the user is trying to create an account from is
3897 # blocked with createaccount disabled, prevent new account creation there even
3898 # when the user is logged in
3899 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3900 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
3902 return $this->mBlockedFromCreateAccount instanceof Block
3903 && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
3904 ? $this->mBlockedFromCreateAccount
3905 : false;
3909 * Get whether the user is blocked from using Special:Emailuser.
3910 * @return bool
3912 public function isBlockedFromEmailuser() {
3913 $this->getBlockedStatus();
3914 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
3918 * Get whether the user is allowed to create an account.
3919 * @return bool
3921 public function isAllowedToCreateAccount() {
3922 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3926 * Get this user's personal page title.
3928 * @return Title User's personal page title
3930 public function getUserPage() {
3931 return Title::makeTitle( NS_USER, $this->getName() );
3935 * Get this user's talk page title.
3937 * @return Title User's talk page title
3939 public function getTalkPage() {
3940 $title = $this->getUserPage();
3941 return $title->getTalkPage();
3945 * Determine whether the user is a newbie. Newbies are either
3946 * anonymous IPs, or the most recently created accounts.
3947 * @return bool
3949 public function isNewbie() {
3950 return !$this->isAllowed( 'autoconfirmed' );
3954 * Check to see if the given clear-text password is one of the accepted passwords
3955 * @deprecated since 1.27. AuthManager is coming.
3956 * @param string $password User password
3957 * @return bool True if the given password is correct, otherwise False
3959 public function checkPassword( $password ) {
3960 global $wgAuth, $wgLegacyEncoding;
3962 $this->load();
3964 // Some passwords will give a fatal Status, which means there is
3965 // some sort of technical or security reason for this password to
3966 // be completely invalid and should never be checked (e.g., T64685)
3967 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
3968 return false;
3971 // Certain authentication plugins do NOT want to save
3972 // domain passwords in a mysql database, so we should
3973 // check this (in case $wgAuth->strict() is false).
3974 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3975 return true;
3976 } elseif ( $wgAuth->strict() ) {
3977 // Auth plugin doesn't allow local authentication
3978 return false;
3979 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3980 // Auth plugin doesn't allow local authentication for this user name
3981 return false;
3984 $passwordFactory = new PasswordFactory();
3985 $passwordFactory->init( RequestContext::getMain()->getConfig() );
3986 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
3987 ? wfGetDB( DB_MASTER )
3988 : wfGetDB( DB_SLAVE );
3990 try {
3991 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
3992 'user', 'user_password', array( 'user_id' => $this->getId() ), __METHOD__
3993 ) );
3994 } catch ( PasswordError $e ) {
3995 wfDebug( 'Invalid password hash found in database.' );
3996 $mPassword = PasswordFactory::newInvalidPassword();
3999 if ( !$mPassword->equals( $password ) ) {
4000 if ( $wgLegacyEncoding ) {
4001 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4002 // Check for this with iconv
4003 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4004 if ( $cp1252Password === $password || !$mPassword->equals( $cp1252Password ) ) {
4005 return false;
4007 } else {
4008 return false;
4012 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4013 $this->setPasswordInternal( $password );
4016 return true;
4020 * Check if the given clear-text password matches the temporary password
4021 * sent by e-mail for password reset operations.
4023 * @deprecated since 1.27. AuthManager is coming.
4024 * @param string $plaintext
4025 * @return bool True if matches, false otherwise
4027 public function checkTemporaryPassword( $plaintext ) {
4028 global $wgNewPasswordExpiry;
4030 $this->load();
4032 $passwordFactory = new PasswordFactory();
4033 $passwordFactory->init( RequestContext::getMain()->getConfig() );
4034 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
4035 ? wfGetDB( DB_MASTER )
4036 : wfGetDB( DB_SLAVE );
4038 $row = $db->selectRow(
4039 'user',
4040 array( 'user_newpassword', 'user_newpass_time' ),
4041 array( 'user_id' => $this->getId() ),
4042 __METHOD__
4044 try {
4045 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword );
4046 } catch ( PasswordError $e ) {
4047 wfDebug( 'Invalid password hash found in database.' );
4048 $newPassword = PasswordFactory::newInvalidPassword();
4051 if ( $newPassword->equals( $plaintext ) ) {
4052 if ( is_null( $row->user_newpass_time ) ) {
4053 return true;
4055 $expiry = wfTimestamp( TS_UNIX, $row->user_newpass_time ) + $wgNewPasswordExpiry;
4056 return ( time() < $expiry );
4057 } else {
4058 return false;
4063 * Internal implementation for self::getEditToken() and
4064 * self::matchEditToken().
4066 * @param string|array $salt
4067 * @param WebRequest $request
4068 * @param string|int $timestamp
4069 * @return string
4071 private function getEditTokenAtTimestamp( $salt, $request, $timestamp ) {
4072 if ( $this->isAnon() ) {
4073 return self::EDIT_TOKEN_SUFFIX;
4074 } else {
4075 $token = $request->getSessionData( 'wsEditToken' );
4076 if ( $token === null ) {
4077 $token = MWCryptRand::generateHex( 32 );
4078 $request->setSessionData( 'wsEditToken', $token );
4080 if ( is_array( $salt ) ) {
4081 $salt = implode( '|', $salt );
4083 return hash_hmac( 'md5', $timestamp . $salt, $token, false ) .
4084 dechex( $timestamp ) .
4085 self::EDIT_TOKEN_SUFFIX;
4090 * Initialize (if necessary) and return a session token value
4091 * which can be used in edit forms to show that the user's
4092 * login credentials aren't being hijacked with a foreign form
4093 * submission.
4095 * @since 1.19
4097 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4098 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4099 * @return string The new edit token
4101 public function getEditToken( $salt = '', $request = null ) {
4102 return $this->getEditTokenAtTimestamp(
4103 $salt, $request ?: $this->getRequest(), wfTimestamp()
4108 * Get the embedded timestamp from a token.
4109 * @param string $val Input token
4110 * @return int|null
4112 public static function getEditTokenTimestamp( $val ) {
4113 $suffixLen = strlen( self::EDIT_TOKEN_SUFFIX );
4114 if ( strlen( $val ) <= 32 + $suffixLen ) {
4115 return null;
4118 return hexdec( substr( $val, 32, -$suffixLen ) );
4122 * Check given value against the token value stored in the session.
4123 * A match should confirm that the form was submitted from the
4124 * user's own login session, not a form submission from a third-party
4125 * site.
4127 * @param string $val Input value to compare
4128 * @param string $salt Optional function-specific data for hashing
4129 * @param WebRequest|null $request Object to use or null to use $wgRequest
4130 * @param int $maxage Fail tokens older than this, in seconds
4131 * @return bool Whether the token matches
4133 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4134 if ( $this->isAnon() ) {
4135 return $val === self::EDIT_TOKEN_SUFFIX;
4138 $timestamp = self::getEditTokenTimestamp( $val );
4139 if ( $timestamp === null ) {
4140 return false;
4142 if ( $maxage !== null && $timestamp < wfTimestamp() - $maxage ) {
4143 // Expired token
4144 return false;
4147 $sessionToken = $this->getEditTokenAtTimestamp(
4148 $salt, $request ?: $this->getRequest(), $timestamp
4151 if ( !hash_equals( $sessionToken, $val ) ) {
4152 wfDebug( "User::matchEditToken: broken session data\n" );
4155 return hash_equals( $sessionToken, $val );
4159 * Check given value against the token value stored in the session,
4160 * ignoring the suffix.
4162 * @param string $val Input value to compare
4163 * @param string $salt Optional function-specific data for hashing
4164 * @param WebRequest|null $request Object to use or null to use $wgRequest
4165 * @param int $maxage Fail tokens older than this, in seconds
4166 * @return bool Whether the token matches
4168 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4169 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self::EDIT_TOKEN_SUFFIX;
4170 return $this->matchEditToken( $val, $salt, $request, $maxage );
4174 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4175 * mail to the user's given address.
4177 * @param string $type Message to send, either "created", "changed" or "set"
4178 * @return Status
4180 public function sendConfirmationMail( $type = 'created' ) {
4181 global $wgLang;
4182 $expiration = null; // gets passed-by-ref and defined in next line.
4183 $token = $this->confirmationToken( $expiration );
4184 $url = $this->confirmationTokenUrl( $token );
4185 $invalidateURL = $this->invalidationTokenUrl( $token );
4186 $this->saveSettings();
4188 if ( $type == 'created' || $type === false ) {
4189 $message = 'confirmemail_body';
4190 } elseif ( $type === true ) {
4191 $message = 'confirmemail_body_changed';
4192 } else {
4193 // Messages: confirmemail_body_changed, confirmemail_body_set
4194 $message = 'confirmemail_body_' . $type;
4197 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4198 wfMessage( $message,
4199 $this->getRequest()->getIP(),
4200 $this->getName(),
4201 $url,
4202 $wgLang->userTimeAndDate( $expiration, $this ),
4203 $invalidateURL,
4204 $wgLang->userDate( $expiration, $this ),
4205 $wgLang->userTime( $expiration, $this ) )->text() );
4209 * Send an e-mail to this user's account. Does not check for
4210 * confirmed status or validity.
4212 * @param string $subject Message subject
4213 * @param string $body Message body
4214 * @param User|null $from Optional sending user; if unspecified, default
4215 * $wgPasswordSender will be used.
4216 * @param string $replyto Reply-To address
4217 * @return Status
4219 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4220 global $wgPasswordSender;
4222 if ( $from instanceof User ) {
4223 $sender = MailAddress::newFromUser( $from );
4224 } else {
4225 $sender = new MailAddress( $wgPasswordSender,
4226 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4228 $to = MailAddress::newFromUser( $this );
4230 return UserMailer::send( $to, $sender, $subject, $body, array(
4231 'replyTo' => $replyto,
4232 ) );
4236 * Generate, store, and return a new e-mail confirmation code.
4237 * A hash (unsalted, since it's used as a key) is stored.
4239 * @note Call saveSettings() after calling this function to commit
4240 * this change to the database.
4242 * @param string &$expiration Accepts the expiration time
4243 * @return string New token
4245 protected function confirmationToken( &$expiration ) {
4246 global $wgUserEmailConfirmationTokenExpiry;
4247 $now = time();
4248 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
4249 $expiration = wfTimestamp( TS_MW, $expires );
4250 $this->load();
4251 $token = MWCryptRand::generateHex( 32 );
4252 $hash = md5( $token );
4253 $this->mEmailToken = $hash;
4254 $this->mEmailTokenExpires = $expiration;
4255 return $token;
4259 * Return a URL the user can use to confirm their email address.
4260 * @param string $token Accepts the email confirmation token
4261 * @return string New token URL
4263 protected function confirmationTokenUrl( $token ) {
4264 return $this->getTokenUrl( 'ConfirmEmail', $token );
4268 * Return a URL the user can use to invalidate their email address.
4269 * @param string $token Accepts the email confirmation token
4270 * @return string New token URL
4272 protected function invalidationTokenUrl( $token ) {
4273 return $this->getTokenUrl( 'InvalidateEmail', $token );
4277 * Internal function to format the e-mail validation/invalidation URLs.
4278 * This uses a quickie hack to use the
4279 * hardcoded English names of the Special: pages, for ASCII safety.
4281 * @note Since these URLs get dropped directly into emails, using the
4282 * short English names avoids insanely long URL-encoded links, which
4283 * also sometimes can get corrupted in some browsers/mailers
4284 * (bug 6957 with Gmail and Internet Explorer).
4286 * @param string $page Special page
4287 * @param string $token Token
4288 * @return string Formatted URL
4290 protected function getTokenUrl( $page, $token ) {
4291 // Hack to bypass localization of 'Special:'
4292 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
4293 return $title->getCanonicalURL();
4297 * Mark the e-mail address confirmed.
4299 * @note Call saveSettings() after calling this function to commit the change.
4301 * @return bool
4303 public function confirmEmail() {
4304 // Check if it's already confirmed, so we don't touch the database
4305 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4306 if ( !$this->isEmailConfirmed() ) {
4307 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4308 Hooks::run( 'ConfirmEmailComplete', array( $this ) );
4310 return true;
4314 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4315 * address if it was already confirmed.
4317 * @note Call saveSettings() after calling this function to commit the change.
4318 * @return bool Returns true
4320 public function invalidateEmail() {
4321 $this->load();
4322 $this->mEmailToken = null;
4323 $this->mEmailTokenExpires = null;
4324 $this->setEmailAuthenticationTimestamp( null );
4325 $this->mEmail = '';
4326 Hooks::run( 'InvalidateEmailComplete', array( $this ) );
4327 return true;
4331 * Set the e-mail authentication timestamp.
4332 * @param string $timestamp TS_MW timestamp
4334 public function setEmailAuthenticationTimestamp( $timestamp ) {
4335 $this->load();
4336 $this->mEmailAuthenticated = $timestamp;
4337 Hooks::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
4341 * Is this user allowed to send e-mails within limits of current
4342 * site configuration?
4343 * @return bool
4345 public function canSendEmail() {
4346 global $wgEnableEmail, $wgEnableUserEmail;
4347 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4348 return false;
4350 $canSend = $this->isEmailConfirmed();
4351 Hooks::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4352 return $canSend;
4356 * Is this user allowed to receive e-mails within limits of current
4357 * site configuration?
4358 * @return bool
4360 public function canReceiveEmail() {
4361 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4365 * Is this user's e-mail address valid-looking and confirmed within
4366 * limits of the current site configuration?
4368 * @note If $wgEmailAuthentication is on, this may require the user to have
4369 * confirmed their address by returning a code or using a password
4370 * sent to the address from the wiki.
4372 * @return bool
4374 public function isEmailConfirmed() {
4375 global $wgEmailAuthentication;
4376 $this->load();
4377 $confirmed = true;
4378 if ( Hooks::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4379 if ( $this->isAnon() ) {
4380 return false;
4382 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4383 return false;
4385 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4386 return false;
4388 return true;
4389 } else {
4390 return $confirmed;
4395 * Check whether there is an outstanding request for e-mail confirmation.
4396 * @return bool
4398 public function isEmailConfirmationPending() {
4399 global $wgEmailAuthentication;
4400 return $wgEmailAuthentication &&
4401 !$this->isEmailConfirmed() &&
4402 $this->mEmailToken &&
4403 $this->mEmailTokenExpires > wfTimestamp();
4407 * Get the timestamp of account creation.
4409 * @return string|bool|null Timestamp of account creation, false for
4410 * non-existent/anonymous user accounts, or null if existing account
4411 * but information is not in database.
4413 public function getRegistration() {
4414 if ( $this->isAnon() ) {
4415 return false;
4417 $this->load();
4418 return $this->mRegistration;
4422 * Get the timestamp of the first edit
4424 * @return string|bool Timestamp of first edit, or false for
4425 * non-existent/anonymous user accounts.
4427 public function getFirstEditTimestamp() {
4428 if ( $this->getId() == 0 ) {
4429 return false; // anons
4431 $dbr = wfGetDB( DB_SLAVE );
4432 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4433 array( 'rev_user' => $this->getId() ),
4434 __METHOD__,
4435 array( 'ORDER BY' => 'rev_timestamp ASC' )
4437 if ( !$time ) {
4438 return false; // no edits
4440 return wfTimestamp( TS_MW, $time );
4444 * Get the permissions associated with a given list of groups
4446 * @param array $groups Array of Strings List of internal group names
4447 * @return array Array of Strings List of permission key names for given groups combined
4449 public static function getGroupPermissions( $groups ) {
4450 global $wgGroupPermissions, $wgRevokePermissions;
4451 $rights = array();
4452 // grant every granted permission first
4453 foreach ( $groups as $group ) {
4454 if ( isset( $wgGroupPermissions[$group] ) ) {
4455 $rights = array_merge( $rights,
4456 // array_filter removes empty items
4457 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4460 // now revoke the revoked permissions
4461 foreach ( $groups as $group ) {
4462 if ( isset( $wgRevokePermissions[$group] ) ) {
4463 $rights = array_diff( $rights,
4464 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4467 return array_unique( $rights );
4471 * Get all the groups who have a given permission
4473 * @param string $role Role to check
4474 * @return array Array of Strings List of internal group names with the given permission
4476 public static function getGroupsWithPermission( $role ) {
4477 global $wgGroupPermissions;
4478 $allowedGroups = array();
4479 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4480 if ( self::groupHasPermission( $group, $role ) ) {
4481 $allowedGroups[] = $group;
4484 return $allowedGroups;
4488 * Check, if the given group has the given permission
4490 * If you're wanting to check whether all users have a permission, use
4491 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4492 * from anyone.
4494 * @since 1.21
4495 * @param string $group Group to check
4496 * @param string $role Role to check
4497 * @return bool
4499 public static function groupHasPermission( $group, $role ) {
4500 global $wgGroupPermissions, $wgRevokePermissions;
4501 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4502 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4506 * Check if all users may be assumed to have the given permission
4508 * We generally assume so if the right is granted to '*' and isn't revoked
4509 * on any group. It doesn't attempt to take grants or other extension
4510 * limitations on rights into account in the general case, though, as that
4511 * would require it to always return false and defeat the purpose.
4512 * Specifically, session-based rights restrictions (such as OAuth or bot
4513 * passwords) are applied based on the current session.
4515 * @since 1.22
4516 * @param string $right Right to check
4517 * @return bool
4519 public static function isEveryoneAllowed( $right ) {
4520 global $wgGroupPermissions, $wgRevokePermissions;
4521 static $cache = array();
4523 // Use the cached results, except in unit tests which rely on
4524 // being able change the permission mid-request
4525 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4526 return $cache[$right];
4529 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
4530 $cache[$right] = false;
4531 return false;
4534 // If it's revoked anywhere, then everyone doesn't have it
4535 foreach ( $wgRevokePermissions as $rights ) {
4536 if ( isset( $rights[$right] ) && $rights[$right] ) {
4537 $cache[$right] = false;
4538 return false;
4542 // Remove any rights that aren't allowed to the global-session user
4543 $allowedRights = SessionManager::getGlobalSession()->getAllowedUserRights();
4544 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4545 $cache[$right] = false;
4546 return false;
4549 // Allow extensions to say false
4550 if ( !Hooks::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4551 $cache[$right] = false;
4552 return false;
4555 $cache[$right] = true;
4556 return true;
4560 * Get the localized descriptive name for a group, if it exists
4562 * @param string $group Internal group name
4563 * @return string Localized descriptive group name
4565 public static function getGroupName( $group ) {
4566 $msg = wfMessage( "group-$group" );
4567 return $msg->isBlank() ? $group : $msg->text();
4571 * Get the localized descriptive name for a member of a group, if it exists
4573 * @param string $group Internal group name
4574 * @param string $username Username for gender (since 1.19)
4575 * @return string Localized name for group member
4577 public static function getGroupMember( $group, $username = '#' ) {
4578 $msg = wfMessage( "group-$group-member", $username );
4579 return $msg->isBlank() ? $group : $msg->text();
4583 * Return the set of defined explicit groups.
4584 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4585 * are not included, as they are defined automatically, not in the database.
4586 * @return array Array of internal group names
4588 public static function getAllGroups() {
4589 global $wgGroupPermissions, $wgRevokePermissions;
4590 return array_diff(
4591 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4592 self::getImplicitGroups()
4597 * Get a list of all available permissions.
4598 * @return string[] Array of permission names
4600 public static function getAllRights() {
4601 if ( self::$mAllRights === false ) {
4602 global $wgAvailableRights;
4603 if ( count( $wgAvailableRights ) ) {
4604 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
4605 } else {
4606 self::$mAllRights = self::$mCoreRights;
4608 Hooks::run( 'UserGetAllRights', array( &self::$mAllRights ) );
4610 return self::$mAllRights;
4614 * Get a list of implicit groups
4615 * @return array Array of Strings Array of internal group names
4617 public static function getImplicitGroups() {
4618 global $wgImplicitGroups;
4620 $groups = $wgImplicitGroups;
4621 # Deprecated, use $wgImplicitGroups instead
4622 Hooks::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4624 return $groups;
4628 * Get the title of a page describing a particular group
4630 * @param string $group Internal group name
4631 * @return Title|bool Title of the page if it exists, false otherwise
4633 public static function getGroupPage( $group ) {
4634 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4635 if ( $msg->exists() ) {
4636 $title = Title::newFromText( $msg->text() );
4637 if ( is_object( $title ) ) {
4638 return $title;
4641 return false;
4645 * Create a link to the group in HTML, if available;
4646 * else return the group name.
4648 * @param string $group Internal name of the group
4649 * @param string $text The text of the link
4650 * @return string HTML link to the group
4652 public static function makeGroupLinkHTML( $group, $text = '' ) {
4653 if ( $text == '' ) {
4654 $text = self::getGroupName( $group );
4656 $title = self::getGroupPage( $group );
4657 if ( $title ) {
4658 return Linker::link( $title, htmlspecialchars( $text ) );
4659 } else {
4660 return htmlspecialchars( $text );
4665 * Create a link to the group in Wikitext, if available;
4666 * else return the group name.
4668 * @param string $group Internal name of the group
4669 * @param string $text The text of the link
4670 * @return string Wikilink to the group
4672 public static function makeGroupLinkWiki( $group, $text = '' ) {
4673 if ( $text == '' ) {
4674 $text = self::getGroupName( $group );
4676 $title = self::getGroupPage( $group );
4677 if ( $title ) {
4678 $page = $title->getFullText();
4679 return "[[$page|$text]]";
4680 } else {
4681 return $text;
4686 * Returns an array of the groups that a particular group can add/remove.
4688 * @param string $group The group to check for whether it can add/remove
4689 * @return array Array( 'add' => array( addablegroups ),
4690 * 'remove' => array( removablegroups ),
4691 * 'add-self' => array( addablegroups to self),
4692 * 'remove-self' => array( removable groups from self) )
4694 public static function changeableByGroup( $group ) {
4695 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4697 $groups = array(
4698 'add' => array(),
4699 'remove' => array(),
4700 'add-self' => array(),
4701 'remove-self' => array()
4704 if ( empty( $wgAddGroups[$group] ) ) {
4705 // Don't add anything to $groups
4706 } elseif ( $wgAddGroups[$group] === true ) {
4707 // You get everything
4708 $groups['add'] = self::getAllGroups();
4709 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4710 $groups['add'] = $wgAddGroups[$group];
4713 // Same thing for remove
4714 if ( empty( $wgRemoveGroups[$group] ) ) {
4715 // Do nothing
4716 } elseif ( $wgRemoveGroups[$group] === true ) {
4717 $groups['remove'] = self::getAllGroups();
4718 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4719 $groups['remove'] = $wgRemoveGroups[$group];
4722 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4723 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4724 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4725 if ( is_int( $key ) ) {
4726 $wgGroupsAddToSelf['user'][] = $value;
4731 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4732 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4733 if ( is_int( $key ) ) {
4734 $wgGroupsRemoveFromSelf['user'][] = $value;
4739 // Now figure out what groups the user can add to him/herself
4740 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4741 // Do nothing
4742 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4743 // No idea WHY this would be used, but it's there
4744 $groups['add-self'] = User::getAllGroups();
4745 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4746 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4749 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4750 // Do nothing
4751 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4752 $groups['remove-self'] = User::getAllGroups();
4753 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4754 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4757 return $groups;
4761 * Returns an array of groups that this user can add and remove
4762 * @return array Array( 'add' => array( addablegroups ),
4763 * 'remove' => array( removablegroups ),
4764 * 'add-self' => array( addablegroups to self),
4765 * 'remove-self' => array( removable groups from self) )
4767 public function changeableGroups() {
4768 if ( $this->isAllowed( 'userrights' ) ) {
4769 // This group gives the right to modify everything (reverse-
4770 // compatibility with old "userrights lets you change
4771 // everything")
4772 // Using array_merge to make the groups reindexed
4773 $all = array_merge( User::getAllGroups() );
4774 return array(
4775 'add' => $all,
4776 'remove' => $all,
4777 'add-self' => array(),
4778 'remove-self' => array()
4782 // Okay, it's not so simple, we will have to go through the arrays
4783 $groups = array(
4784 'add' => array(),
4785 'remove' => array(),
4786 'add-self' => array(),
4787 'remove-self' => array()
4789 $addergroups = $this->getEffectiveGroups();
4791 foreach ( $addergroups as $addergroup ) {
4792 $groups = array_merge_recursive(
4793 $groups, $this->changeableByGroup( $addergroup )
4795 $groups['add'] = array_unique( $groups['add'] );
4796 $groups['remove'] = array_unique( $groups['remove'] );
4797 $groups['add-self'] = array_unique( $groups['add-self'] );
4798 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4800 return $groups;
4804 * Deferred version of incEditCountImmediate()
4806 public function incEditCount() {
4807 $that = $this;
4808 wfGetDB( DB_MASTER )->onTransactionPreCommitOrIdle( function() use ( $that ) {
4809 $that->incEditCountImmediate();
4810 } );
4814 * Increment the user's edit-count field.
4815 * Will have no effect for anonymous users.
4816 * @since 1.26
4818 public function incEditCountImmediate() {
4819 if ( $this->isAnon() ) {
4820 return;
4823 $dbw = wfGetDB( DB_MASTER );
4824 // No rows will be "affected" if user_editcount is NULL
4825 $dbw->update(
4826 'user',
4827 array( 'user_editcount=user_editcount+1' ),
4828 array( 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ),
4829 __METHOD__
4831 // Lazy initialization check...
4832 if ( $dbw->affectedRows() == 0 ) {
4833 // Now here's a goddamn hack...
4834 $dbr = wfGetDB( DB_SLAVE );
4835 if ( $dbr !== $dbw ) {
4836 // If we actually have a slave server, the count is
4837 // at least one behind because the current transaction
4838 // has not been committed and replicated.
4839 $this->initEditCount( 1 );
4840 } else {
4841 // But if DB_SLAVE is selecting the master, then the
4842 // count we just read includes the revision that was
4843 // just added in the working transaction.
4844 $this->initEditCount();
4847 // Edit count in user cache too
4848 $this->invalidateCache();
4852 * Initialize user_editcount from data out of the revision table
4854 * @param int $add Edits to add to the count from the revision table
4855 * @return int Number of edits
4857 protected function initEditCount( $add = 0 ) {
4858 // Pull from a slave to be less cruel to servers
4859 // Accuracy isn't the point anyway here
4860 $dbr = wfGetDB( DB_SLAVE );
4861 $count = (int)$dbr->selectField(
4862 'revision',
4863 'COUNT(rev_user)',
4864 array( 'rev_user' => $this->getId() ),
4865 __METHOD__
4867 $count = $count + $add;
4869 $dbw = wfGetDB( DB_MASTER );
4870 $dbw->update(
4871 'user',
4872 array( 'user_editcount' => $count ),
4873 array( 'user_id' => $this->getId() ),
4874 __METHOD__
4877 return $count;
4881 * Get the description of a given right
4883 * @param string $right Right to query
4884 * @return string Localized description of the right
4886 public static function getRightDescription( $right ) {
4887 $key = "right-$right";
4888 $msg = wfMessage( $key );
4889 return $msg->isBlank() ? $right : $msg->text();
4893 * Make a new-style password hash
4895 * @param string $password Plain-text password
4896 * @param bool|string $salt Optional salt, may be random or the user ID.
4897 * If unspecified or false, will generate one automatically
4898 * @return string Password hash
4899 * @deprecated since 1.24, use Password class
4901 public static function crypt( $password, $salt = false ) {
4902 wfDeprecated( __METHOD__, '1.24' );
4903 $passwordFactory = new PasswordFactory();
4904 $passwordFactory->init( RequestContext::getMain()->getConfig() );
4905 $hash = $passwordFactory->newFromPlaintext( $password );
4906 return $hash->toString();
4910 * Compare a password hash with a plain-text password. Requires the user
4911 * ID if there's a chance that the hash is an old-style hash.
4913 * @param string $hash Password hash
4914 * @param string $password Plain-text password to compare
4915 * @param string|bool $userId User ID for old-style password salt
4917 * @return bool
4918 * @deprecated since 1.24, use Password class
4920 public static function comparePasswords( $hash, $password, $userId = false ) {
4921 wfDeprecated( __METHOD__, '1.24' );
4923 // Check for *really* old password hashes that don't even have a type
4924 // The old hash format was just an md5 hex hash, with no type information
4925 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4926 global $wgPasswordSalt;
4927 if ( $wgPasswordSalt ) {
4928 $password = ":B:{$userId}:{$hash}";
4929 } else {
4930 $password = ":A:{$hash}";
4934 $passwordFactory = new PasswordFactory();
4935 $passwordFactory->init( RequestContext::getMain()->getConfig() );
4936 $hash = $passwordFactory->newFromCiphertext( $hash );
4937 return $hash->equals( $password );
4941 * Add a newuser log entry for this user.
4942 * Before 1.19 the return value was always true.
4944 * @param string|bool $action Account creation type.
4945 * - String, one of the following values:
4946 * - 'create' for an anonymous user creating an account for himself.
4947 * This will force the action's performer to be the created user itself,
4948 * no matter the value of $wgUser
4949 * - 'create2' for a logged in user creating an account for someone else
4950 * - 'byemail' when the created user will receive its password by e-mail
4951 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4952 * - Boolean means whether the account was created by e-mail (deprecated):
4953 * - true will be converted to 'byemail'
4954 * - false will be converted to 'create' if this object is the same as
4955 * $wgUser and to 'create2' otherwise
4957 * @param string $reason User supplied reason
4959 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4961 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4962 global $wgUser, $wgNewUserLog;
4963 if ( empty( $wgNewUserLog ) ) {
4964 return true; // disabled
4967 if ( $action === true ) {
4968 $action = 'byemail';
4969 } elseif ( $action === false ) {
4970 if ( $this->equals( $wgUser ) ) {
4971 $action = 'create';
4972 } else {
4973 $action = 'create2';
4977 if ( $action === 'create' || $action === 'autocreate' ) {
4978 $performer = $this;
4979 } else {
4980 $performer = $wgUser;
4983 $logEntry = new ManualLogEntry( 'newusers', $action );
4984 $logEntry->setPerformer( $performer );
4985 $logEntry->setTarget( $this->getUserPage() );
4986 $logEntry->setComment( $reason );
4987 $logEntry->setParameters( array(
4988 '4::userid' => $this->getId(),
4989 ) );
4990 $logid = $logEntry->insert();
4992 if ( $action !== 'autocreate' ) {
4993 $logEntry->publish( $logid );
4996 return (int)$logid;
5000 * Add an autocreate newuser log entry for this user
5001 * Used by things like CentralAuth and perhaps other authplugins.
5002 * Consider calling addNewUserLogEntry() directly instead.
5004 * @return bool
5006 public function addNewUserLogEntryAutoCreate() {
5007 $this->addNewUserLogEntry( 'autocreate' );
5009 return true;
5013 * Load the user options either from cache, the database or an array
5015 * @param array $data Rows for the current user out of the user_properties table
5017 protected function loadOptions( $data = null ) {
5018 global $wgContLang;
5020 $this->load();
5022 if ( $this->mOptionsLoaded ) {
5023 return;
5026 $this->mOptions = self::getDefaultOptions();
5028 if ( !$this->getId() ) {
5029 // For unlogged-in users, load language/variant options from request.
5030 // There's no need to do it for logged-in users: they can set preferences,
5031 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5032 // so don't override user's choice (especially when the user chooses site default).
5033 $variant = $wgContLang->getDefaultVariant();
5034 $this->mOptions['variant'] = $variant;
5035 $this->mOptions['language'] = $variant;
5036 $this->mOptionsLoaded = true;
5037 return;
5040 // Maybe load from the object
5041 if ( !is_null( $this->mOptionOverrides ) ) {
5042 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5043 foreach ( $this->mOptionOverrides as $key => $value ) {
5044 $this->mOptions[$key] = $value;
5046 } else {
5047 if ( !is_array( $data ) ) {
5048 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5049 // Load from database
5050 $dbr = ( $this->queryFlagsUsed & self::READ_LATEST )
5051 ? wfGetDB( DB_MASTER )
5052 : wfGetDB( DB_SLAVE );
5054 $res = $dbr->select(
5055 'user_properties',
5056 array( 'up_property', 'up_value' ),
5057 array( 'up_user' => $this->getId() ),
5058 __METHOD__
5061 $this->mOptionOverrides = array();
5062 $data = array();
5063 foreach ( $res as $row ) {
5064 $data[$row->up_property] = $row->up_value;
5067 foreach ( $data as $property => $value ) {
5068 $this->mOptionOverrides[$property] = $value;
5069 $this->mOptions[$property] = $value;
5073 $this->mOptionsLoaded = true;
5075 Hooks::run( 'UserLoadOptions', array( $this, &$this->mOptions ) );
5079 * Saves the non-default options for this user, as previously set e.g. via
5080 * setOption(), in the database's "user_properties" (preferences) table.
5081 * Usually used via saveSettings().
5083 protected function saveOptions() {
5084 $this->loadOptions();
5086 // Not using getOptions(), to keep hidden preferences in database
5087 $saveOptions = $this->mOptions;
5089 // Allow hooks to abort, for instance to save to a global profile.
5090 // Reset options to default state before saving.
5091 if ( !Hooks::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
5092 return;
5095 $userId = $this->getId();
5097 $insert_rows = array(); // all the new preference rows
5098 foreach ( $saveOptions as $key => $value ) {
5099 // Don't bother storing default values
5100 $defaultOption = self::getDefaultOption( $key );
5101 if ( ( $defaultOption === null && $value !== false && $value !== null )
5102 || $value != $defaultOption
5104 $insert_rows[] = array(
5105 'up_user' => $userId,
5106 'up_property' => $key,
5107 'up_value' => $value,
5112 $dbw = wfGetDB( DB_MASTER );
5114 $res = $dbw->select( 'user_properties',
5115 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__ );
5117 // Find prior rows that need to be removed or updated. These rows will
5118 // all be deleted (the later so that INSERT IGNORE applies the new values).
5119 $keysDelete = array();
5120 foreach ( $res as $row ) {
5121 if ( !isset( $saveOptions[$row->up_property] )
5122 || strcmp( $saveOptions[$row->up_property], $row->up_value ) != 0
5124 $keysDelete[] = $row->up_property;
5128 if ( count( $keysDelete ) ) {
5129 // Do the DELETE by PRIMARY KEY for prior rows.
5130 // In the past a very large portion of calls to this function are for setting
5131 // 'rememberpassword' for new accounts (a preference that has since been removed).
5132 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5133 // caused gap locks on [max user ID,+infinity) which caused high contention since
5134 // updates would pile up on each other as they are for higher (newer) user IDs.
5135 // It might not be necessary these days, but it shouldn't hurt either.
5136 $dbw->delete( 'user_properties',
5137 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__ );
5139 // Insert the new preference rows
5140 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, array( 'IGNORE' ) );
5144 * Lazily instantiate and return a factory object for making passwords
5146 * @deprecated since 1.27, create a PasswordFactory directly instead
5147 * @return PasswordFactory
5149 public static function getPasswordFactory() {
5150 wfDeprecated( __METHOD__, '1.27' );
5151 $ret = new PasswordFactory();
5152 $ret->init( RequestContext::getMain()->getConfig() );
5153 return $ret;
5157 * Provide an array of HTML5 attributes to put on an input element
5158 * intended for the user to enter a new password. This may include
5159 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5161 * Do *not* use this when asking the user to enter his current password!
5162 * Regardless of configuration, users may have invalid passwords for whatever
5163 * reason (e.g., they were set before requirements were tightened up).
5164 * Only use it when asking for a new password, like on account creation or
5165 * ResetPass.
5167 * Obviously, you still need to do server-side checking.
5169 * NOTE: A combination of bugs in various browsers means that this function
5170 * actually just returns array() unconditionally at the moment. May as
5171 * well keep it around for when the browser bugs get fixed, though.
5173 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5175 * @deprecated since 1.27
5176 * @return array Array of HTML attributes suitable for feeding to
5177 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5178 * That will get confused by the boolean attribute syntax used.)
5180 public static function passwordChangeInputAttribs() {
5181 global $wgMinimalPasswordLength;
5183 if ( $wgMinimalPasswordLength == 0 ) {
5184 return array();
5187 # Note that the pattern requirement will always be satisfied if the
5188 # input is empty, so we need required in all cases.
5190 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5191 # if e-mail confirmation is being used. Since HTML5 input validation
5192 # is b0rked anyway in some browsers, just return nothing. When it's
5193 # re-enabled, fix this code to not output required for e-mail
5194 # registration.
5195 # $ret = array( 'required' );
5196 $ret = array();
5198 # We can't actually do this right now, because Opera 9.6 will print out
5199 # the entered password visibly in its error message! When other
5200 # browsers add support for this attribute, or Opera fixes its support,
5201 # we can add support with a version check to avoid doing this on Opera
5202 # versions where it will be a problem. Reported to Opera as
5203 # DSK-262266, but they don't have a public bug tracker for us to follow.
5205 if ( $wgMinimalPasswordLength > 1 ) {
5206 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5207 $ret['title'] = wfMessage( 'passwordtooshort' )
5208 ->numParams( $wgMinimalPasswordLength )->text();
5212 return $ret;
5216 * Return the list of user fields that should be selected to create
5217 * a new user object.
5218 * @return array
5220 public static function selectFields() {
5221 return array(
5222 'user_id',
5223 'user_name',
5224 'user_real_name',
5225 'user_email',
5226 'user_touched',
5227 'user_token',
5228 'user_email_authenticated',
5229 'user_email_token',
5230 'user_email_token_expires',
5231 'user_registration',
5232 'user_editcount',
5237 * Factory function for fatal permission-denied errors
5239 * @since 1.22
5240 * @param string $permission User right required
5241 * @return Status
5243 static function newFatalPermissionDeniedStatus( $permission ) {
5244 global $wgLang;
5246 $groups = array_map(
5247 array( 'User', 'makeGroupLinkWiki' ),
5248 User::getGroupsWithPermission( $permission )
5251 if ( $groups ) {
5252 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5253 } else {
5254 return Status::newFatal( 'badaccess-group0' );
5259 * Get a new instance of this user that was loaded from the master via a locking read
5261 * Use this instead of the main context User when updating that user. This avoids races
5262 * where that user was loaded from a slave or even the master but without proper locks.
5264 * @return User|null Returns null if the user was not found in the DB
5265 * @since 1.27
5267 public function getInstanceForUpdate() {
5268 if ( !$this->getId() ) {
5269 return null; // anon
5272 $user = self::newFromId( $this->getId() );
5273 if ( !$user->loadFromId( self::READ_EXCLUSIVE ) ) {
5274 return null;
5277 return $user;
5281 * Checks if two user objects point to the same user.
5283 * @since 1.25
5284 * @param User $user
5285 * @return bool
5287 public function equals( User $user ) {
5288 return $this->getName() === $user->getName();