Merge "Improve the wording of apihelp-parse-param-section"
[mediawiki.git] / includes / User.php
blobd57dfaac159c1254773eb4be5dc8aaa8b4cb30d6
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 /**
24 * String Some punctuation to prevent editing from broken text-mangling proxies.
25 * @ingroup Constants
27 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
29 /**
30 * The User object encapsulates all of the user-specific settings (user_id,
31 * name, rights, password, email address, options, last login time). Client
32 * classes use the getXXX() functions to access these fields. These functions
33 * do all the work of determining whether the user is logged in,
34 * whether the requested option can be satisfied from cookies or
35 * whether a database query is needed. Most of the settings needed
36 * for rendering normal pages are set in the cookie to minimize use
37 * of the database.
39 class User implements IDBAccessObject {
40 /**
41 * @const int Number of characters in user_token field.
43 const TOKEN_LENGTH = 32;
45 /**
46 * Global constant made accessible as class constants so that autoloader
47 * magic can be used.
49 const EDIT_TOKEN_SUFFIX = EDIT_TOKEN_SUFFIX;
51 /**
52 * @const int Serialized record version.
54 const VERSION = 10;
56 /**
57 * Maximum items in $mWatchedItems
59 const MAX_WATCHED_ITEMS_CACHE = 100;
61 /**
62 * Exclude user options that are set to their default value.
63 * @since 1.25
65 const GETOPTIONS_EXCLUDE_DEFAULTS = 1;
67 /**
68 * @var PasswordFactory Lazily loaded factory object for passwords
70 private static $mPasswordFactory = null;
72 /**
73 * Array of Strings List of member variables which are saved to the
74 * shared cache (memcached). Any operation which changes the
75 * corresponding database fields must call a cache-clearing function.
76 * @showinitializer
78 protected static $mCacheVars = array(
79 // user table
80 'mId',
81 'mName',
82 'mRealName',
83 'mEmail',
84 'mTouched',
85 'mToken',
86 'mEmailAuthenticated',
87 'mEmailToken',
88 'mEmailTokenExpires',
89 'mRegistration',
90 'mEditCount',
91 // user_groups table
92 'mGroups',
93 // user_properties table
94 'mOptionOverrides',
97 /**
98 * Array of Strings Core rights.
99 * Each of these should have a corresponding message of the form
100 * "right-$right".
101 * @showinitializer
103 protected static $mCoreRights = array(
104 'apihighlimits',
105 'applychangetags',
106 'autoconfirmed',
107 'autopatrol',
108 'bigdelete',
109 'block',
110 'blockemail',
111 'bot',
112 'browsearchive',
113 'changetags',
114 'createaccount',
115 'createpage',
116 'createtalk',
117 'delete',
118 'deletedhistory',
119 'deletedtext',
120 'deletelogentry',
121 'deleterevision',
122 'edit',
123 'editcontentmodel',
124 'editinterface',
125 'editprotected',
126 'editmyoptions',
127 'editmyprivateinfo',
128 'editmyusercss',
129 'editmyuserjs',
130 'editmywatchlist',
131 'editsemiprotected',
132 'editusercssjs', #deprecated
133 'editusercss',
134 'edituserjs',
135 'hideuser',
136 'import',
137 'importupload',
138 'ipblock-exempt',
139 'managechangetags',
140 'markbotedits',
141 'mergehistory',
142 'minoredit',
143 'move',
144 'movefile',
145 'move-categorypages',
146 'move-rootuserpages',
147 'move-subpages',
148 'nominornewtalk',
149 'noratelimit',
150 'override-export-depth',
151 'pagelang',
152 'passwordreset',
153 'patrol',
154 'patrolmarks',
155 'protect',
156 'proxyunbannable',
157 'purge',
158 'read',
159 'reupload',
160 'reupload-own',
161 'reupload-shared',
162 'rollback',
163 'sendemail',
164 'siteadmin',
165 'suppressionlog',
166 'suppressredirect',
167 'suppressrevision',
168 'unblockself',
169 'undelete',
170 'unwatchedpages',
171 'upload',
172 'upload_by_url',
173 'userrights',
174 'userrights-interwiki',
175 'viewmyprivateinfo',
176 'viewmywatchlist',
177 'viewsuppressed',
178 'writeapi',
182 * String Cached results of getAllRights()
184 protected static $mAllRights = false;
186 /** Cache variables */
187 //@{
188 public $mId;
189 /** @var string */
190 public $mName;
191 /** @var string */
192 public $mRealName;
194 * @todo Make this actually private
195 * @private
196 * @var Password
198 public $mPassword;
200 * @todo Make this actually private
201 * @private
202 * @var Password
204 public $mNewpassword;
205 /** @var string */
206 public $mNewpassTime;
207 /** @var string */
208 public $mEmail;
209 /** @var string TS_MW timestamp from the DB */
210 public $mTouched;
211 /** @var string TS_MW timestamp from cache */
212 protected $mQuickTouched;
213 /** @var string */
214 protected $mToken;
215 /** @var string */
216 public $mEmailAuthenticated;
217 /** @var string */
218 protected $mEmailToken;
219 /** @var string */
220 protected $mEmailTokenExpires;
221 /** @var string */
222 protected $mRegistration;
223 /** @var int */
224 protected $mEditCount;
225 /** @var array */
226 public $mGroups;
227 /** @var array */
228 protected $mOptionOverrides;
229 /** @var string */
230 protected $mPasswordExpires;
231 //@}
234 * Bool Whether the cache variables have been loaded.
236 //@{
237 public $mOptionsLoaded;
240 * Array with already loaded items or true if all items have been loaded.
242 protected $mLoadedItems = array();
243 //@}
246 * String Initialization data source if mLoadedItems!==true. May be one of:
247 * - 'defaults' anonymous user initialised from class defaults
248 * - 'name' initialise from mName
249 * - 'id' initialise from mId
250 * - 'session' log in from cookies or session if possible
252 * Use the User::newFrom*() family of functions to set this.
254 public $mFrom;
257 * Lazy-initialized variables, invalidated with clearInstanceCache
259 protected $mNewtalk;
260 /** @var string */
261 protected $mDatePreference;
262 /** @var string */
263 public $mBlockedby;
264 /** @var string */
265 protected $mHash;
266 /** @var array */
267 public $mRights;
268 /** @var string */
269 protected $mBlockreason;
270 /** @var array */
271 protected $mEffectiveGroups;
272 /** @var array */
273 protected $mImplicitGroups;
274 /** @var array */
275 protected $mFormerGroups;
276 /** @var bool */
277 protected $mBlockedGlobally;
278 /** @var bool */
279 protected $mLocked;
280 /** @var bool */
281 public $mHideName;
282 /** @var array */
283 public $mOptions;
286 * @var WebRequest
288 private $mRequest;
290 /** @var Block */
291 public $mBlock;
293 /** @var bool */
294 protected $mAllowUsertalk;
296 /** @var Block */
297 private $mBlockedFromCreateAccount = false;
299 /** @var array */
300 private $mWatchedItems = array();
302 /** @var integer User::READ_* constant bitfield used to load data */
303 protected $queryFlagsUsed = self::READ_NORMAL;
305 public static $idCacheByName = array();
308 * Lightweight constructor for an anonymous user.
309 * Use the User::newFrom* factory functions for other kinds of users.
311 * @see newFromName()
312 * @see newFromId()
313 * @see newFromConfirmationCode()
314 * @see newFromSession()
315 * @see newFromRow()
317 public function __construct() {
318 $this->clearInstanceCache( 'defaults' );
322 * @return string
324 public function __toString() {
325 return $this->getName();
329 * Load the user table data for this object from the source given by mFrom.
331 * @param integer $flags User::READ_* constant bitfield
333 public function load( $flags = self::READ_NORMAL ) {
334 if ( $this->mLoadedItems === true ) {
335 return;
338 // Set it now to avoid infinite recursion in accessors
339 $this->mLoadedItems = true;
340 $this->queryFlagsUsed = $flags;
342 switch ( $this->mFrom ) {
343 case 'defaults':
344 $this->loadDefaults();
345 break;
346 case 'name':
347 // Make sure this thread sees its own changes
348 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
349 $flags |= self::READ_LATEST;
350 $this->queryFlagsUsed = $flags;
353 $this->mId = self::idFromName( $this->mName, $flags );
354 if ( !$this->mId ) {
355 // Nonexistent user placeholder object
356 $this->loadDefaults( $this->mName );
357 } else {
358 $this->loadFromId( $flags );
360 break;
361 case 'id':
362 $this->loadFromId( $flags );
363 break;
364 case 'session':
365 if ( !$this->loadFromSession() ) {
366 // Loading from session failed. Load defaults.
367 $this->loadDefaults();
369 Hooks::run( 'UserLoadAfterLoadFromSession', array( $this ) );
370 break;
371 default:
372 throw new UnexpectedValueException(
373 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
378 * Load user table data, given mId has already been set.
379 * @param integer $flags User::READ_* constant bitfield
380 * @return bool False if the ID does not exist, true otherwise
382 public function loadFromId( $flags = self::READ_NORMAL ) {
383 if ( $this->mId == 0 ) {
384 $this->loadDefaults();
385 return false;
388 // Try cache (unless this needs to lock the DB).
389 // NOTE: if this thread called saveSettings(), the cache was cleared.
390 $locking = ( ( $flags & self::READ_LOCKING ) == self::READ_LOCKING );
391 if ( $locking || !$this->loadFromCache() ) {
392 wfDebug( "User: cache miss for user {$this->mId}\n" );
393 // Load from DB (make sure this thread sees its own changes)
394 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
395 $flags |= self::READ_LATEST;
397 if ( !$this->loadFromDatabase( $flags ) ) {
398 // Can't load from ID, user is anonymous
399 return false;
401 $this->saveToCache();
404 $this->mLoadedItems = true;
405 $this->queryFlagsUsed = $flags;
407 return true;
411 * Load user data from shared cache, given mId has already been set.
413 * @return bool false if the ID does not exist or data is invalid, true otherwise
414 * @since 1.25
416 protected function loadFromCache() {
417 if ( $this->mId == 0 ) {
418 $this->loadDefaults();
419 return false;
422 $key = wfMemcKey( 'user', 'id', $this->mId );
423 $data = ObjectCache::getMainWANInstance()->get( $key );
424 if ( !is_array( $data ) || $data['mVersion'] < self::VERSION ) {
425 // Object is expired
426 return false;
429 wfDebug( "User: got user {$this->mId} from cache\n" );
431 // Restore from cache
432 foreach ( self::$mCacheVars as $name ) {
433 $this->$name = $data[$name];
436 return true;
440 * Save user data to the shared cache
442 * This method should not be called outside the User class
444 public function saveToCache() {
445 $this->load();
446 $this->loadGroups();
447 $this->loadOptions();
449 if ( $this->isAnon() ) {
450 // Anonymous users are uncached
451 return;
454 $data = array();
455 foreach ( self::$mCacheVars as $name ) {
456 $data[$name] = $this->$name;
458 $data['mVersion'] = self::VERSION;
459 $key = wfMemcKey( 'user', 'id', $this->mId );
461 ObjectCache::getMainWANInstance()->set( $key, $data, 3600 );
464 /** @name newFrom*() static factory methods */
465 //@{
468 * Static factory method for creation from username.
470 * This is slightly less efficient than newFromId(), so use newFromId() if
471 * you have both an ID and a name handy.
473 * @param string $name Username, validated by Title::newFromText()
474 * @param string|bool $validate Validate username. Takes the same parameters as
475 * User::getCanonicalName(), except that true is accepted as an alias
476 * for 'valid', for BC.
478 * @return User|bool User object, or false if the username is invalid
479 * (e.g. if it contains illegal characters or is an IP address). If the
480 * username is not present in the database, the result will be a user object
481 * with a name, zero user ID and default settings.
483 public static function newFromName( $name, $validate = 'valid' ) {
484 if ( $validate === true ) {
485 $validate = 'valid';
487 $name = self::getCanonicalName( $name, $validate );
488 if ( $name === false ) {
489 return false;
490 } else {
491 // Create unloaded user object
492 $u = new User;
493 $u->mName = $name;
494 $u->mFrom = 'name';
495 $u->setItemLoaded( 'name' );
496 return $u;
501 * Static factory method for creation from a given user ID.
503 * @param int $id Valid user ID
504 * @return User The corresponding User object
506 public static function newFromId( $id ) {
507 $u = new User;
508 $u->mId = $id;
509 $u->mFrom = 'id';
510 $u->setItemLoaded( 'id' );
511 return $u;
515 * Factory method to fetch whichever user has a given email confirmation code.
516 * This code is generated when an account is created or its e-mail address
517 * has changed.
519 * If the code is invalid or has expired, returns NULL.
521 * @param string $code Confirmation code
522 * @param int $flags User::READ_* bitfield
523 * @return User|null
525 public static function newFromConfirmationCode( $code, $flags = 0 ) {
526 $db = ( $flags & self::READ_LATEST ) == self::READ_LATEST
527 ? wfGetDB( DB_MASTER )
528 : wfGetDB( DB_SLAVE );
530 $id = $db->selectField(
531 'user',
532 'user_id',
533 array(
534 'user_email_token' => md5( $code ),
535 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
539 return $id ? User::newFromId( $id ) : null;
543 * Create a new user object using data from session or cookies. If the
544 * login credentials are invalid, the result is an anonymous user.
546 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
547 * @return User
549 public static function newFromSession( WebRequest $request = null ) {
550 $user = new User;
551 $user->mFrom = 'session';
552 $user->mRequest = $request;
553 return $user;
557 * Create a new user object from a user row.
558 * The row should have the following fields from the user table in it:
559 * - either user_name or user_id to load further data if needed (or both)
560 * - user_real_name
561 * - all other fields (email, password, etc.)
562 * It is useless to provide the remaining fields if either user_id,
563 * user_name and user_real_name are not provided because the whole row
564 * will be loaded once more from the database when accessing them.
566 * @param stdClass $row A row from the user table
567 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
568 * @return User
570 public static function newFromRow( $row, $data = null ) {
571 $user = new User;
572 $user->loadFromRow( $row, $data );
573 return $user;
576 //@}
579 * Get the username corresponding to a given user ID
580 * @param int $id User ID
581 * @return string|bool The corresponding username
583 public static function whoIs( $id ) {
584 return UserCache::singleton()->getProp( $id, 'name' );
588 * Get the real name of a user given their user ID
590 * @param int $id User ID
591 * @return string|bool The corresponding user's real name
593 public static function whoIsReal( $id ) {
594 return UserCache::singleton()->getProp( $id, 'real_name' );
598 * Get database id given a user name
599 * @param string $name Username
600 * @param integer $flags User::READ_* constant bitfield
601 * @return int|null The corresponding user's ID, or null if user is nonexistent
603 public static function idFromName( $name, $flags = self::READ_NORMAL ) {
604 $nt = Title::makeTitleSafe( NS_USER, $name );
605 if ( is_null( $nt ) ) {
606 // Illegal name
607 return null;
610 if ( isset( self::$idCacheByName[$name] ) ) {
611 return self::$idCacheByName[$name];
614 $db = ( $flags & self::READ_LATEST )
615 ? wfGetDB( DB_MASTER )
616 : wfGetDB( DB_SLAVE );
618 $s = $db->selectRow(
619 'user',
620 array( 'user_id' ),
621 array( 'user_name' => $nt->getText() ),
622 __METHOD__
625 if ( $s === false ) {
626 $result = null;
627 } else {
628 $result = $s->user_id;
631 self::$idCacheByName[$name] = $result;
633 if ( count( self::$idCacheByName ) > 1000 ) {
634 self::$idCacheByName = array();
637 return $result;
641 * Reset the cache used in idFromName(). For use in tests.
643 public static function resetIdByNameCache() {
644 self::$idCacheByName = array();
648 * Does the string match an anonymous IPv4 address?
650 * This function exists for username validation, in order to reject
651 * usernames which are similar in form to IP addresses. Strings such
652 * as 300.300.300.300 will return true because it looks like an IP
653 * address, despite not being strictly valid.
655 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
656 * address because the usemod software would "cloak" anonymous IP
657 * addresses like this, if we allowed accounts like this to be created
658 * new users could get the old edits of these anonymous users.
660 * @param string $name Name to match
661 * @return bool
663 public static function isIP( $name ) {
664 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
665 || IP::isIPv6( $name );
669 * Is the input a valid username?
671 * Checks if the input is a valid username, we don't want an empty string,
672 * an IP address, anything that contains slashes (would mess up subpages),
673 * is longer than the maximum allowed username size or doesn't begin with
674 * a capital letter.
676 * @param string $name Name to match
677 * @return bool
679 public static function isValidUserName( $name ) {
680 global $wgContLang, $wgMaxNameChars;
682 if ( $name == ''
683 || User::isIP( $name )
684 || strpos( $name, '/' ) !== false
685 || strlen( $name ) > $wgMaxNameChars
686 || $name != $wgContLang->ucfirst( $name )
688 wfDebugLog( 'username', __METHOD__ .
689 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
690 return false;
693 // Ensure that the name can't be misresolved as a different title,
694 // such as with extra namespace keys at the start.
695 $parsed = Title::newFromText( $name );
696 if ( is_null( $parsed )
697 || $parsed->getNamespace()
698 || strcmp( $name, $parsed->getPrefixedText() ) ) {
699 wfDebugLog( 'username', __METHOD__ .
700 ": '$name' invalid due to ambiguous prefixes" );
701 return false;
704 // Check an additional blacklist of troublemaker characters.
705 // Should these be merged into the title char list?
706 $unicodeBlacklist = '/[' .
707 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
708 '\x{00a0}' . # non-breaking space
709 '\x{2000}-\x{200f}' . # various whitespace
710 '\x{2028}-\x{202f}' . # breaks and control chars
711 '\x{3000}' . # ideographic space
712 '\x{e000}-\x{f8ff}' . # private use
713 ']/u';
714 if ( preg_match( $unicodeBlacklist, $name ) ) {
715 wfDebugLog( 'username', __METHOD__ .
716 ": '$name' invalid due to blacklisted characters" );
717 return false;
720 return true;
724 * Usernames which fail to pass this function will be blocked
725 * from user login and new account registrations, but may be used
726 * internally by batch processes.
728 * If an account already exists in this form, login will be blocked
729 * by a failure to pass this function.
731 * @param string $name Name to match
732 * @return bool
734 public static function isUsableName( $name ) {
735 global $wgReservedUsernames;
736 // Must be a valid username, obviously ;)
737 if ( !self::isValidUserName( $name ) ) {
738 return false;
741 static $reservedUsernames = false;
742 if ( !$reservedUsernames ) {
743 $reservedUsernames = $wgReservedUsernames;
744 Hooks::run( 'UserGetReservedNames', array( &$reservedUsernames ) );
747 // Certain names may be reserved for batch processes.
748 foreach ( $reservedUsernames as $reserved ) {
749 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
750 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
752 if ( $reserved == $name ) {
753 return false;
756 return true;
760 * Usernames which fail to pass this function will be blocked
761 * from new account registrations, but may be used internally
762 * either by batch processes or by user accounts which have
763 * already been created.
765 * Additional blacklisting may be added here rather than in
766 * isValidUserName() to avoid disrupting existing accounts.
768 * @param string $name String to match
769 * @return bool
771 public static function isCreatableName( $name ) {
772 global $wgInvalidUsernameCharacters;
774 // Ensure that the username isn't longer than 235 bytes, so that
775 // (at least for the builtin skins) user javascript and css files
776 // will work. (bug 23080)
777 if ( strlen( $name ) > 235 ) {
778 wfDebugLog( 'username', __METHOD__ .
779 ": '$name' invalid due to length" );
780 return false;
783 // Preg yells if you try to give it an empty string
784 if ( $wgInvalidUsernameCharacters !== '' ) {
785 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
786 wfDebugLog( 'username', __METHOD__ .
787 ": '$name' invalid due to wgInvalidUsernameCharacters" );
788 return false;
792 return self::isUsableName( $name );
796 * Is the input a valid password for this user?
798 * @param string $password Desired password
799 * @return bool
801 public function isValidPassword( $password ) {
802 //simple boolean wrapper for getPasswordValidity
803 return $this->getPasswordValidity( $password ) === true;
808 * Given unvalidated password input, return error message on failure.
810 * @param string $password Desired password
811 * @return bool|string|array True on success, string or array of error message on failure
813 public function getPasswordValidity( $password ) {
814 $result = $this->checkPasswordValidity( $password );
815 if ( $result->isGood() ) {
816 return true;
817 } else {
818 $messages = array();
819 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
820 $messages[] = $error['message'];
822 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
823 $messages[] = $warning['message'];
825 if ( count( $messages ) === 1 ) {
826 return $messages[0];
828 return $messages;
833 * Check if this is a valid password for this user
835 * Create a Status object based on the password's validity.
836 * The Status should be set to fatal if the user should not
837 * be allowed to log in, and should have any errors that
838 * would block changing the password.
840 * If the return value of this is not OK, the password
841 * should not be checked. If the return value is not Good,
842 * the password can be checked, but the user should not be
843 * able to set their password to this.
845 * @param string $password Desired password
846 * @param string $purpose one of 'login', 'create', 'reset'
847 * @return Status
848 * @since 1.23
850 public function checkPasswordValidity( $password, $purpose = 'login' ) {
851 global $wgPasswordPolicy;
853 $upp = new UserPasswordPolicy(
854 $wgPasswordPolicy['policies'],
855 $wgPasswordPolicy['checks']
858 $status = Status::newGood();
859 $result = false; //init $result to false for the internal checks
861 if ( !Hooks::run( 'isValidPassword', array( $password, &$result, $this ) ) ) {
862 $status->error( $result );
863 return $status;
866 if ( $result === false ) {
867 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
868 return $status;
869 } elseif ( $result === true ) {
870 return $status;
871 } else {
872 $status->error( $result );
873 return $status; //the isValidPassword hook set a string $result and returned true
878 * Expire a user's password
879 * @since 1.23
880 * @param int $ts Optional timestamp to convert, default 0 for the current time
882 public function expirePassword( $ts = 0 ) {
883 $this->loadPasswords();
884 $timestamp = wfTimestamp( TS_MW, $ts );
885 $this->mPasswordExpires = $timestamp;
886 $this->saveSettings();
890 * Clear the password expiration for a user
891 * @since 1.23
892 * @param bool $load Ensure user object is loaded first
894 public function resetPasswordExpiration( $load = true ) {
895 global $wgPasswordExpirationDays;
896 if ( $load ) {
897 $this->load();
899 $newExpire = null;
900 if ( $wgPasswordExpirationDays ) {
901 $newExpire = wfTimestamp(
902 TS_MW,
903 time() + ( $wgPasswordExpirationDays * 24 * 3600 )
906 // Give extensions a chance to force an expiration
907 Hooks::run( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
908 $this->mPasswordExpires = $newExpire;
912 * Check if the user's password is expired.
913 * TODO: Put this and password length into a PasswordPolicy object
914 * @since 1.23
915 * @return string|bool The expiration type, or false if not expired
916 * hard: A password change is required to login
917 * soft: Allow login, but encourage password change
918 * false: Password is not expired
920 public function getPasswordExpired() {
921 global $wgPasswordExpireGrace;
922 $expired = false;
923 $now = wfTimestamp();
924 $expiration = $this->getPasswordExpireDate();
925 $expUnix = wfTimestamp( TS_UNIX, $expiration );
926 if ( $expiration !== null && $expUnix < $now ) {
927 $expired = ( $expUnix + $wgPasswordExpireGrace < $now ) ? 'hard' : 'soft';
929 return $expired;
933 * Get this user's password expiration date. Since this may be using
934 * the cached User object, we assume that whatever mechanism is setting
935 * the expiration date is also expiring the User cache.
936 * @since 1.23
937 * @return string|bool The datestamp of the expiration, or null if not set
939 public function getPasswordExpireDate() {
940 $this->load();
941 return $this->mPasswordExpires;
945 * Given unvalidated user input, return a canonical username, or false if
946 * the username is invalid.
947 * @param string $name User input
948 * @param string|bool $validate Type of validation to use:
949 * - false No validation
950 * - 'valid' Valid for batch processes
951 * - 'usable' Valid for batch processes and login
952 * - 'creatable' Valid for batch processes, login and account creation
954 * @throws InvalidArgumentException
955 * @return bool|string
957 public static function getCanonicalName( $name, $validate = 'valid' ) {
958 // Force usernames to capital
959 global $wgContLang;
960 $name = $wgContLang->ucfirst( $name );
962 # Reject names containing '#'; these will be cleaned up
963 # with title normalisation, but then it's too late to
964 # check elsewhere
965 if ( strpos( $name, '#' ) !== false ) {
966 return false;
969 // Clean up name according to title rules,
970 // but only when validation is requested (bug 12654)
971 $t = ( $validate !== false ) ?
972 Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
973 // Check for invalid titles
974 if ( is_null( $t ) ) {
975 return false;
978 // Reject various classes of invalid names
979 global $wgAuth;
980 $name = $wgAuth->getCanonicalName( $t->getText() );
982 switch ( $validate ) {
983 case false:
984 break;
985 case 'valid':
986 if ( !User::isValidUserName( $name ) ) {
987 $name = false;
989 break;
990 case 'usable':
991 if ( !User::isUsableName( $name ) ) {
992 $name = false;
994 break;
995 case 'creatable':
996 if ( !User::isCreatableName( $name ) ) {
997 $name = false;
999 break;
1000 default:
1001 throw new InvalidArgumentException(
1002 'Invalid parameter value for $validate in ' . __METHOD__ );
1004 return $name;
1008 * Count the number of edits of a user
1010 * @param int $uid User ID to check
1011 * @return int The user's edit count
1013 * @deprecated since 1.21 in favour of User::getEditCount
1015 public static function edits( $uid ) {
1016 wfDeprecated( __METHOD__, '1.21' );
1017 $user = self::newFromId( $uid );
1018 return $user->getEditCount();
1022 * Return a random password.
1024 * @return string New random password
1026 public static function randomPassword() {
1027 global $wgMinimalPasswordLength;
1028 // Decide the final password length based on our min password length,
1029 // stopping at a minimum of 10 chars.
1030 $length = max( 10, $wgMinimalPasswordLength );
1031 // Multiply by 1.25 to get the number of hex characters we need
1032 $length = $length * 1.25;
1033 // Generate random hex chars
1034 $hex = MWCryptRand::generateHex( $length );
1035 // Convert from base 16 to base 32 to get a proper password like string
1036 return wfBaseConvert( $hex, 16, 32 );
1040 * Set cached properties to default.
1042 * @note This no longer clears uncached lazy-initialised properties;
1043 * the constructor does that instead.
1045 * @param string|bool $name
1047 public function loadDefaults( $name = false ) {
1049 $passwordFactory = self::getPasswordFactory();
1051 $this->mId = 0;
1052 $this->mName = $name;
1053 $this->mRealName = '';
1054 $this->mPassword = $passwordFactory->newFromCiphertext( null );
1055 $this->mNewpassword = $passwordFactory->newFromCiphertext( null );
1056 $this->mNewpassTime = null;
1057 $this->mEmail = '';
1058 $this->mOptionOverrides = null;
1059 $this->mOptionsLoaded = false;
1061 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1062 if ( $loggedOut !== null ) {
1063 $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
1064 } else {
1065 $this->mTouched = '1'; # Allow any pages to be cached
1068 $this->mToken = null; // Don't run cryptographic functions till we need a token
1069 $this->mEmailAuthenticated = null;
1070 $this->mEmailToken = '';
1071 $this->mEmailTokenExpires = null;
1072 $this->mPasswordExpires = null;
1073 $this->resetPasswordExpiration( false );
1074 $this->mRegistration = wfTimestamp( TS_MW );
1075 $this->mGroups = array();
1077 Hooks::run( 'UserLoadDefaults', array( $this, $name ) );
1081 * Return whether an item has been loaded.
1083 * @param string $item Item to check. Current possibilities:
1084 * - id
1085 * - name
1086 * - realname
1087 * @param string $all 'all' to check if the whole object has been loaded
1088 * or any other string to check if only the item is available (e.g.
1089 * for optimisation)
1090 * @return bool
1092 public function isItemLoaded( $item, $all = 'all' ) {
1093 return ( $this->mLoadedItems === true && $all === 'all' ) ||
1094 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
1098 * Set that an item has been loaded
1100 * @param string $item
1102 protected function setItemLoaded( $item ) {
1103 if ( is_array( $this->mLoadedItems ) ) {
1104 $this->mLoadedItems[$item] = true;
1109 * Load user data from the session or login cookie.
1111 * @return bool True if the user is logged in, false otherwise.
1113 private function loadFromSession() {
1114 $result = null;
1115 Hooks::run( 'UserLoadFromSession', array( $this, &$result ) );
1116 if ( $result !== null ) {
1117 return $result;
1120 $request = $this->getRequest();
1122 $cookieId = $request->getCookie( 'UserID' );
1123 $sessId = $request->getSessionData( 'wsUserID' );
1125 if ( $cookieId !== null ) {
1126 $sId = intval( $cookieId );
1127 if ( $sessId !== null && $cookieId != $sessId ) {
1128 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1129 cookie user ID ($sId) don't match!" );
1130 return false;
1132 $request->setSessionData( 'wsUserID', $sId );
1133 } elseif ( $sessId !== null && $sessId != 0 ) {
1134 $sId = $sessId;
1135 } else {
1136 return false;
1139 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1140 $sName = $request->getSessionData( 'wsUserName' );
1141 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1142 $sName = $request->getCookie( 'UserName' );
1143 $request->setSessionData( 'wsUserName', $sName );
1144 } else {
1145 return false;
1148 $proposedUser = User::newFromId( $sId );
1149 if ( !$proposedUser->isLoggedIn() ) {
1150 // Not a valid ID
1151 return false;
1154 global $wgBlockDisablesLogin;
1155 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1156 // User blocked and we've disabled blocked user logins
1157 return false;
1160 if ( $request->getSessionData( 'wsToken' ) ) {
1161 $passwordCorrect =
1162 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1163 $from = 'session';
1164 } elseif ( $request->getCookie( 'Token' ) ) {
1165 # Get the token from DB/cache and clean it up to remove garbage padding.
1166 # This deals with historical problems with bugs and the default column value.
1167 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1168 // Make comparison in constant time (bug 61346)
1169 $passwordCorrect = strlen( $token )
1170 && hash_equals( $token, $request->getCookie( 'Token' ) );
1171 $from = 'cookie';
1172 } else {
1173 // No session or persistent login cookie
1174 return false;
1177 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1178 $this->loadFromUserObject( $proposedUser );
1179 $request->setSessionData( 'wsToken', $this->mToken );
1180 wfDebug( "User: logged in from $from\n" );
1181 return true;
1182 } else {
1183 // Invalid credentials
1184 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1185 return false;
1190 * Load user and user_group data from the database.
1191 * $this->mId must be set, this is how the user is identified.
1193 * @param integer $flags User::READ_* constant bitfield
1194 * @return bool True if the user exists, false if the user is anonymous
1196 public function loadFromDatabase( $flags = self::READ_LATEST ) {
1197 // Paranoia
1198 $this->mId = intval( $this->mId );
1200 // Anonymous user
1201 if ( !$this->mId ) {
1202 $this->loadDefaults();
1203 return false;
1206 $db = ( $flags & self::READ_LATEST )
1207 ? wfGetDB( DB_MASTER )
1208 : wfGetDB( DB_SLAVE );
1210 $s = $db->selectRow(
1211 'user',
1212 self::selectFields(),
1213 array( 'user_id' => $this->mId ),
1214 __METHOD__,
1215 ( ( $flags & self::READ_LOCKING ) == self::READ_LOCKING )
1216 ? array( 'LOCK IN SHARE MODE' )
1217 : array()
1220 $this->queryFlagsUsed = $flags;
1221 Hooks::run( 'UserLoadFromDatabase', array( $this, &$s ) );
1223 if ( $s !== false ) {
1224 // Initialise user table data
1225 $this->loadFromRow( $s );
1226 $this->mGroups = null; // deferred
1227 $this->getEditCount(); // revalidation for nulls
1228 return true;
1229 } else {
1230 // Invalid user_id
1231 $this->mId = 0;
1232 $this->loadDefaults();
1233 return false;
1238 * Initialize this object from a row from the user table.
1240 * @param stdClass $row Row from the user table to load.
1241 * @param array $data Further user data to load into the object
1243 * user_groups Array with groups out of the user_groups table
1244 * user_properties Array with properties out of the user_properties table
1246 protected function loadFromRow( $row, $data = null ) {
1247 $all = true;
1248 $passwordFactory = self::getPasswordFactory();
1250 $this->mGroups = null; // deferred
1252 if ( isset( $row->user_name ) ) {
1253 $this->mName = $row->user_name;
1254 $this->mFrom = 'name';
1255 $this->setItemLoaded( 'name' );
1256 } else {
1257 $all = false;
1260 if ( isset( $row->user_real_name ) ) {
1261 $this->mRealName = $row->user_real_name;
1262 $this->setItemLoaded( 'realname' );
1263 } else {
1264 $all = false;
1267 if ( isset( $row->user_id ) ) {
1268 $this->mId = intval( $row->user_id );
1269 $this->mFrom = 'id';
1270 $this->setItemLoaded( 'id' );
1271 } else {
1272 $all = false;
1275 if ( isset( $row->user_id ) && isset( $row->user_name ) ) {
1276 self::$idCacheByName[$row->user_name] = $row->user_id;
1279 if ( isset( $row->user_editcount ) ) {
1280 $this->mEditCount = $row->user_editcount;
1281 } else {
1282 $all = false;
1285 if ( isset( $row->user_password ) ) {
1286 // Check for *really* old password hashes that don't even have a type
1287 // The old hash format was just an md5 hex hash, with no type information
1288 if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password ) ) {
1289 $row->user_password = ":A:{$this->mId}:{$row->user_password}";
1292 try {
1293 $this->mPassword = $passwordFactory->newFromCiphertext( $row->user_password );
1294 } catch ( PasswordError $e ) {
1295 wfDebug( 'Invalid password hash found in database.' );
1296 $this->mPassword = $passwordFactory->newFromCiphertext( null );
1299 try {
1300 $this->mNewpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword );
1301 } catch ( PasswordError $e ) {
1302 wfDebug( 'Invalid password hash found in database.' );
1303 $this->mNewpassword = $passwordFactory->newFromCiphertext( null );
1306 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
1307 $this->mPasswordExpires = wfTimestampOrNull( TS_MW, $row->user_password_expires );
1310 if ( isset( $row->user_email ) ) {
1311 $this->mEmail = $row->user_email;
1312 $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1313 $this->mToken = $row->user_token;
1314 if ( $this->mToken == '' ) {
1315 $this->mToken = null;
1317 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1318 $this->mEmailToken = $row->user_email_token;
1319 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1320 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1321 } else {
1322 $all = false;
1325 if ( $all ) {
1326 $this->mLoadedItems = true;
1329 if ( is_array( $data ) ) {
1330 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1331 $this->mGroups = $data['user_groups'];
1333 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1334 $this->loadOptions( $data['user_properties'] );
1340 * Load the data for this user object from another user object.
1342 * @param User $user
1344 protected function loadFromUserObject( $user ) {
1345 $user->load();
1346 $user->loadGroups();
1347 $user->loadOptions();
1348 foreach ( self::$mCacheVars as $var ) {
1349 $this->$var = $user->$var;
1354 * Load the groups from the database if they aren't already loaded.
1356 private function loadGroups() {
1357 if ( is_null( $this->mGroups ) ) {
1358 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
1359 ? wfGetDB( DB_MASTER )
1360 : wfGetDB( DB_SLAVE );
1361 $res = $db->select( 'user_groups',
1362 array( 'ug_group' ),
1363 array( 'ug_user' => $this->mId ),
1364 __METHOD__ );
1365 $this->mGroups = array();
1366 foreach ( $res as $row ) {
1367 $this->mGroups[] = $row->ug_group;
1373 * Load the user's password hashes from the database
1375 * This is usually called in a scenario where the actual User object was
1376 * loaded from the cache, and then password comparison needs to be performed.
1377 * Password hashes are not stored in memcached.
1379 * @since 1.24
1381 private function loadPasswords() {
1382 if ( $this->getId() !== 0 &&
1383 ( $this->mPassword === null || $this->mNewpassword === null )
1385 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
1386 ? wfGetDB( DB_MASTER )
1387 : wfGetDB( DB_SLAVE );
1389 $this->loadFromRow( $db->selectRow(
1390 'user',
1391 array( 'user_password', 'user_newpassword',
1392 'user_newpass_time', 'user_password_expires' ),
1393 array( 'user_id' => $this->getId() ),
1394 __METHOD__
1395 ) );
1400 * Add the user to the group if he/she meets given criteria.
1402 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1403 * possible to remove manually via Special:UserRights. In such case it
1404 * will not be re-added automatically. The user will also not lose the
1405 * group if they no longer meet the criteria.
1407 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1409 * @return array Array of groups the user has been promoted to.
1411 * @see $wgAutopromoteOnce
1413 public function addAutopromoteOnceGroups( $event ) {
1414 global $wgAutopromoteOnceLogInRC, $wgAuth;
1416 if ( wfReadOnly() || !$this->getId() ) {
1417 return array();
1420 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1421 if ( !count( $toPromote ) ) {
1422 return array();
1425 if ( !$this->checkAndSetTouched() ) {
1426 return array(); // raced out (bug T48834)
1429 $oldGroups = $this->getGroups(); // previous groups
1430 foreach ( $toPromote as $group ) {
1431 $this->addGroup( $group );
1433 // update groups in external authentication database
1434 Hooks::run( 'UserGroupsChanged', array( $this, $toPromote, array(), false ) );
1435 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1437 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1439 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1440 $logEntry->setPerformer( $this );
1441 $logEntry->setTarget( $this->getUserPage() );
1442 $logEntry->setParameters( array(
1443 '4::oldgroups' => $oldGroups,
1444 '5::newgroups' => $newGroups,
1445 ) );
1446 $logid = $logEntry->insert();
1447 if ( $wgAutopromoteOnceLogInRC ) {
1448 $logEntry->publish( $logid );
1451 return $toPromote;
1455 * Bump user_touched if it didn't change since this object was loaded
1457 * On success, the mTouched field is updated.
1458 * The user serialization cache is always cleared.
1460 * @return bool Whether user_touched was actually updated
1461 * @since 1.26
1463 protected function checkAndSetTouched() {
1464 $this->load();
1466 if ( !$this->mId ) {
1467 return false; // anon
1470 // Get a new user_touched that is higher than the old one
1471 $oldTouched = $this->mTouched;
1472 $newTouched = $this->newTouchedTimestamp();
1474 $dbw = wfGetDB( DB_MASTER );
1475 $dbw->update( 'user',
1476 array( 'user_touched' => $dbw->timestamp( $newTouched ) ),
1477 array(
1478 'user_id' => $this->mId,
1479 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
1481 __METHOD__
1483 $success = ( $dbw->affectedRows() > 0 );
1485 if ( $success ) {
1486 $this->mTouched = $newTouched;
1489 // Clears on failure too since that is desired if the cache is stale
1490 $this->clearSharedCache();
1492 return $success;
1496 * Clear various cached data stored in this object. The cache of the user table
1497 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1499 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1500 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1502 public function clearInstanceCache( $reloadFrom = false ) {
1503 $this->mNewtalk = -1;
1504 $this->mDatePreference = null;
1505 $this->mBlockedby = -1; # Unset
1506 $this->mHash = false;
1507 $this->mRights = null;
1508 $this->mEffectiveGroups = null;
1509 $this->mImplicitGroups = null;
1510 $this->mGroups = null;
1511 $this->mOptions = null;
1512 $this->mOptionsLoaded = false;
1513 $this->mEditCount = null;
1515 if ( $reloadFrom ) {
1516 $this->mLoadedItems = array();
1517 $this->mFrom = $reloadFrom;
1522 * Combine the language default options with any site-specific options
1523 * and add the default language variants.
1525 * @return array Array of String options
1527 public static function getDefaultOptions() {
1528 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1530 static $defOpt = null;
1531 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1532 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1533 // mid-request and see that change reflected in the return value of this function.
1534 // Which is insane and would never happen during normal MW operation
1535 return $defOpt;
1538 $defOpt = $wgDefaultUserOptions;
1539 // Default language setting
1540 $defOpt['language'] = $wgContLang->getCode();
1541 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
1542 $defOpt[$langCode == $wgContLang->getCode() ? 'variant' : "variant-$langCode"] = $langCode;
1544 foreach ( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1545 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1547 $defOpt['skin'] = Skin::normalizeKey( $wgDefaultSkin );
1549 Hooks::run( 'UserGetDefaultOptions', array( &$defOpt ) );
1551 return $defOpt;
1555 * Get a given default option value.
1557 * @param string $opt Name of option to retrieve
1558 * @return string Default option value
1560 public static function getDefaultOption( $opt ) {
1561 $defOpts = self::getDefaultOptions();
1562 if ( isset( $defOpts[$opt] ) ) {
1563 return $defOpts[$opt];
1564 } else {
1565 return null;
1570 * Get blocking information
1571 * @param bool $bFromSlave Whether to check the slave database first.
1572 * To improve performance, non-critical checks are done against slaves.
1573 * Check when actually saving should be done against master.
1575 private function getBlockedStatus( $bFromSlave = true ) {
1576 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1578 if ( -1 != $this->mBlockedby ) {
1579 return;
1582 wfDebug( __METHOD__ . ": checking...\n" );
1584 // Initialize data...
1585 // Otherwise something ends up stomping on $this->mBlockedby when
1586 // things get lazy-loaded later, causing false positive block hits
1587 // due to -1 !== 0. Probably session-related... Nothing should be
1588 // overwriting mBlockedby, surely?
1589 $this->load();
1591 # We only need to worry about passing the IP address to the Block generator if the
1592 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1593 # know which IP address they're actually coming from
1594 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->equals( $wgUser ) ) {
1595 $ip = $this->getRequest()->getIP();
1596 } else {
1597 $ip = null;
1600 // User/IP blocking
1601 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1603 // Proxy blocking
1604 if ( !$block instanceof Block && $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1605 && !in_array( $ip, $wgProxyWhitelist )
1607 // Local list
1608 if ( self::isLocallyBlockedProxy( $ip ) ) {
1609 $block = new Block;
1610 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1611 $block->mReason = wfMessage( 'proxyblockreason' )->text();
1612 $block->setTarget( $ip );
1613 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1614 $block = new Block;
1615 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1616 $block->mReason = wfMessage( 'sorbsreason' )->text();
1617 $block->setTarget( $ip );
1621 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1622 if ( !$block instanceof Block
1623 && $wgApplyIpBlocksToXff
1624 && $ip !== null
1625 && !$this->isAllowed( 'proxyunbannable' )
1626 && !in_array( $ip, $wgProxyWhitelist )
1628 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1629 $xff = array_map( 'trim', explode( ',', $xff ) );
1630 $xff = array_diff( $xff, array( $ip ) );
1631 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1632 $block = Block::chooseBlock( $xffblocks, $xff );
1633 if ( $block instanceof Block ) {
1634 # Mangle the reason to alert the user that the block
1635 # originated from matching the X-Forwarded-For header.
1636 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->text();
1640 if ( $block instanceof Block ) {
1641 wfDebug( __METHOD__ . ": Found block.\n" );
1642 $this->mBlock = $block;
1643 $this->mBlockedby = $block->getByName();
1644 $this->mBlockreason = $block->mReason;
1645 $this->mHideName = $block->mHideName;
1646 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1647 } else {
1648 $this->mBlockedby = '';
1649 $this->mHideName = 0;
1650 $this->mAllowUsertalk = false;
1653 // Extensions
1654 Hooks::run( 'GetBlockedStatus', array( &$this ) );
1659 * Whether the given IP is in a DNS blacklist.
1661 * @param string $ip IP to check
1662 * @param bool $checkWhitelist Whether to check the whitelist first
1663 * @return bool True if blacklisted.
1665 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1666 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1668 if ( !$wgEnableDnsBlacklist ) {
1669 return false;
1672 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1673 return false;
1676 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1680 * Whether the given IP is in a given DNS blacklist.
1682 * @param string $ip IP to check
1683 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1684 * @return bool True if blacklisted.
1686 public function inDnsBlacklist( $ip, $bases ) {
1688 $found = false;
1689 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1690 if ( IP::isIPv4( $ip ) ) {
1691 // Reverse IP, bug 21255
1692 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1694 foreach ( (array)$bases as $base ) {
1695 // Make hostname
1696 // If we have an access key, use that too (ProjectHoneypot, etc.)
1697 $basename = $base;
1698 if ( is_array( $base ) ) {
1699 if ( count( $base ) >= 2 ) {
1700 // Access key is 1, base URL is 0
1701 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1702 } else {
1703 $host = "$ipReversed.{$base[0]}";
1705 $basename = $base[0];
1706 } else {
1707 $host = "$ipReversed.$base";
1710 // Send query
1711 $ipList = gethostbynamel( $host );
1713 if ( $ipList ) {
1714 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1715 $found = true;
1716 break;
1717 } else {
1718 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1723 return $found;
1727 * Check if an IP address is in the local proxy list
1729 * @param string $ip
1731 * @return bool
1733 public static function isLocallyBlockedProxy( $ip ) {
1734 global $wgProxyList;
1736 if ( !$wgProxyList ) {
1737 return false;
1740 if ( !is_array( $wgProxyList ) ) {
1741 // Load from the specified file
1742 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1745 if ( !is_array( $wgProxyList ) ) {
1746 $ret = false;
1747 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1748 $ret = true;
1749 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1750 // Old-style flipped proxy list
1751 $ret = true;
1752 } else {
1753 $ret = false;
1755 return $ret;
1759 * Is this user subject to rate limiting?
1761 * @return bool True if rate limited
1763 public function isPingLimitable() {
1764 global $wgRateLimitsExcludedIPs;
1765 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1766 // No other good way currently to disable rate limits
1767 // for specific IPs. :P
1768 // But this is a crappy hack and should die.
1769 return false;
1771 return !$this->isAllowed( 'noratelimit' );
1775 * Primitive rate limits: enforce maximum actions per time period
1776 * to put a brake on flooding.
1778 * The method generates both a generic profiling point and a per action one
1779 * (suffix being "-$action".
1781 * @note When using a shared cache like memcached, IP-address
1782 * last-hit counters will be shared across wikis.
1784 * @param string $action Action to enforce; 'edit' if unspecified
1785 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1786 * @return bool True if a rate limiter was tripped
1788 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1789 // Call the 'PingLimiter' hook
1790 $result = false;
1791 if ( !Hooks::run( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1792 return $result;
1795 global $wgRateLimits;
1796 if ( !isset( $wgRateLimits[$action] ) ) {
1797 return false;
1800 // Some groups shouldn't trigger the ping limiter, ever
1801 if ( !$this->isPingLimitable() ) {
1802 return false;
1805 global $wgMemc;
1807 $limits = $wgRateLimits[$action];
1808 $keys = array();
1809 $id = $this->getId();
1810 $userLimit = false;
1812 if ( isset( $limits['anon'] ) && $id == 0 ) {
1813 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1816 if ( isset( $limits['user'] ) && $id != 0 ) {
1817 $userLimit = $limits['user'];
1819 if ( $this->isNewbie() ) {
1820 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1821 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1823 if ( isset( $limits['ip'] ) ) {
1824 $ip = $this->getRequest()->getIP();
1825 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1827 if ( isset( $limits['subnet'] ) ) {
1828 $ip = $this->getRequest()->getIP();
1829 $matches = array();
1830 $subnet = false;
1831 if ( IP::isIPv6( $ip ) ) {
1832 $parts = IP::parseRange( "$ip/64" );
1833 $subnet = $parts[0];
1834 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1835 // IPv4
1836 $subnet = $matches[1];
1838 if ( $subnet !== false ) {
1839 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1843 // Check for group-specific permissions
1844 // If more than one group applies, use the group with the highest limit
1845 foreach ( $this->getGroups() as $group ) {
1846 if ( isset( $limits[$group] ) ) {
1847 if ( $userLimit === false
1848 || $limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1850 $userLimit = $limits[$group];
1854 // Set the user limit key
1855 if ( $userLimit !== false ) {
1856 list( $max, $period ) = $userLimit;
1857 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
1858 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1861 $triggered = false;
1862 foreach ( $keys as $key => $limit ) {
1863 list( $max, $period ) = $limit;
1864 $summary = "(limit $max in {$period}s)";
1865 $count = $wgMemc->get( $key );
1866 // Already pinged?
1867 if ( $count ) {
1868 if ( $count >= $max ) {
1869 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1870 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1871 $triggered = true;
1872 } else {
1873 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1875 } else {
1876 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1877 if ( $incrBy > 0 ) {
1878 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1881 if ( $incrBy > 0 ) {
1882 $wgMemc->incr( $key, $incrBy );
1886 return $triggered;
1890 * Check if user is blocked
1892 * @param bool $bFromSlave Whether to check the slave database instead of
1893 * the master. Hacked from false due to horrible probs on site.
1894 * @return bool True if blocked, false otherwise
1896 public function isBlocked( $bFromSlave = true ) {
1897 return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
1901 * Get the block affecting the user, or null if the user is not blocked
1903 * @param bool $bFromSlave Whether to check the slave database instead of the master
1904 * @return Block|null
1906 public function getBlock( $bFromSlave = true ) {
1907 $this->getBlockedStatus( $bFromSlave );
1908 return $this->mBlock instanceof Block ? $this->mBlock : null;
1912 * Check if user is blocked from editing a particular article
1914 * @param Title $title Title to check
1915 * @param bool $bFromSlave Whether to check the slave database instead of the master
1916 * @return bool
1918 public function isBlockedFrom( $title, $bFromSlave = false ) {
1919 global $wgBlockAllowsUTEdit;
1921 $blocked = $this->isBlocked( $bFromSlave );
1922 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1923 // If a user's name is suppressed, they cannot make edits anywhere
1924 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName()
1925 && $title->getNamespace() == NS_USER_TALK ) {
1926 $blocked = false;
1927 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1930 Hooks::run( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1932 return $blocked;
1936 * If user is blocked, return the name of the user who placed the block
1937 * @return string Name of blocker
1939 public function blockedBy() {
1940 $this->getBlockedStatus();
1941 return $this->mBlockedby;
1945 * If user is blocked, return the specified reason for the block
1946 * @return string Blocking reason
1948 public function blockedFor() {
1949 $this->getBlockedStatus();
1950 return $this->mBlockreason;
1954 * If user is blocked, return the ID for the block
1955 * @return int Block ID
1957 public function getBlockId() {
1958 $this->getBlockedStatus();
1959 return ( $this->mBlock ? $this->mBlock->getId() : false );
1963 * Check if user is blocked on all wikis.
1964 * Do not use for actual edit permission checks!
1965 * This is intended for quick UI checks.
1967 * @param string $ip IP address, uses current client if none given
1968 * @return bool True if blocked, false otherwise
1970 public function isBlockedGlobally( $ip = '' ) {
1971 if ( $this->mBlockedGlobally !== null ) {
1972 return $this->mBlockedGlobally;
1974 // User is already an IP?
1975 if ( IP::isIPAddress( $this->getName() ) ) {
1976 $ip = $this->getName();
1977 } elseif ( !$ip ) {
1978 $ip = $this->getRequest()->getIP();
1980 $blocked = false;
1981 Hooks::run( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1982 $this->mBlockedGlobally = (bool)$blocked;
1983 return $this->mBlockedGlobally;
1987 * Check if user account is locked
1989 * @return bool True if locked, false otherwise
1991 public function isLocked() {
1992 if ( $this->mLocked !== null ) {
1993 return $this->mLocked;
1995 global $wgAuth;
1996 $authUser = $wgAuth->getUserInstance( $this );
1997 $this->mLocked = (bool)$authUser->isLocked();
1998 Hooks::run( 'UserIsLocked', array( $this, &$this->mLocked ) );
1999 return $this->mLocked;
2003 * Check if user account is hidden
2005 * @return bool True if hidden, false otherwise
2007 public function isHidden() {
2008 if ( $this->mHideName !== null ) {
2009 return $this->mHideName;
2011 $this->getBlockedStatus();
2012 if ( !$this->mHideName ) {
2013 global $wgAuth;
2014 $authUser = $wgAuth->getUserInstance( $this );
2015 $this->mHideName = (bool)$authUser->isHidden();
2016 Hooks::run( 'UserIsHidden', array( $this, &$this->mHideName ) );
2018 return $this->mHideName;
2022 * Get the user's ID.
2023 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2025 public function getId() {
2026 if ( $this->mId === null && $this->mName !== null && User::isIP( $this->mName ) ) {
2027 // Special case, we know the user is anonymous
2028 return 0;
2029 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2030 // Don't load if this was initialized from an ID
2031 $this->load();
2033 return $this->mId;
2037 * Set the user and reload all fields according to a given ID
2038 * @param int $v User ID to reload
2040 public function setId( $v ) {
2041 $this->mId = $v;
2042 $this->clearInstanceCache( 'id' );
2046 * Get the user name, or the IP of an anonymous user
2047 * @return string User's name or IP address
2049 public function getName() {
2050 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2051 // Special case optimisation
2052 return $this->mName;
2053 } else {
2054 $this->load();
2055 if ( $this->mName === false ) {
2056 // Clean up IPs
2057 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
2059 return $this->mName;
2064 * Set the user name.
2066 * This does not reload fields from the database according to the given
2067 * name. Rather, it is used to create a temporary "nonexistent user" for
2068 * later addition to the database. It can also be used to set the IP
2069 * address for an anonymous user to something other than the current
2070 * remote IP.
2072 * @note User::newFromName() has roughly the same function, when the named user
2073 * does not exist.
2074 * @param string $str New user name to set
2076 public function setName( $str ) {
2077 $this->load();
2078 $this->mName = $str;
2082 * Get the user's name escaped by underscores.
2083 * @return string Username escaped by underscores.
2085 public function getTitleKey() {
2086 return str_replace( ' ', '_', $this->getName() );
2090 * Check if the user has new messages.
2091 * @return bool True if the user has new messages
2093 public function getNewtalk() {
2094 $this->load();
2096 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2097 if ( $this->mNewtalk === -1 ) {
2098 $this->mNewtalk = false; # reset talk page status
2100 // Check memcached separately for anons, who have no
2101 // entire User object stored in there.
2102 if ( !$this->mId ) {
2103 global $wgDisableAnonTalk;
2104 if ( $wgDisableAnonTalk ) {
2105 // Anon newtalk disabled by configuration.
2106 $this->mNewtalk = false;
2107 } else {
2108 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName() );
2110 } else {
2111 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
2115 return (bool)$this->mNewtalk;
2119 * Return the data needed to construct links for new talk page message
2120 * alerts. If there are new messages, this will return an associative array
2121 * with the following data:
2122 * wiki: The database name of the wiki
2123 * link: Root-relative link to the user's talk page
2124 * rev: The last talk page revision that the user has seen or null. This
2125 * is useful for building diff links.
2126 * If there are no new messages, it returns an empty array.
2127 * @note This function was designed to accomodate multiple talk pages, but
2128 * currently only returns a single link and revision.
2129 * @return array
2131 public function getNewMessageLinks() {
2132 $talks = array();
2133 if ( !Hooks::run( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2134 return $talks;
2135 } elseif ( !$this->getNewtalk() ) {
2136 return array();
2138 $utp = $this->getTalkPage();
2139 $dbr = wfGetDB( DB_SLAVE );
2140 // Get the "last viewed rev" timestamp from the oldest message notification
2141 $timestamp = $dbr->selectField( 'user_newtalk',
2142 'MIN(user_last_timestamp)',
2143 $this->isAnon() ? array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2144 __METHOD__ );
2145 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2146 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2150 * Get the revision ID for the last talk page revision viewed by the talk
2151 * page owner.
2152 * @return int|null Revision ID or null
2154 public function getNewMessageRevisionId() {
2155 $newMessageRevisionId = null;
2156 $newMessageLinks = $this->getNewMessageLinks();
2157 if ( $newMessageLinks ) {
2158 // Note: getNewMessageLinks() never returns more than a single link
2159 // and it is always for the same wiki, but we double-check here in
2160 // case that changes some time in the future.
2161 if ( count( $newMessageLinks ) === 1
2162 && $newMessageLinks[0]['wiki'] === wfWikiID()
2163 && $newMessageLinks[0]['rev']
2165 /** @var Revision $newMessageRevision */
2166 $newMessageRevision = $newMessageLinks[0]['rev'];
2167 $newMessageRevisionId = $newMessageRevision->getId();
2170 return $newMessageRevisionId;
2174 * Internal uncached check for new messages
2176 * @see getNewtalk()
2177 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2178 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2179 * @return bool True if the user has new messages
2181 protected function checkNewtalk( $field, $id ) {
2182 $dbr = wfGetDB( DB_SLAVE );
2184 $ok = $dbr->selectField( 'user_newtalk', $field, array( $field => $id ), __METHOD__ );
2186 return $ok !== false;
2190 * Add or update the new messages flag
2191 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2192 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2193 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2194 * @return bool True if successful, false otherwise
2196 protected function updateNewtalk( $field, $id, $curRev = null ) {
2197 // Get timestamp of the talk page revision prior to the current one
2198 $prevRev = $curRev ? $curRev->getPrevious() : false;
2199 $ts = $prevRev ? $prevRev->getTimestamp() : null;
2200 // Mark the user as having new messages since this revision
2201 $dbw = wfGetDB( DB_MASTER );
2202 $dbw->insert( 'user_newtalk',
2203 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2204 __METHOD__,
2205 'IGNORE' );
2206 if ( $dbw->affectedRows() ) {
2207 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
2208 return true;
2209 } else {
2210 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
2211 return false;
2216 * Clear the new messages flag for the given user
2217 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2218 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2219 * @return bool True if successful, false otherwise
2221 protected function deleteNewtalk( $field, $id ) {
2222 $dbw = wfGetDB( DB_MASTER );
2223 $dbw->delete( 'user_newtalk',
2224 array( $field => $id ),
2225 __METHOD__ );
2226 if ( $dbw->affectedRows() ) {
2227 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
2228 return true;
2229 } else {
2230 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
2231 return false;
2236 * Update the 'You have new messages!' status.
2237 * @param bool $val Whether the user has new messages
2238 * @param Revision $curRev New, as yet unseen revision of the user talk
2239 * page. Ignored if null or !$val.
2241 public function setNewtalk( $val, $curRev = null ) {
2242 if ( wfReadOnly() ) {
2243 return;
2246 $this->load();
2247 $this->mNewtalk = $val;
2249 if ( $this->isAnon() ) {
2250 $field = 'user_ip';
2251 $id = $this->getName();
2252 } else {
2253 $field = 'user_id';
2254 $id = $this->getId();
2257 if ( $val ) {
2258 $changed = $this->updateNewtalk( $field, $id, $curRev );
2259 } else {
2260 $changed = $this->deleteNewtalk( $field, $id );
2263 if ( $changed ) {
2264 $this->invalidateCache();
2269 * Generate a current or new-future timestamp to be stored in the
2270 * user_touched field when we update things.
2271 * @return string Timestamp in TS_MW format
2273 private function newTouchedTimestamp() {
2274 global $wgClockSkewFudge;
2276 $time = wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
2277 if ( $this->mTouched && $time <= $this->mTouched ) {
2278 $time = wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $this->mTouched ) + 1 );
2281 return $time;
2285 * Clear user data from memcached.
2286 * Use after applying fun updates to the database; caller's
2287 * responsibility to update user_touched if appropriate.
2289 * Called implicitly from invalidateCache() and saveSettings().
2291 public function clearSharedCache() {
2292 $id = $this->getId();
2293 if ( $id ) {
2294 $key = wfMemcKey( 'user', 'id', $id );
2295 ObjectCache::getMainWANInstance()->delete( $key );
2300 * Immediately touch the user data cache for this account
2302 * Calls touch() and removes account data from memcached
2304 public function invalidateCache() {
2305 $this->touch();
2306 $this->clearSharedCache();
2310 * Update the "touched" timestamp for the user
2312 * This is useful on various login/logout events when making sure that
2313 * a browser or proxy that has multiple tenants does not suffer cache
2314 * pollution where the new user sees the old users content. The value
2315 * of getTouched() is checked when determining 304 vs 200 responses.
2316 * Unlike invalidateCache(), this preserves the User object cache and
2317 * avoids database writes.
2319 * @since 1.25
2321 public function touch() {
2322 $id = $this->getId();
2323 if ( $id ) {
2324 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2325 ObjectCache::getMainWANInstance()->touchCheckKey( $key );
2326 $this->mQuickTouched = null;
2331 * Validate the cache for this account.
2332 * @param string $timestamp A timestamp in TS_MW format
2333 * @return bool
2335 public function validateCache( $timestamp ) {
2336 return ( $timestamp >= $this->getTouched() );
2340 * Get the user touched timestamp
2342 * Use this value only to validate caches via inequalities
2343 * such as in the case of HTTP If-Modified-Since response logic
2345 * @return string TS_MW Timestamp
2347 public function getTouched() {
2348 $this->load();
2350 if ( $this->mId ) {
2351 if ( $this->mQuickTouched === null ) {
2352 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId );
2353 $cache = ObjectCache::getMainWANInstance();
2355 $this->mQuickTouched = wfTimestamp( TS_MW, $cache->getCheckKeyTime( $key ) );
2358 return max( $this->mTouched, $this->mQuickTouched );
2361 return $this->mTouched;
2365 * Get the user_touched timestamp field (time of last DB updates)
2366 * @return string TS_MW Timestamp
2367 * @since 1.26
2369 public function getDBTouched() {
2370 $this->load();
2372 return $this->mTouched;
2376 * @return Password
2377 * @since 1.24
2379 public function getPassword() {
2380 $this->loadPasswords();
2382 return $this->mPassword;
2386 * @return Password
2387 * @since 1.24
2389 public function getTemporaryPassword() {
2390 $this->loadPasswords();
2392 return $this->mNewpassword;
2396 * Set the password and reset the random token.
2397 * Calls through to authentication plugin if necessary;
2398 * will have no effect if the auth plugin refuses to
2399 * pass the change through or if the legal password
2400 * checks fail.
2402 * As a special case, setting the password to null
2403 * wipes it, so the account cannot be logged in until
2404 * a new password is set, for instance via e-mail.
2406 * @param string $str New password to set
2407 * @throws PasswordError On failure
2409 * @return bool
2411 public function setPassword( $str ) {
2412 global $wgAuth;
2414 $this->loadPasswords();
2416 if ( $str !== null ) {
2417 if ( !$wgAuth->allowPasswordChange() ) {
2418 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2421 $status = $this->checkPasswordValidity( $str );
2422 if ( !$status->isGood() ) {
2423 throw new PasswordError( $status->getMessage()->text() );
2427 if ( !$wgAuth->setPassword( $this, $str ) ) {
2428 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2431 $this->setInternalPassword( $str );
2433 return true;
2437 * Set the password and reset the random token unconditionally.
2439 * @param string|null $str New password to set or null to set an invalid
2440 * password hash meaning that the user will not be able to log in
2441 * through the web interface.
2443 public function setInternalPassword( $str ) {
2444 $this->setToken();
2445 $this->setOption( 'watchlisttoken', false );
2447 $passwordFactory = self::getPasswordFactory();
2448 $this->mPassword = $passwordFactory->newFromPlaintext( $str );
2450 $this->mNewpassword = $passwordFactory->newFromCiphertext( null );
2451 $this->mNewpassTime = null;
2455 * Get the user's current token.
2456 * @param bool $forceCreation Force the generation of a new token if the
2457 * user doesn't have one (default=true for backwards compatibility).
2458 * @return string Token
2460 public function getToken( $forceCreation = true ) {
2461 $this->load();
2462 if ( !$this->mToken && $forceCreation ) {
2463 $this->setToken();
2465 return $this->mToken;
2469 * Set the random token (used for persistent authentication)
2470 * Called from loadDefaults() among other places.
2472 * @param string|bool $token If specified, set the token to this value
2474 public function setToken( $token = false ) {
2475 $this->load();
2476 if ( !$token ) {
2477 $this->mToken = MWCryptRand::generateHex( self::TOKEN_LENGTH );
2478 } else {
2479 $this->mToken = $token;
2484 * Set the password for a password reminder or new account email
2486 * @param string $str New password to set or null to set an invalid
2487 * password hash meaning that the user will not be able to use it
2488 * @param bool $throttle If true, reset the throttle timestamp to the present
2490 public function setNewpassword( $str, $throttle = true ) {
2491 $this->loadPasswords();
2493 $this->mNewpassword = self::getPasswordFactory()->newFromPlaintext( $str );
2494 if ( $str === null ) {
2495 $this->mNewpassTime = null;
2496 } elseif ( $throttle ) {
2497 $this->mNewpassTime = wfTimestampNow();
2502 * Has password reminder email been sent within the last
2503 * $wgPasswordReminderResendTime hours?
2504 * @return bool
2506 public function isPasswordReminderThrottled() {
2507 global $wgPasswordReminderResendTime;
2508 $this->load();
2509 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
2510 return false;
2512 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
2513 return time() < $expiry;
2517 * Get the user's e-mail address
2518 * @return string User's email address
2520 public function getEmail() {
2521 $this->load();
2522 Hooks::run( 'UserGetEmail', array( $this, &$this->mEmail ) );
2523 return $this->mEmail;
2527 * Get the timestamp of the user's e-mail authentication
2528 * @return string TS_MW timestamp
2530 public function getEmailAuthenticationTimestamp() {
2531 $this->load();
2532 Hooks::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2533 return $this->mEmailAuthenticated;
2537 * Set the user's e-mail address
2538 * @param string $str New e-mail address
2540 public function setEmail( $str ) {
2541 $this->load();
2542 if ( $str == $this->mEmail ) {
2543 return;
2545 $this->invalidateEmail();
2546 $this->mEmail = $str;
2547 Hooks::run( 'UserSetEmail', array( $this, &$this->mEmail ) );
2551 * Set the user's e-mail address and a confirmation mail if needed.
2553 * @since 1.20
2554 * @param string $str New e-mail address
2555 * @return Status
2557 public function setEmailWithConfirmation( $str ) {
2558 global $wgEnableEmail, $wgEmailAuthentication;
2560 if ( !$wgEnableEmail ) {
2561 return Status::newFatal( 'emaildisabled' );
2564 $oldaddr = $this->getEmail();
2565 if ( $str === $oldaddr ) {
2566 return Status::newGood( true );
2569 $this->setEmail( $str );
2571 if ( $str !== '' && $wgEmailAuthentication ) {
2572 // Send a confirmation request to the new address if needed
2573 $type = $oldaddr != '' ? 'changed' : 'set';
2574 $result = $this->sendConfirmationMail( $type );
2575 if ( $result->isGood() ) {
2576 // Say to the caller that a confirmation mail has been sent
2577 $result->value = 'eauth';
2579 } else {
2580 $result = Status::newGood( true );
2583 return $result;
2587 * Get the user's real name
2588 * @return string User's real name
2590 public function getRealName() {
2591 if ( !$this->isItemLoaded( 'realname' ) ) {
2592 $this->load();
2595 return $this->mRealName;
2599 * Set the user's real name
2600 * @param string $str New real name
2602 public function setRealName( $str ) {
2603 $this->load();
2604 $this->mRealName = $str;
2608 * Get the user's current setting for a given option.
2610 * @param string $oname The option to check
2611 * @param string $defaultOverride A default value returned if the option does not exist
2612 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2613 * @return string User's current value for the option
2614 * @see getBoolOption()
2615 * @see getIntOption()
2617 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2618 global $wgHiddenPrefs;
2619 $this->loadOptions();
2621 # We want 'disabled' preferences to always behave as the default value for
2622 # users, even if they have set the option explicitly in their settings (ie they
2623 # set it, and then it was disabled removing their ability to change it). But
2624 # we don't want to erase the preferences in the database in case the preference
2625 # is re-enabled again. So don't touch $mOptions, just override the returned value
2626 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2627 return self::getDefaultOption( $oname );
2630 if ( array_key_exists( $oname, $this->mOptions ) ) {
2631 return $this->mOptions[$oname];
2632 } else {
2633 return $defaultOverride;
2638 * Get all user's options
2640 * @param int $flags Bitwise combination of:
2641 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2642 * to the default value. (Since 1.25)
2643 * @return array
2645 public function getOptions( $flags = 0 ) {
2646 global $wgHiddenPrefs;
2647 $this->loadOptions();
2648 $options = $this->mOptions;
2650 # We want 'disabled' preferences to always behave as the default value for
2651 # users, even if they have set the option explicitly in their settings (ie they
2652 # set it, and then it was disabled removing their ability to change it). But
2653 # we don't want to erase the preferences in the database in case the preference
2654 # is re-enabled again. So don't touch $mOptions, just override the returned value
2655 foreach ( $wgHiddenPrefs as $pref ) {
2656 $default = self::getDefaultOption( $pref );
2657 if ( $default !== null ) {
2658 $options[$pref] = $default;
2662 if ( $flags & self::GETOPTIONS_EXCLUDE_DEFAULTS ) {
2663 $options = array_diff_assoc( $options, self::getDefaultOptions() );
2666 return $options;
2670 * Get the user's current setting for a given option, as a boolean value.
2672 * @param string $oname The option to check
2673 * @return bool User's current value for the option
2674 * @see getOption()
2676 public function getBoolOption( $oname ) {
2677 return (bool)$this->getOption( $oname );
2681 * Get the user's current setting for a given option, as an integer value.
2683 * @param string $oname The option to check
2684 * @param int $defaultOverride A default value returned if the option does not exist
2685 * @return int User's current value for the option
2686 * @see getOption()
2688 public function getIntOption( $oname, $defaultOverride = 0 ) {
2689 $val = $this->getOption( $oname );
2690 if ( $val == '' ) {
2691 $val = $defaultOverride;
2693 return intval( $val );
2697 * Set the given option for a user.
2699 * You need to call saveSettings() to actually write to the database.
2701 * @param string $oname The option to set
2702 * @param mixed $val New value to set
2704 public function setOption( $oname, $val ) {
2705 $this->loadOptions();
2707 // Explicitly NULL values should refer to defaults
2708 if ( is_null( $val ) ) {
2709 $val = self::getDefaultOption( $oname );
2712 $this->mOptions[$oname] = $val;
2716 * Get a token stored in the preferences (like the watchlist one),
2717 * resetting it if it's empty (and saving changes).
2719 * @param string $oname The option name to retrieve the token from
2720 * @return string|bool User's current value for the option, or false if this option is disabled.
2721 * @see resetTokenFromOption()
2722 * @see getOption()
2723 * @deprecated 1.26 Applications should use the OAuth extension
2725 public function getTokenFromOption( $oname ) {
2726 global $wgHiddenPrefs;
2728 $id = $this->getId();
2729 if ( !$id || in_array( $oname, $wgHiddenPrefs ) ) {
2730 return false;
2733 $token = $this->getOption( $oname );
2734 if ( !$token ) {
2735 // Default to a value based on the user token to avoid space
2736 // wasted on storing tokens for all users. When this option
2737 // is set manually by the user, only then is it stored.
2738 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2741 return $token;
2745 * Reset a token stored in the preferences (like the watchlist one).
2746 * *Does not* save user's preferences (similarly to setOption()).
2748 * @param string $oname The option name to reset the token in
2749 * @return string|bool New token value, or false if this option is disabled.
2750 * @see getTokenFromOption()
2751 * @see setOption()
2753 public function resetTokenFromOption( $oname ) {
2754 global $wgHiddenPrefs;
2755 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2756 return false;
2759 $token = MWCryptRand::generateHex( 40 );
2760 $this->setOption( $oname, $token );
2761 return $token;
2765 * Return a list of the types of user options currently returned by
2766 * User::getOptionKinds().
2768 * Currently, the option kinds are:
2769 * - 'registered' - preferences which are registered in core MediaWiki or
2770 * by extensions using the UserGetDefaultOptions hook.
2771 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2772 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2773 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2774 * be used by user scripts.
2775 * - 'special' - "preferences" that are not accessible via User::getOptions
2776 * or User::setOptions.
2777 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2778 * These are usually legacy options, removed in newer versions.
2780 * The API (and possibly others) use this function to determine the possible
2781 * option types for validation purposes, so make sure to update this when a
2782 * new option kind is added.
2784 * @see User::getOptionKinds
2785 * @return array Option kinds
2787 public static function listOptionKinds() {
2788 return array(
2789 'registered',
2790 'registered-multiselect',
2791 'registered-checkmatrix',
2792 'userjs',
2793 'special',
2794 'unused'
2799 * Return an associative array mapping preferences keys to the kind of a preference they're
2800 * used for. Different kinds are handled differently when setting or reading preferences.
2802 * See User::listOptionKinds for the list of valid option types that can be provided.
2804 * @see User::listOptionKinds
2805 * @param IContextSource $context
2806 * @param array $options Assoc. array with options keys to check as keys.
2807 * Defaults to $this->mOptions.
2808 * @return array The key => kind mapping data
2810 public function getOptionKinds( IContextSource $context, $options = null ) {
2811 $this->loadOptions();
2812 if ( $options === null ) {
2813 $options = $this->mOptions;
2816 $prefs = Preferences::getPreferences( $this, $context );
2817 $mapping = array();
2819 // Pull out the "special" options, so they don't get converted as
2820 // multiselect or checkmatrix.
2821 $specialOptions = array_fill_keys( Preferences::getSaveBlacklist(), true );
2822 foreach ( $specialOptions as $name => $value ) {
2823 unset( $prefs[$name] );
2826 // Multiselect and checkmatrix options are stored in the database with
2827 // one key per option, each having a boolean value. Extract those keys.
2828 $multiselectOptions = array();
2829 foreach ( $prefs as $name => $info ) {
2830 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2831 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2832 $opts = HTMLFormField::flattenOptions( $info['options'] );
2833 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2835 foreach ( $opts as $value ) {
2836 $multiselectOptions["$prefix$value"] = true;
2839 unset( $prefs[$name] );
2842 $checkmatrixOptions = array();
2843 foreach ( $prefs as $name => $info ) {
2844 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2845 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2846 $columns = HTMLFormField::flattenOptions( $info['columns'] );
2847 $rows = HTMLFormField::flattenOptions( $info['rows'] );
2848 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2850 foreach ( $columns as $column ) {
2851 foreach ( $rows as $row ) {
2852 $checkmatrixOptions["$prefix$column-$row"] = true;
2856 unset( $prefs[$name] );
2860 // $value is ignored
2861 foreach ( $options as $key => $value ) {
2862 if ( isset( $prefs[$key] ) ) {
2863 $mapping[$key] = 'registered';
2864 } elseif ( isset( $multiselectOptions[$key] ) ) {
2865 $mapping[$key] = 'registered-multiselect';
2866 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2867 $mapping[$key] = 'registered-checkmatrix';
2868 } elseif ( isset( $specialOptions[$key] ) ) {
2869 $mapping[$key] = 'special';
2870 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2871 $mapping[$key] = 'userjs';
2872 } else {
2873 $mapping[$key] = 'unused';
2877 return $mapping;
2881 * Reset certain (or all) options to the site defaults
2883 * The optional parameter determines which kinds of preferences will be reset.
2884 * Supported values are everything that can be reported by getOptionKinds()
2885 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2887 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2888 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2889 * for backwards-compatibility.
2890 * @param IContextSource|null $context Context source used when $resetKinds
2891 * does not contain 'all', passed to getOptionKinds().
2892 * Defaults to RequestContext::getMain() when null.
2894 public function resetOptions(
2895 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2896 IContextSource $context = null
2898 $this->load();
2899 $defaultOptions = self::getDefaultOptions();
2901 if ( !is_array( $resetKinds ) ) {
2902 $resetKinds = array( $resetKinds );
2905 if ( in_array( 'all', $resetKinds ) ) {
2906 $newOptions = $defaultOptions;
2907 } else {
2908 if ( $context === null ) {
2909 $context = RequestContext::getMain();
2912 $optionKinds = $this->getOptionKinds( $context );
2913 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
2914 $newOptions = array();
2916 // Use default values for the options that should be deleted, and
2917 // copy old values for the ones that shouldn't.
2918 foreach ( $this->mOptions as $key => $value ) {
2919 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2920 if ( array_key_exists( $key, $defaultOptions ) ) {
2921 $newOptions[$key] = $defaultOptions[$key];
2923 } else {
2924 $newOptions[$key] = $value;
2929 Hooks::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions, $resetKinds ) );
2931 $this->mOptions = $newOptions;
2932 $this->mOptionsLoaded = true;
2936 * Get the user's preferred date format.
2937 * @return string User's preferred date format
2939 public function getDatePreference() {
2940 // Important migration for old data rows
2941 if ( is_null( $this->mDatePreference ) ) {
2942 global $wgLang;
2943 $value = $this->getOption( 'date' );
2944 $map = $wgLang->getDatePreferenceMigrationMap();
2945 if ( isset( $map[$value] ) ) {
2946 $value = $map[$value];
2948 $this->mDatePreference = $value;
2950 return $this->mDatePreference;
2954 * Determine based on the wiki configuration and the user's options,
2955 * whether this user must be over HTTPS no matter what.
2957 * @return bool
2959 public function requiresHTTPS() {
2960 global $wgSecureLogin;
2961 if ( !$wgSecureLogin ) {
2962 return false;
2963 } else {
2964 $https = $this->getBoolOption( 'prefershttps' );
2965 Hooks::run( 'UserRequiresHTTPS', array( $this, &$https ) );
2966 if ( $https ) {
2967 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2969 return $https;
2974 * Get the user preferred stub threshold
2976 * @return int
2978 public function getStubThreshold() {
2979 global $wgMaxArticleSize; # Maximum article size, in Kb
2980 $threshold = $this->getIntOption( 'stubthreshold' );
2981 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2982 // If they have set an impossible value, disable the preference
2983 // so we can use the parser cache again.
2984 $threshold = 0;
2986 return $threshold;
2990 * Get the permissions this user has.
2991 * @return array Array of String permission names
2993 public function getRights() {
2994 if ( is_null( $this->mRights ) ) {
2995 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2996 Hooks::run( 'UserGetRights', array( $this, &$this->mRights ) );
2997 // Force reindexation of rights when a hook has unset one of them
2998 $this->mRights = array_values( array_unique( $this->mRights ) );
3000 return $this->mRights;
3004 * Get the list of explicit group memberships this user has.
3005 * The implicit * and user groups are not included.
3006 * @return array Array of String internal group names
3008 public function getGroups() {
3009 $this->load();
3010 $this->loadGroups();
3011 return $this->mGroups;
3015 * Get the list of implicit group memberships this user has.
3016 * This includes all explicit groups, plus 'user' if logged in,
3017 * '*' for all accounts, and autopromoted groups
3018 * @param bool $recache Whether to avoid the cache
3019 * @return array Array of String internal group names
3021 public function getEffectiveGroups( $recache = false ) {
3022 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
3023 $this->mEffectiveGroups = array_unique( array_merge(
3024 $this->getGroups(), // explicit groups
3025 $this->getAutomaticGroups( $recache ) // implicit groups
3026 ) );
3027 // Hook for additional groups
3028 Hooks::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
3029 // Force reindexation of groups when a hook has unset one of them
3030 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
3032 return $this->mEffectiveGroups;
3036 * Get the list of implicit group memberships this user has.
3037 * This includes 'user' if logged in, '*' for all accounts,
3038 * and autopromoted groups
3039 * @param bool $recache Whether to avoid the cache
3040 * @return array Array of String internal group names
3042 public function getAutomaticGroups( $recache = false ) {
3043 if ( $recache || is_null( $this->mImplicitGroups ) ) {
3044 $this->mImplicitGroups = array( '*' );
3045 if ( $this->getId() ) {
3046 $this->mImplicitGroups[] = 'user';
3048 $this->mImplicitGroups = array_unique( array_merge(
3049 $this->mImplicitGroups,
3050 Autopromote::getAutopromoteGroups( $this )
3051 ) );
3053 if ( $recache ) {
3054 // Assure data consistency with rights/groups,
3055 // as getEffectiveGroups() depends on this function
3056 $this->mEffectiveGroups = null;
3059 return $this->mImplicitGroups;
3063 * Returns the groups the user has belonged to.
3065 * The user may still belong to the returned groups. Compare with getGroups().
3067 * The function will not return groups the user had belonged to before MW 1.17
3069 * @return array Names of the groups the user has belonged to.
3071 public function getFormerGroups() {
3072 $this->load();
3074 if ( is_null( $this->mFormerGroups ) ) {
3075 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
3076 ? wfGetDB( DB_MASTER )
3077 : wfGetDB( DB_SLAVE );
3078 $res = $db->select( 'user_former_groups',
3079 array( 'ufg_group' ),
3080 array( 'ufg_user' => $this->mId ),
3081 __METHOD__ );
3082 $this->mFormerGroups = array();
3083 foreach ( $res as $row ) {
3084 $this->mFormerGroups[] = $row->ufg_group;
3088 return $this->mFormerGroups;
3092 * Get the user's edit count.
3093 * @return int|null Null for anonymous users
3095 public function getEditCount() {
3096 if ( !$this->getId() ) {
3097 return null;
3100 if ( $this->mEditCount === null ) {
3101 /* Populate the count, if it has not been populated yet */
3102 $dbr = wfGetDB( DB_SLAVE );
3103 // check if the user_editcount field has been initialized
3104 $count = $dbr->selectField(
3105 'user', 'user_editcount',
3106 array( 'user_id' => $this->mId ),
3107 __METHOD__
3110 if ( $count === null ) {
3111 // it has not been initialized. do so.
3112 $count = $this->initEditCount();
3114 $this->mEditCount = $count;
3116 return (int)$this->mEditCount;
3120 * Add the user to the given group.
3121 * This takes immediate effect.
3122 * @param string $group Name of the group to add
3123 * @return bool
3125 public function addGroup( $group ) {
3126 $this->load();
3128 if ( !Hooks::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3129 return false;
3132 $dbw = wfGetDB( DB_MASTER );
3133 if ( $this->getId() ) {
3134 $dbw->insert( 'user_groups',
3135 array(
3136 'ug_user' => $this->getID(),
3137 'ug_group' => $group,
3139 __METHOD__,
3140 array( 'IGNORE' ) );
3143 $this->loadGroups();
3144 $this->mGroups[] = $group;
3145 // In case loadGroups was not called before, we now have the right twice.
3146 // Get rid of the duplicate.
3147 $this->mGroups = array_unique( $this->mGroups );
3149 // Refresh the groups caches, and clear the rights cache so it will be
3150 // refreshed on the next call to $this->getRights().
3151 $this->getEffectiveGroups( true );
3152 $this->mRights = null;
3154 $this->invalidateCache();
3156 return true;
3160 * Remove the user from the given group.
3161 * This takes immediate effect.
3162 * @param string $group Name of the group to remove
3163 * @return bool
3165 public function removeGroup( $group ) {
3166 $this->load();
3167 if ( !Hooks::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3168 return false;
3171 $dbw = wfGetDB( DB_MASTER );
3172 $dbw->delete( 'user_groups',
3173 array(
3174 'ug_user' => $this->getID(),
3175 'ug_group' => $group,
3176 ), __METHOD__
3178 // Remember that the user was in this group
3179 $dbw->insert( 'user_former_groups',
3180 array(
3181 'ufg_user' => $this->getID(),
3182 'ufg_group' => $group,
3184 __METHOD__,
3185 array( 'IGNORE' )
3188 $this->loadGroups();
3189 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
3191 // Refresh the groups caches, and clear the rights cache so it will be
3192 // refreshed on the next call to $this->getRights().
3193 $this->getEffectiveGroups( true );
3194 $this->mRights = null;
3196 $this->invalidateCache();
3198 return true;
3202 * Get whether the user is logged in
3203 * @return bool
3205 public function isLoggedIn() {
3206 return $this->getID() != 0;
3210 * Get whether the user is anonymous
3211 * @return bool
3213 public function isAnon() {
3214 return !$this->isLoggedIn();
3218 * Check if user is allowed to access a feature / make an action
3220 * @param string ... Permissions to test
3221 * @return bool True if user is allowed to perform *any* of the given actions
3223 public function isAllowedAny() {
3224 $permissions = func_get_args();
3225 foreach ( $permissions as $permission ) {
3226 if ( $this->isAllowed( $permission ) ) {
3227 return true;
3230 return false;
3235 * @param string ... Permissions to test
3236 * @return bool True if the user is allowed to perform *all* of the given actions
3238 public function isAllowedAll() {
3239 $permissions = func_get_args();
3240 foreach ( $permissions as $permission ) {
3241 if ( !$this->isAllowed( $permission ) ) {
3242 return false;
3245 return true;
3249 * Internal mechanics of testing a permission
3250 * @param string $action
3251 * @return bool
3253 public function isAllowed( $action = '' ) {
3254 if ( $action === '' ) {
3255 return true; // In the spirit of DWIM
3257 // Patrolling may not be enabled
3258 if ( $action === 'patrol' || $action === 'autopatrol' ) {
3259 global $wgUseRCPatrol, $wgUseNPPatrol;
3260 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3261 return false;
3264 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3265 // by misconfiguration: 0 == 'foo'
3266 return in_array( $action, $this->getRights(), true );
3270 * Check whether to enable recent changes patrol features for this user
3271 * @return bool True or false
3273 public function useRCPatrol() {
3274 global $wgUseRCPatrol;
3275 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3279 * Check whether to enable new pages patrol features for this user
3280 * @return bool True or false
3282 public function useNPPatrol() {
3283 global $wgUseRCPatrol, $wgUseNPPatrol;
3284 return (
3285 ( $wgUseRCPatrol || $wgUseNPPatrol )
3286 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3291 * Get the WebRequest object to use with this object
3293 * @return WebRequest
3295 public function getRequest() {
3296 if ( $this->mRequest ) {
3297 return $this->mRequest;
3298 } else {
3299 global $wgRequest;
3300 return $wgRequest;
3305 * Get the current skin, loading it if required
3306 * @return Skin The current skin
3307 * @todo FIXME: Need to check the old failback system [AV]
3308 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3310 public function getSkin() {
3311 wfDeprecated( __METHOD__, '1.18' );
3312 return RequestContext::getMain()->getSkin();
3316 * Get a WatchedItem for this user and $title.
3318 * @since 1.22 $checkRights parameter added
3319 * @param Title $title
3320 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3321 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3322 * @return WatchedItem
3324 public function getWatchedItem( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3325 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3327 if ( isset( $this->mWatchedItems[$key] ) ) {
3328 return $this->mWatchedItems[$key];
3331 if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
3332 $this->mWatchedItems = array();
3335 $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title, $checkRights );
3336 return $this->mWatchedItems[$key];
3340 * Check the watched status of an article.
3341 * @since 1.22 $checkRights parameter added
3342 * @param Title $title Title of the article to look at
3343 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3344 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3345 * @return bool
3347 public function isWatched( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3348 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3352 * Watch an article.
3353 * @since 1.22 $checkRights parameter added
3354 * @param Title $title Title of the article to look at
3355 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3356 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3358 public function addWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3359 $this->getWatchedItem( $title, $checkRights )->addWatch();
3360 $this->invalidateCache();
3364 * Stop watching an article.
3365 * @since 1.22 $checkRights parameter added
3366 * @param Title $title Title of the article to look at
3367 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3368 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3370 public function removeWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3371 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3372 $this->invalidateCache();
3376 * Clear the user's notification timestamp for the given title.
3377 * If e-notif e-mails are on, they will receive notification mails on
3378 * the next change of the page if it's watched etc.
3379 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3380 * @param Title $title Title of the article to look at
3381 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3383 public function clearNotification( &$title, $oldid = 0 ) {
3384 global $wgUseEnotif, $wgShowUpdatedMarker;
3386 // Do nothing if the database is locked to writes
3387 if ( wfReadOnly() ) {
3388 return;
3391 // Do nothing if not allowed to edit the watchlist
3392 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3393 return;
3396 // If we're working on user's talk page, we should update the talk page message indicator
3397 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3398 if ( !Hooks::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3399 return;
3402 $that = $this;
3403 // Try to update the DB post-send and only if needed...
3404 DeferredUpdates::addCallableUpdate( function() use ( $that, $title, $oldid ) {
3405 if ( !$that->getNewtalk() ) {
3406 return; // no notifications to clear
3409 // Delete the last notifications (they stack up)
3410 $that->setNewtalk( false );
3412 // If there is a new, unseen, revision, use its timestamp
3413 $nextid = $oldid
3414 ? $title->getNextRevisionID( $oldid, Title::GAID_FOR_UPDATE )
3415 : null;
3416 if ( $nextid ) {
3417 $that->setNewtalk( true, Revision::newFromId( $nextid ) );
3419 } );
3422 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3423 return;
3426 if ( $this->isAnon() ) {
3427 // Nothing else to do...
3428 return;
3431 // Only update the timestamp if the page is being watched.
3432 // The query to find out if it is watched is cached both in memcached and per-invocation,
3433 // and when it does have to be executed, it can be on a slave
3434 // If this is the user's newtalk page, we always update the timestamp
3435 $force = '';
3436 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3437 $force = 'force';
3440 $this->getWatchedItem( $title )->resetNotificationTimestamp(
3441 $force, $oldid, WatchedItem::DEFERRED
3446 * Resets all of the given user's page-change notification timestamps.
3447 * If e-notif e-mails are on, they will receive notification mails on
3448 * the next change of any watched page.
3449 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3451 public function clearAllNotifications() {
3452 if ( wfReadOnly() ) {
3453 return;
3456 // Do nothing if not allowed to edit the watchlist
3457 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3458 return;
3461 global $wgUseEnotif, $wgShowUpdatedMarker;
3462 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3463 $this->setNewtalk( false );
3464 return;
3466 $id = $this->getId();
3467 if ( $id != 0 ) {
3468 $dbw = wfGetDB( DB_MASTER );
3469 $dbw->update( 'watchlist',
3470 array( /* SET */ 'wl_notificationtimestamp' => null ),
3471 array( /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ),
3472 __METHOD__
3474 // We also need to clear here the "you have new message" notification for the own user_talk page;
3475 // it's cleared one page view later in WikiPage::doViewUpdates().
3480 * Set a cookie on the user's client. Wrapper for
3481 * WebResponse::setCookie
3482 * @param string $name Name of the cookie to set
3483 * @param string $value Value to set
3484 * @param int $exp Expiration time, as a UNIX time value;
3485 * if 0 or not specified, use the default $wgCookieExpiration
3486 * @param bool $secure
3487 * true: Force setting the secure attribute when setting the cookie
3488 * false: Force NOT setting the secure attribute when setting the cookie
3489 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3490 * @param array $params Array of options sent passed to WebResponse::setcookie()
3491 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3492 * is passed.
3494 protected function setCookie(
3495 $name, $value, $exp = 0, $secure = null, $params = array(), $request = null
3497 if ( $request === null ) {
3498 $request = $this->getRequest();
3500 $params['secure'] = $secure;
3501 $request->response()->setcookie( $name, $value, $exp, $params );
3505 * Clear a cookie on the user's client
3506 * @param string $name Name of the cookie to clear
3507 * @param bool $secure
3508 * true: Force setting the secure attribute when setting the cookie
3509 * false: Force NOT setting the secure attribute when setting the cookie
3510 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3511 * @param array $params Array of options sent passed to WebResponse::setcookie()
3513 protected function clearCookie( $name, $secure = null, $params = array() ) {
3514 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3518 * Set an extended login cookie on the user's client. The expiry of the cookie
3519 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3520 * variable.
3522 * @see User::setCookie
3524 * @param string $name Name of the cookie to set
3525 * @param string $value Value to set
3526 * @param bool $secure
3527 * true: Force setting the secure attribute when setting the cookie
3528 * false: Force NOT setting the secure attribute when setting the cookie
3529 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3531 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3532 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3534 $exp = time();
3535 $exp += $wgExtendedLoginCookieExpiration !== null
3536 ? $wgExtendedLoginCookieExpiration
3537 : $wgCookieExpiration;
3539 $this->setCookie( $name, $value, $exp, $secure );
3543 * Set the default cookies for this session on the user's client.
3545 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3546 * is passed.
3547 * @param bool $secure Whether to force secure/insecure cookies or use default
3548 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3550 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3551 global $wgExtendedLoginCookies;
3553 if ( $request === null ) {
3554 $request = $this->getRequest();
3557 $this->load();
3558 if ( 0 == $this->mId ) {
3559 return;
3561 if ( !$this->mToken ) {
3562 // When token is empty or NULL generate a new one and then save it to the database
3563 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3564 // Simply by setting every cell in the user_token column to NULL and letting them be
3565 // regenerated as users log back into the wiki.
3566 $this->setToken();
3567 if ( !wfReadOnly() ) {
3568 $this->saveSettings();
3571 $session = array(
3572 'wsUserID' => $this->mId,
3573 'wsToken' => $this->mToken,
3574 'wsUserName' => $this->getName()
3576 $cookies = array(
3577 'UserID' => $this->mId,
3578 'UserName' => $this->getName(),
3580 if ( $rememberMe ) {
3581 $cookies['Token'] = $this->mToken;
3582 } else {
3583 $cookies['Token'] = false;
3586 Hooks::run( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3588 foreach ( $session as $name => $value ) {
3589 $request->setSessionData( $name, $value );
3591 foreach ( $cookies as $name => $value ) {
3592 if ( $value === false ) {
3593 $this->clearCookie( $name );
3594 } elseif ( $rememberMe && in_array( $name, $wgExtendedLoginCookies ) ) {
3595 $this->setExtendedLoginCookie( $name, $value, $secure );
3596 } else {
3597 $this->setCookie( $name, $value, 0, $secure, array(), $request );
3602 * If wpStickHTTPS was selected, also set an insecure cookie that
3603 * will cause the site to redirect the user to HTTPS, if they access
3604 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3605 * as the one set by centralauth (bug 53538). Also set it to session, or
3606 * standard time setting, based on if rememberme was set.
3608 if ( $request->getCheck( 'wpStickHTTPS' ) || $this->requiresHTTPS() ) {
3609 $this->setCookie(
3610 'forceHTTPS',
3611 'true',
3612 $rememberMe ? 0 : null,
3613 false,
3614 array( 'prefix' => '' ) // no prefix
3620 * Log this user out.
3622 public function logout() {
3623 if ( Hooks::run( 'UserLogout', array( &$this ) ) ) {
3624 $this->doLogout();
3629 * Clear the user's cookies and session, and reset the instance cache.
3630 * @see logout()
3632 public function doLogout() {
3633 $this->clearInstanceCache( 'defaults' );
3635 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3637 $this->clearCookie( 'UserID' );
3638 $this->clearCookie( 'Token' );
3639 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3641 // Remember when user logged out, to prevent seeing cached pages
3642 $this->setCookie( 'LoggedOut', time(), time() + 86400 );
3646 * Save this user's settings into the database.
3647 * @todo Only rarely do all these fields need to be set!
3649 public function saveSettings() {
3650 global $wgAuth;
3652 if ( wfReadOnly() ) {
3653 // @TODO: caller should deal with this instead!
3654 // This should really just be an exception.
3655 MWExceptionHandler::logException( new DBExpectedError(
3656 null,
3657 "Could not update user with ID '{$this->mId}'; DB is read-only."
3658 ) );
3659 return;
3662 $this->load();
3663 $this->loadPasswords();
3664 if ( 0 == $this->mId ) {
3665 return; // anon
3668 // Get a new user_touched that is higher than the old one.
3669 // This will be used for a CAS check as a last-resort safety
3670 // check against race conditions and slave lag.
3671 $oldTouched = $this->mTouched;
3672 $newTouched = $this->newTouchedTimestamp();
3674 if ( !$wgAuth->allowSetLocalPassword() ) {
3675 $this->mPassword = self::getPasswordFactory()->newFromCiphertext( null );
3678 $dbw = wfGetDB( DB_MASTER );
3679 $dbw->update( 'user',
3680 array( /* SET */
3681 'user_name' => $this->mName,
3682 'user_password' => $this->mPassword->toString(),
3683 'user_newpassword' => $this->mNewpassword->toString(),
3684 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3685 'user_real_name' => $this->mRealName,
3686 'user_email' => $this->mEmail,
3687 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3688 'user_touched' => $dbw->timestamp( $newTouched ),
3689 'user_token' => strval( $this->mToken ),
3690 'user_email_token' => $this->mEmailToken,
3691 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3692 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires ),
3693 ), array( /* WHERE */
3694 'user_id' => $this->mId,
3695 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3696 ), __METHOD__
3699 if ( !$dbw->affectedRows() ) {
3700 // Maybe the problem was a missed cache update; clear it to be safe
3701 $this->clearSharedCache();
3702 // User was changed in the meantime or loaded with stale data
3703 $from = ( $this->queryFlagsUsed & self::READ_LATEST ) ? 'master' : 'slave';
3704 throw new MWException(
3705 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3706 " the version of the user to be saved is older than the current version."
3710 $this->mTouched = $newTouched;
3711 $this->saveOptions();
3713 Hooks::run( 'UserSaveSettings', array( $this ) );
3714 $this->clearSharedCache();
3715 $this->getUserPage()->invalidateCache();
3719 * If only this user's username is known, and it exists, return the user ID.
3721 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3722 * @return int
3724 public function idForName( $flags = 0 ) {
3725 $s = trim( $this->getName() );
3726 if ( $s === '' ) {
3727 return 0;
3730 $db = ( ( $flags & self::READ_LATEST ) == self::READ_LATEST )
3731 ? wfGetDB( DB_MASTER )
3732 : wfGetDB( DB_SLAVE );
3734 $options = ( ( $flags & self::READ_LOCKING ) == self::READ_LOCKING )
3735 ? array( 'LOCK IN SHARE MODE' )
3736 : array();
3738 $id = $db->selectField( 'user',
3739 'user_id', array( 'user_name' => $s ), __METHOD__, $options );
3741 return (int)$id;
3745 * Add a user to the database, return the user object
3747 * @param string $name Username to add
3748 * @param array $params Array of Strings Non-default parameters to save to
3749 * the database as user_* fields:
3750 * - password: The user's password hash. Password logins will be disabled
3751 * if this is omitted.
3752 * - newpassword: Hash for a temporary password that has been mailed to
3753 * the user.
3754 * - email: The user's email address.
3755 * - email_authenticated: The email authentication timestamp.
3756 * - real_name: The user's real name.
3757 * - options: An associative array of non-default options.
3758 * - token: Random authentication token. Do not set.
3759 * - registration: Registration timestamp. Do not set.
3761 * @return User|null User object, or null if the username already exists.
3763 public static function createNew( $name, $params = array() ) {
3764 $user = new User;
3765 $user->load();
3766 $user->loadPasswords();
3767 $user->setToken(); // init token
3768 if ( isset( $params['options'] ) ) {
3769 $user->mOptions = $params['options'] + (array)$user->mOptions;
3770 unset( $params['options'] );
3772 $dbw = wfGetDB( DB_MASTER );
3773 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3775 $fields = array(
3776 'user_id' => $seqVal,
3777 'user_name' => $name,
3778 'user_password' => $user->mPassword->toString(),
3779 'user_newpassword' => $user->mNewpassword->toString(),
3780 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
3781 'user_email' => $user->mEmail,
3782 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3783 'user_real_name' => $user->mRealName,
3784 'user_token' => strval( $user->mToken ),
3785 'user_registration' => $dbw->timestamp( $user->mRegistration ),
3786 'user_editcount' => 0,
3787 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3789 foreach ( $params as $name => $value ) {
3790 $fields["user_$name"] = $value;
3792 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
3793 if ( $dbw->affectedRows() ) {
3794 $newUser = User::newFromId( $dbw->insertId() );
3795 } else {
3796 $newUser = null;
3798 return $newUser;
3802 * Add this existing user object to the database. If the user already
3803 * exists, a fatal status object is returned, and the user object is
3804 * initialised with the data from the database.
3806 * Previously, this function generated a DB error due to a key conflict
3807 * if the user already existed. Many extension callers use this function
3808 * in code along the lines of:
3810 * $user = User::newFromName( $name );
3811 * if ( !$user->isLoggedIn() ) {
3812 * $user->addToDatabase();
3814 * // do something with $user...
3816 * However, this was vulnerable to a race condition (bug 16020). By
3817 * initialising the user object if the user exists, we aim to support this
3818 * calling sequence as far as possible.
3820 * Note that if the user exists, this function will acquire a write lock,
3821 * so it is still advisable to make the call conditional on isLoggedIn(),
3822 * and to commit the transaction after calling.
3824 * @throws MWException
3825 * @return Status
3827 public function addToDatabase() {
3828 $this->load();
3829 $this->loadPasswords();
3830 if ( !$this->mToken ) {
3831 $this->setToken(); // init token
3834 $this->mTouched = $this->newTouchedTimestamp();
3836 $dbw = wfGetDB( DB_MASTER );
3837 $inWrite = $dbw->writesOrCallbacksPending();
3838 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3839 $dbw->insert( 'user',
3840 array(
3841 'user_id' => $seqVal,
3842 'user_name' => $this->mName,
3843 'user_password' => $this->mPassword->toString(),
3844 'user_newpassword' => $this->mNewpassword->toString(),
3845 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3846 'user_email' => $this->mEmail,
3847 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3848 'user_real_name' => $this->mRealName,
3849 'user_token' => strval( $this->mToken ),
3850 'user_registration' => $dbw->timestamp( $this->mRegistration ),
3851 'user_editcount' => 0,
3852 'user_touched' => $dbw->timestamp( $this->mTouched ),
3853 ), __METHOD__,
3854 array( 'IGNORE' )
3856 if ( !$dbw->affectedRows() ) {
3857 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3858 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3859 if ( $inWrite ) {
3860 // Can't commit due to pending writes that may need atomicity.
3861 // This may cause some lock contention unlike the case below.
3862 $options = array( 'LOCK IN SHARE MODE' );
3863 $flags = self::READ_LOCKING;
3864 } else {
3865 // Often, this case happens early in views before any writes when
3866 // using CentralAuth. It's should be OK to commit and break the snapshot.
3867 $dbw->commit( __METHOD__, 'flush' );
3868 $options = array();
3869 $flags = self::READ_LATEST;
3871 $this->mId = $dbw->selectField( 'user', 'user_id',
3872 array( 'user_name' => $this->mName ), __METHOD__, $options );
3873 $loaded = false;
3874 if ( $this->mId ) {
3875 if ( $this->loadFromDatabase( $flags ) ) {
3876 $loaded = true;
3879 if ( !$loaded ) {
3880 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
3881 "to insert user '{$this->mName}' row, but it was not present in select!" );
3883 return Status::newFatal( 'userexists' );
3885 $this->mId = $dbw->insertId();
3887 // Clear instance cache other than user table data, which is already accurate
3888 $this->clearInstanceCache();
3890 $this->saveOptions();
3891 return Status::newGood();
3895 * If this user is logged-in and blocked,
3896 * block any IP address they've successfully logged in from.
3897 * @return bool A block was spread
3899 public function spreadAnyEditBlock() {
3900 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3901 return $this->spreadBlock();
3903 return false;
3907 * If this (non-anonymous) user is blocked,
3908 * block the IP address they've successfully logged in from.
3909 * @return bool A block was spread
3911 protected function spreadBlock() {
3912 wfDebug( __METHOD__ . "()\n" );
3913 $this->load();
3914 if ( $this->mId == 0 ) {
3915 return false;
3918 $userblock = Block::newFromTarget( $this->getName() );
3919 if ( !$userblock ) {
3920 return false;
3923 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3927 * Get whether the user is explicitly blocked from account creation.
3928 * @return bool|Block
3930 public function isBlockedFromCreateAccount() {
3931 $this->getBlockedStatus();
3932 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
3933 return $this->mBlock;
3936 # bug 13611: if the IP address the user is trying to create an account from is
3937 # blocked with createaccount disabled, prevent new account creation there even
3938 # when the user is logged in
3939 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3940 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
3942 return $this->mBlockedFromCreateAccount instanceof Block
3943 && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
3944 ? $this->mBlockedFromCreateAccount
3945 : false;
3949 * Get whether the user is blocked from using Special:Emailuser.
3950 * @return bool
3952 public function isBlockedFromEmailuser() {
3953 $this->getBlockedStatus();
3954 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
3958 * Get whether the user is allowed to create an account.
3959 * @return bool
3961 public function isAllowedToCreateAccount() {
3962 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3966 * Get this user's personal page title.
3968 * @return Title User's personal page title
3970 public function getUserPage() {
3971 return Title::makeTitle( NS_USER, $this->getName() );
3975 * Get this user's talk page title.
3977 * @return Title User's talk page title
3979 public function getTalkPage() {
3980 $title = $this->getUserPage();
3981 return $title->getTalkPage();
3985 * Determine whether the user is a newbie. Newbies are either
3986 * anonymous IPs, or the most recently created accounts.
3987 * @return bool
3989 public function isNewbie() {
3990 return !$this->isAllowed( 'autoconfirmed' );
3994 * Check to see if the given clear-text password is one of the accepted passwords
3995 * @param string $password User password
3996 * @return bool True if the given password is correct, otherwise False
3998 public function checkPassword( $password ) {
3999 global $wgAuth, $wgLegacyEncoding;
4001 $this->loadPasswords();
4003 // Some passwords will give a fatal Status, which means there is
4004 // some sort of technical or security reason for this password to
4005 // be completely invalid and should never be checked (e.g., T64685)
4006 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4007 return false;
4010 // Certain authentication plugins do NOT want to save
4011 // domain passwords in a mysql database, so we should
4012 // check this (in case $wgAuth->strict() is false).
4013 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4014 return true;
4015 } elseif ( $wgAuth->strict() ) {
4016 // Auth plugin doesn't allow local authentication
4017 return false;
4018 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4019 // Auth plugin doesn't allow local authentication for this user name
4020 return false;
4023 if ( !$this->mPassword->equals( $password ) ) {
4024 if ( $wgLegacyEncoding ) {
4025 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4026 // Check for this with iconv
4027 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4028 if ( $cp1252Password === $password || !$this->mPassword->equals( $cp1252Password ) ) {
4029 return false;
4031 } else {
4032 return false;
4036 $passwordFactory = self::getPasswordFactory();
4037 if ( $passwordFactory->needsUpdate( $this->mPassword ) && !wfReadOnly() ) {
4038 $this->mPassword = $passwordFactory->newFromPlaintext( $password );
4039 $this->saveSettings();
4042 return true;
4046 * Check if the given clear-text password matches the temporary password
4047 * sent by e-mail for password reset operations.
4049 * @param string $plaintext
4051 * @return bool True if matches, false otherwise
4053 public function checkTemporaryPassword( $plaintext ) {
4054 global $wgNewPasswordExpiry;
4056 $this->load();
4057 $this->loadPasswords();
4058 if ( $this->mNewpassword->equals( $plaintext ) ) {
4059 if ( is_null( $this->mNewpassTime ) ) {
4060 return true;
4062 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
4063 return ( time() < $expiry );
4064 } else {
4065 return false;
4070 * Alias for getEditToken.
4071 * @deprecated since 1.19, use getEditToken instead.
4073 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4074 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4075 * @return string The new edit token
4077 public function editToken( $salt = '', $request = null ) {
4078 wfDeprecated( __METHOD__, '1.19' );
4079 return $this->getEditToken( $salt, $request );
4083 * Internal implementation for self::getEditToken() and
4084 * self::matchEditToken().
4086 * @param string|array $salt
4087 * @param WebRequest $request
4088 * @param string|int $timestamp
4089 * @return string
4091 private function getEditTokenAtTimestamp( $salt, $request, $timestamp ) {
4092 if ( $this->isAnon() ) {
4093 return self::EDIT_TOKEN_SUFFIX;
4094 } else {
4095 $token = $request->getSessionData( 'wsEditToken' );
4096 if ( $token === null ) {
4097 $token = MWCryptRand::generateHex( 32 );
4098 $request->setSessionData( 'wsEditToken', $token );
4100 if ( is_array( $salt ) ) {
4101 $salt = implode( '|', $salt );
4103 return hash_hmac( 'md5', $timestamp . $salt, $token, false ) .
4104 dechex( $timestamp ) .
4105 self::EDIT_TOKEN_SUFFIX;
4110 * Initialize (if necessary) and return a session token value
4111 * which can be used in edit forms to show that the user's
4112 * login credentials aren't being hijacked with a foreign form
4113 * submission.
4115 * @since 1.19
4117 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4118 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4119 * @return string The new edit token
4121 public function getEditToken( $salt = '', $request = null ) {
4122 return $this->getEditTokenAtTimestamp(
4123 $salt, $request ?: $this->getRequest(), wfTimestamp()
4128 * Generate a looking random token for various uses.
4130 * @return string The new random token
4131 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
4132 * wfRandomString for pseudo-randomness.
4134 public static function generateToken() {
4135 return MWCryptRand::generateHex( 32 );
4139 * Get the embedded timestamp from a token.
4140 * @param string $val Input token
4141 * @return int|null
4143 public static function getEditTokenTimestamp( $val ) {
4144 $suffixLen = strlen( self::EDIT_TOKEN_SUFFIX );
4145 if ( strlen( $val ) <= 32 + $suffixLen ) {
4146 return null;
4149 return hexdec( substr( $val, 32, -$suffixLen ) );
4153 * Check given value against the token value stored in the session.
4154 * A match should confirm that the form was submitted from the
4155 * user's own login session, not a form submission from a third-party
4156 * site.
4158 * @param string $val Input value to compare
4159 * @param string $salt Optional function-specific data for hashing
4160 * @param WebRequest|null $request Object to use or null to use $wgRequest
4161 * @param int $maxage Fail tokens older than this, in seconds
4162 * @return bool Whether the token matches
4164 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4165 if ( $this->isAnon() ) {
4166 return $val === self::EDIT_TOKEN_SUFFIX;
4169 $timestamp = self::getEditTokenTimestamp( $val );
4170 if ( $timestamp === null ) {
4171 return false;
4173 if ( $maxage !== null && $timestamp < wfTimestamp() - $maxage ) {
4174 // Expired token
4175 return false;
4178 $sessionToken = $this->getEditTokenAtTimestamp(
4179 $salt, $request ?: $this->getRequest(), $timestamp
4182 if ( $val != $sessionToken ) {
4183 wfDebug( "User::matchEditToken: broken session data\n" );
4186 return hash_equals( $sessionToken, $val );
4190 * Check given value against the token value stored in the session,
4191 * ignoring the suffix.
4193 * @param string $val Input value to compare
4194 * @param string $salt Optional function-specific data for hashing
4195 * @param WebRequest|null $request Object to use or null to use $wgRequest
4196 * @param int $maxage Fail tokens older than this, in seconds
4197 * @return bool Whether the token matches
4199 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4200 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self::EDIT_TOKEN_SUFFIX;
4201 return $this->matchEditToken( $val, $salt, $request, $maxage );
4205 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4206 * mail to the user's given address.
4208 * @param string $type Message to send, either "created", "changed" or "set"
4209 * @return Status
4211 public function sendConfirmationMail( $type = 'created' ) {
4212 global $wgLang;
4213 $expiration = null; // gets passed-by-ref and defined in next line.
4214 $token = $this->confirmationToken( $expiration );
4215 $url = $this->confirmationTokenUrl( $token );
4216 $invalidateURL = $this->invalidationTokenUrl( $token );
4217 $this->saveSettings();
4219 if ( $type == 'created' || $type === false ) {
4220 $message = 'confirmemail_body';
4221 } elseif ( $type === true ) {
4222 $message = 'confirmemail_body_changed';
4223 } else {
4224 // Messages: confirmemail_body_changed, confirmemail_body_set
4225 $message = 'confirmemail_body_' . $type;
4228 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4229 wfMessage( $message,
4230 $this->getRequest()->getIP(),
4231 $this->getName(),
4232 $url,
4233 $wgLang->timeanddate( $expiration, false ),
4234 $invalidateURL,
4235 $wgLang->date( $expiration, false ),
4236 $wgLang->time( $expiration, false ) )->text() );
4240 * Send an e-mail to this user's account. Does not check for
4241 * confirmed status or validity.
4243 * @param string $subject Message subject
4244 * @param string $body Message body
4245 * @param User|null $from Optional sending user; if unspecified, default
4246 * $wgPasswordSender will be used.
4247 * @param string $replyto Reply-To address
4248 * @return Status
4250 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4251 global $wgPasswordSender;
4253 if ( $from instanceof User ) {
4254 $sender = MailAddress::newFromUser( $from );
4255 } else {
4256 $sender = new MailAddress( $wgPasswordSender,
4257 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4259 $to = MailAddress::newFromUser( $this );
4261 return UserMailer::send( $to, $sender, $subject, $body, array(
4262 'replyTo' => $replyto,
4263 ) );
4267 * Generate, store, and return a new e-mail confirmation code.
4268 * A hash (unsalted, since it's used as a key) is stored.
4270 * @note Call saveSettings() after calling this function to commit
4271 * this change to the database.
4273 * @param string &$expiration Accepts the expiration time
4274 * @return string New token
4276 protected function confirmationToken( &$expiration ) {
4277 global $wgUserEmailConfirmationTokenExpiry;
4278 $now = time();
4279 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
4280 $expiration = wfTimestamp( TS_MW, $expires );
4281 $this->load();
4282 $token = MWCryptRand::generateHex( 32 );
4283 $hash = md5( $token );
4284 $this->mEmailToken = $hash;
4285 $this->mEmailTokenExpires = $expiration;
4286 return $token;
4290 * Return a URL the user can use to confirm their email address.
4291 * @param string $token Accepts the email confirmation token
4292 * @return string New token URL
4294 protected function confirmationTokenUrl( $token ) {
4295 return $this->getTokenUrl( 'ConfirmEmail', $token );
4299 * Return a URL the user can use to invalidate their email address.
4300 * @param string $token Accepts the email confirmation token
4301 * @return string New token URL
4303 protected function invalidationTokenUrl( $token ) {
4304 return $this->getTokenUrl( 'InvalidateEmail', $token );
4308 * Internal function to format the e-mail validation/invalidation URLs.
4309 * This uses a quickie hack to use the
4310 * hardcoded English names of the Special: pages, for ASCII safety.
4312 * @note Since these URLs get dropped directly into emails, using the
4313 * short English names avoids insanely long URL-encoded links, which
4314 * also sometimes can get corrupted in some browsers/mailers
4315 * (bug 6957 with Gmail and Internet Explorer).
4317 * @param string $page Special page
4318 * @param string $token Token
4319 * @return string Formatted URL
4321 protected function getTokenUrl( $page, $token ) {
4322 // Hack to bypass localization of 'Special:'
4323 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
4324 return $title->getCanonicalURL();
4328 * Mark the e-mail address confirmed.
4330 * @note Call saveSettings() after calling this function to commit the change.
4332 * @return bool
4334 public function confirmEmail() {
4335 // Check if it's already confirmed, so we don't touch the database
4336 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4337 if ( !$this->isEmailConfirmed() ) {
4338 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4339 Hooks::run( 'ConfirmEmailComplete', array( $this ) );
4341 return true;
4345 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4346 * address if it was already confirmed.
4348 * @note Call saveSettings() after calling this function to commit the change.
4349 * @return bool Returns true
4351 public function invalidateEmail() {
4352 $this->load();
4353 $this->mEmailToken = null;
4354 $this->mEmailTokenExpires = null;
4355 $this->setEmailAuthenticationTimestamp( null );
4356 $this->mEmail = '';
4357 Hooks::run( 'InvalidateEmailComplete', array( $this ) );
4358 return true;
4362 * Set the e-mail authentication timestamp.
4363 * @param string $timestamp TS_MW timestamp
4365 public function setEmailAuthenticationTimestamp( $timestamp ) {
4366 $this->load();
4367 $this->mEmailAuthenticated = $timestamp;
4368 Hooks::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
4372 * Is this user allowed to send e-mails within limits of current
4373 * site configuration?
4374 * @return bool
4376 public function canSendEmail() {
4377 global $wgEnableEmail, $wgEnableUserEmail;
4378 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4379 return false;
4381 $canSend = $this->isEmailConfirmed();
4382 Hooks::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4383 return $canSend;
4387 * Is this user allowed to receive e-mails within limits of current
4388 * site configuration?
4389 * @return bool
4391 public function canReceiveEmail() {
4392 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4396 * Is this user's e-mail address valid-looking and confirmed within
4397 * limits of the current site configuration?
4399 * @note If $wgEmailAuthentication is on, this may require the user to have
4400 * confirmed their address by returning a code or using a password
4401 * sent to the address from the wiki.
4403 * @return bool
4405 public function isEmailConfirmed() {
4406 global $wgEmailAuthentication;
4407 $this->load();
4408 $confirmed = true;
4409 if ( Hooks::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4410 if ( $this->isAnon() ) {
4411 return false;
4413 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4414 return false;
4416 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4417 return false;
4419 return true;
4420 } else {
4421 return $confirmed;
4426 * Check whether there is an outstanding request for e-mail confirmation.
4427 * @return bool
4429 public function isEmailConfirmationPending() {
4430 global $wgEmailAuthentication;
4431 return $wgEmailAuthentication &&
4432 !$this->isEmailConfirmed() &&
4433 $this->mEmailToken &&
4434 $this->mEmailTokenExpires > wfTimestamp();
4438 * Get the timestamp of account creation.
4440 * @return string|bool|null Timestamp of account creation, false for
4441 * non-existent/anonymous user accounts, or null if existing account
4442 * but information is not in database.
4444 public function getRegistration() {
4445 if ( $this->isAnon() ) {
4446 return false;
4448 $this->load();
4449 return $this->mRegistration;
4453 * Get the timestamp of the first edit
4455 * @return string|bool Timestamp of first edit, or false for
4456 * non-existent/anonymous user accounts.
4458 public function getFirstEditTimestamp() {
4459 if ( $this->getId() == 0 ) {
4460 return false; // anons
4462 $dbr = wfGetDB( DB_SLAVE );
4463 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4464 array( 'rev_user' => $this->getId() ),
4465 __METHOD__,
4466 array( 'ORDER BY' => 'rev_timestamp ASC' )
4468 if ( !$time ) {
4469 return false; // no edits
4471 return wfTimestamp( TS_MW, $time );
4475 * Get the permissions associated with a given list of groups
4477 * @param array $groups Array of Strings List of internal group names
4478 * @return array Array of Strings List of permission key names for given groups combined
4480 public static function getGroupPermissions( $groups ) {
4481 global $wgGroupPermissions, $wgRevokePermissions;
4482 $rights = array();
4483 // grant every granted permission first
4484 foreach ( $groups as $group ) {
4485 if ( isset( $wgGroupPermissions[$group] ) ) {
4486 $rights = array_merge( $rights,
4487 // array_filter removes empty items
4488 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4491 // now revoke the revoked permissions
4492 foreach ( $groups as $group ) {
4493 if ( isset( $wgRevokePermissions[$group] ) ) {
4494 $rights = array_diff( $rights,
4495 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4498 return array_unique( $rights );
4502 * Get all the groups who have a given permission
4504 * @param string $role Role to check
4505 * @return array Array of Strings List of internal group names with the given permission
4507 public static function getGroupsWithPermission( $role ) {
4508 global $wgGroupPermissions;
4509 $allowedGroups = array();
4510 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4511 if ( self::groupHasPermission( $group, $role ) ) {
4512 $allowedGroups[] = $group;
4515 return $allowedGroups;
4519 * Check, if the given group has the given permission
4521 * If you're wanting to check whether all users have a permission, use
4522 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4523 * from anyone.
4525 * @since 1.21
4526 * @param string $group Group to check
4527 * @param string $role Role to check
4528 * @return bool
4530 public static function groupHasPermission( $group, $role ) {
4531 global $wgGroupPermissions, $wgRevokePermissions;
4532 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4533 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4537 * Check if all users have the given permission
4539 * @since 1.22
4540 * @param string $right Right to check
4541 * @return bool
4543 public static function isEveryoneAllowed( $right ) {
4544 global $wgGroupPermissions, $wgRevokePermissions;
4545 static $cache = array();
4547 // Use the cached results, except in unit tests which rely on
4548 // being able change the permission mid-request
4549 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4550 return $cache[$right];
4553 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
4554 $cache[$right] = false;
4555 return false;
4558 // If it's revoked anywhere, then everyone doesn't have it
4559 foreach ( $wgRevokePermissions as $rights ) {
4560 if ( isset( $rights[$right] ) && $rights[$right] ) {
4561 $cache[$right] = false;
4562 return false;
4566 // Allow extensions (e.g. OAuth) to say false
4567 if ( !Hooks::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4568 $cache[$right] = false;
4569 return false;
4572 $cache[$right] = true;
4573 return true;
4577 * Get the localized descriptive name for a group, if it exists
4579 * @param string $group Internal group name
4580 * @return string Localized descriptive group name
4582 public static function getGroupName( $group ) {
4583 $msg = wfMessage( "group-$group" );
4584 return $msg->isBlank() ? $group : $msg->text();
4588 * Get the localized descriptive name for a member of a group, if it exists
4590 * @param string $group Internal group name
4591 * @param string $username Username for gender (since 1.19)
4592 * @return string Localized name for group member
4594 public static function getGroupMember( $group, $username = '#' ) {
4595 $msg = wfMessage( "group-$group-member", $username );
4596 return $msg->isBlank() ? $group : $msg->text();
4600 * Return the set of defined explicit groups.
4601 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4602 * are not included, as they are defined automatically, not in the database.
4603 * @return array Array of internal group names
4605 public static function getAllGroups() {
4606 global $wgGroupPermissions, $wgRevokePermissions;
4607 return array_diff(
4608 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4609 self::getImplicitGroups()
4614 * Get a list of all available permissions.
4615 * @return string[] Array of permission names
4617 public static function getAllRights() {
4618 if ( self::$mAllRights === false ) {
4619 global $wgAvailableRights;
4620 if ( count( $wgAvailableRights ) ) {
4621 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
4622 } else {
4623 self::$mAllRights = self::$mCoreRights;
4625 Hooks::run( 'UserGetAllRights', array( &self::$mAllRights ) );
4627 return self::$mAllRights;
4631 * Get a list of implicit groups
4632 * @return array Array of Strings Array of internal group names
4634 public static function getImplicitGroups() {
4635 global $wgImplicitGroups;
4637 $groups = $wgImplicitGroups;
4638 # Deprecated, use $wgImplicitGroups instead
4639 Hooks::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4641 return $groups;
4645 * Get the title of a page describing a particular group
4647 * @param string $group Internal group name
4648 * @return Title|bool Title of the page if it exists, false otherwise
4650 public static function getGroupPage( $group ) {
4651 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4652 if ( $msg->exists() ) {
4653 $title = Title::newFromText( $msg->text() );
4654 if ( is_object( $title ) ) {
4655 return $title;
4658 return false;
4662 * Create a link to the group in HTML, if available;
4663 * else return the group name.
4665 * @param string $group Internal name of the group
4666 * @param string $text The text of the link
4667 * @return string HTML link to the group
4669 public static function makeGroupLinkHTML( $group, $text = '' ) {
4670 if ( $text == '' ) {
4671 $text = self::getGroupName( $group );
4673 $title = self::getGroupPage( $group );
4674 if ( $title ) {
4675 return Linker::link( $title, htmlspecialchars( $text ) );
4676 } else {
4677 return htmlspecialchars( $text );
4682 * Create a link to the group in Wikitext, if available;
4683 * else return the group name.
4685 * @param string $group Internal name of the group
4686 * @param string $text The text of the link
4687 * @return string Wikilink to the group
4689 public static function makeGroupLinkWiki( $group, $text = '' ) {
4690 if ( $text == '' ) {
4691 $text = self::getGroupName( $group );
4693 $title = self::getGroupPage( $group );
4694 if ( $title ) {
4695 $page = $title->getFullText();
4696 return "[[$page|$text]]";
4697 } else {
4698 return $text;
4703 * Returns an array of the groups that a particular group can add/remove.
4705 * @param string $group The group to check for whether it can add/remove
4706 * @return array Array( 'add' => array( addablegroups ),
4707 * 'remove' => array( removablegroups ),
4708 * 'add-self' => array( addablegroups to self),
4709 * 'remove-self' => array( removable groups from self) )
4711 public static function changeableByGroup( $group ) {
4712 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4714 $groups = array(
4715 'add' => array(),
4716 'remove' => array(),
4717 'add-self' => array(),
4718 'remove-self' => array()
4721 if ( empty( $wgAddGroups[$group] ) ) {
4722 // Don't add anything to $groups
4723 } elseif ( $wgAddGroups[$group] === true ) {
4724 // You get everything
4725 $groups['add'] = self::getAllGroups();
4726 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4727 $groups['add'] = $wgAddGroups[$group];
4730 // Same thing for remove
4731 if ( empty( $wgRemoveGroups[$group] ) ) {
4732 // Do nothing
4733 } elseif ( $wgRemoveGroups[$group] === true ) {
4734 $groups['remove'] = self::getAllGroups();
4735 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4736 $groups['remove'] = $wgRemoveGroups[$group];
4739 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4740 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4741 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4742 if ( is_int( $key ) ) {
4743 $wgGroupsAddToSelf['user'][] = $value;
4748 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4749 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4750 if ( is_int( $key ) ) {
4751 $wgGroupsRemoveFromSelf['user'][] = $value;
4756 // Now figure out what groups the user can add to him/herself
4757 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4758 // Do nothing
4759 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4760 // No idea WHY this would be used, but it's there
4761 $groups['add-self'] = User::getAllGroups();
4762 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4763 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4766 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4767 // Do nothing
4768 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4769 $groups['remove-self'] = User::getAllGroups();
4770 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4771 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4774 return $groups;
4778 * Returns an array of groups that this user can add and remove
4779 * @return array Array( 'add' => array( addablegroups ),
4780 * 'remove' => array( removablegroups ),
4781 * 'add-self' => array( addablegroups to self),
4782 * 'remove-self' => array( removable groups from self) )
4784 public function changeableGroups() {
4785 if ( $this->isAllowed( 'userrights' ) ) {
4786 // This group gives the right to modify everything (reverse-
4787 // compatibility with old "userrights lets you change
4788 // everything")
4789 // Using array_merge to make the groups reindexed
4790 $all = array_merge( User::getAllGroups() );
4791 return array(
4792 'add' => $all,
4793 'remove' => $all,
4794 'add-self' => array(),
4795 'remove-self' => array()
4799 // Okay, it's not so simple, we will have to go through the arrays
4800 $groups = array(
4801 'add' => array(),
4802 'remove' => array(),
4803 'add-self' => array(),
4804 'remove-self' => array()
4806 $addergroups = $this->getEffectiveGroups();
4808 foreach ( $addergroups as $addergroup ) {
4809 $groups = array_merge_recursive(
4810 $groups, $this->changeableByGroup( $addergroup )
4812 $groups['add'] = array_unique( $groups['add'] );
4813 $groups['remove'] = array_unique( $groups['remove'] );
4814 $groups['add-self'] = array_unique( $groups['add-self'] );
4815 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4817 return $groups;
4821 * Deferred version of incEditCountImmediate()
4823 public function incEditCount() {
4824 $that = $this;
4825 wfGetDB( DB_MASTER )->onTransactionPreCommitOrIdle( function() use ( $that ) {
4826 $that->incEditCountImmediate();
4827 } );
4831 * Increment the user's edit-count field.
4832 * Will have no effect for anonymous users.
4833 * @since 1.26
4835 public function incEditCountImmediate() {
4836 if ( $this->isAnon() ) {
4837 return;
4840 $dbw = wfGetDB( DB_MASTER );
4841 // No rows will be "affected" if user_editcount is NULL
4842 $dbw->update(
4843 'user',
4844 array( 'user_editcount=user_editcount+1' ),
4845 array( 'user_id' => $this->getId() ),
4846 __METHOD__
4848 // Lazy initialization check...
4849 if ( $dbw->affectedRows() == 0 ) {
4850 // Now here's a goddamn hack...
4851 $dbr = wfGetDB( DB_SLAVE );
4852 if ( $dbr !== $dbw ) {
4853 // If we actually have a slave server, the count is
4854 // at least one behind because the current transaction
4855 // has not been committed and replicated.
4856 $this->initEditCount( 1 );
4857 } else {
4858 // But if DB_SLAVE is selecting the master, then the
4859 // count we just read includes the revision that was
4860 // just added in the working transaction.
4861 $this->initEditCount();
4864 // Edit count in user cache too
4865 $this->invalidateCache();
4869 * Initialize user_editcount from data out of the revision table
4871 * @param int $add Edits to add to the count from the revision table
4872 * @return int Number of edits
4874 protected function initEditCount( $add = 0 ) {
4875 // Pull from a slave to be less cruel to servers
4876 // Accuracy isn't the point anyway here
4877 $dbr = wfGetDB( DB_SLAVE );
4878 $count = (int)$dbr->selectField(
4879 'revision',
4880 'COUNT(rev_user)',
4881 array( 'rev_user' => $this->getId() ),
4882 __METHOD__
4884 $count = $count + $add;
4886 $dbw = wfGetDB( DB_MASTER );
4887 $dbw->update(
4888 'user',
4889 array( 'user_editcount' => $count ),
4890 array( 'user_id' => $this->getId() ),
4891 __METHOD__
4894 return $count;
4898 * Get the description of a given right
4900 * @param string $right Right to query
4901 * @return string Localized description of the right
4903 public static function getRightDescription( $right ) {
4904 $key = "right-$right";
4905 $msg = wfMessage( $key );
4906 return $msg->isBlank() ? $right : $msg->text();
4910 * Make a new-style password hash
4912 * @param string $password Plain-text password
4913 * @param bool|string $salt Optional salt, may be random or the user ID.
4914 * If unspecified or false, will generate one automatically
4915 * @return string Password hash
4916 * @deprecated since 1.24, use Password class
4918 public static function crypt( $password, $salt = false ) {
4919 wfDeprecated( __METHOD__, '1.24' );
4920 $hash = self::getPasswordFactory()->newFromPlaintext( $password );
4921 return $hash->toString();
4925 * Compare a password hash with a plain-text password. Requires the user
4926 * ID if there's a chance that the hash is an old-style hash.
4928 * @param string $hash Password hash
4929 * @param string $password Plain-text password to compare
4930 * @param string|bool $userId User ID for old-style password salt
4932 * @return bool
4933 * @deprecated since 1.24, use Password class
4935 public static function comparePasswords( $hash, $password, $userId = false ) {
4936 wfDeprecated( __METHOD__, '1.24' );
4938 // Check for *really* old password hashes that don't even have a type
4939 // The old hash format was just an md5 hex hash, with no type information
4940 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4941 global $wgPasswordSalt;
4942 if ( $wgPasswordSalt ) {
4943 $password = ":B:{$userId}:{$hash}";
4944 } else {
4945 $password = ":A:{$hash}";
4949 $hash = self::getPasswordFactory()->newFromCiphertext( $hash );
4950 return $hash->equals( $password );
4954 * Add a newuser log entry for this user.
4955 * Before 1.19 the return value was always true.
4957 * @param string|bool $action Account creation type.
4958 * - String, one of the following values:
4959 * - 'create' for an anonymous user creating an account for himself.
4960 * This will force the action's performer to be the created user itself,
4961 * no matter the value of $wgUser
4962 * - 'create2' for a logged in user creating an account for someone else
4963 * - 'byemail' when the created user will receive its password by e-mail
4964 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4965 * - Boolean means whether the account was created by e-mail (deprecated):
4966 * - true will be converted to 'byemail'
4967 * - false will be converted to 'create' if this object is the same as
4968 * $wgUser and to 'create2' otherwise
4970 * @param string $reason User supplied reason
4972 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4974 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4975 global $wgUser, $wgNewUserLog;
4976 if ( empty( $wgNewUserLog ) ) {
4977 return true; // disabled
4980 if ( $action === true ) {
4981 $action = 'byemail';
4982 } elseif ( $action === false ) {
4983 if ( $this->equals( $wgUser ) ) {
4984 $action = 'create';
4985 } else {
4986 $action = 'create2';
4990 if ( $action === 'create' || $action === 'autocreate' ) {
4991 $performer = $this;
4992 } else {
4993 $performer = $wgUser;
4996 $logEntry = new ManualLogEntry( 'newusers', $action );
4997 $logEntry->setPerformer( $performer );
4998 $logEntry->setTarget( $this->getUserPage() );
4999 $logEntry->setComment( $reason );
5000 $logEntry->setParameters( array(
5001 '4::userid' => $this->getId(),
5002 ) );
5003 $logid = $logEntry->insert();
5005 if ( $action !== 'autocreate' ) {
5006 $logEntry->publish( $logid );
5009 return (int)$logid;
5013 * Add an autocreate newuser log entry for this user
5014 * Used by things like CentralAuth and perhaps other authplugins.
5015 * Consider calling addNewUserLogEntry() directly instead.
5017 * @return bool
5019 public function addNewUserLogEntryAutoCreate() {
5020 $this->addNewUserLogEntry( 'autocreate' );
5022 return true;
5026 * Load the user options either from cache, the database or an array
5028 * @param array $data Rows for the current user out of the user_properties table
5030 protected function loadOptions( $data = null ) {
5031 global $wgContLang;
5033 $this->load();
5035 if ( $this->mOptionsLoaded ) {
5036 return;
5039 $this->mOptions = self::getDefaultOptions();
5041 if ( !$this->getId() ) {
5042 // For unlogged-in users, load language/variant options from request.
5043 // There's no need to do it for logged-in users: they can set preferences,
5044 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5045 // so don't override user's choice (especially when the user chooses site default).
5046 $variant = $wgContLang->getDefaultVariant();
5047 $this->mOptions['variant'] = $variant;
5048 $this->mOptions['language'] = $variant;
5049 $this->mOptionsLoaded = true;
5050 return;
5053 // Maybe load from the object
5054 if ( !is_null( $this->mOptionOverrides ) ) {
5055 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5056 foreach ( $this->mOptionOverrides as $key => $value ) {
5057 $this->mOptions[$key] = $value;
5059 } else {
5060 if ( !is_array( $data ) ) {
5061 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5062 // Load from database
5063 $dbr = ( $this->queryFlagsUsed & self::READ_LATEST )
5064 ? wfGetDB( DB_MASTER )
5065 : wfGetDB( DB_SLAVE );
5067 $res = $dbr->select(
5068 'user_properties',
5069 array( 'up_property', 'up_value' ),
5070 array( 'up_user' => $this->getId() ),
5071 __METHOD__
5074 $this->mOptionOverrides = array();
5075 $data = array();
5076 foreach ( $res as $row ) {
5077 $data[$row->up_property] = $row->up_value;
5080 foreach ( $data as $property => $value ) {
5081 $this->mOptionOverrides[$property] = $value;
5082 $this->mOptions[$property] = $value;
5086 $this->mOptionsLoaded = true;
5088 Hooks::run( 'UserLoadOptions', array( $this, &$this->mOptions ) );
5092 * Saves the non-default options for this user, as previously set e.g. via
5093 * setOption(), in the database's "user_properties" (preferences) table.
5094 * Usually used via saveSettings().
5096 protected function saveOptions() {
5097 $this->loadOptions();
5099 // Not using getOptions(), to keep hidden preferences in database
5100 $saveOptions = $this->mOptions;
5102 // Allow hooks to abort, for instance to save to a global profile.
5103 // Reset options to default state before saving.
5104 if ( !Hooks::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
5105 return;
5108 $userId = $this->getId();
5110 $insert_rows = array(); // all the new preference rows
5111 foreach ( $saveOptions as $key => $value ) {
5112 // Don't bother storing default values
5113 $defaultOption = self::getDefaultOption( $key );
5114 if ( ( $defaultOption === null && $value !== false && $value !== null )
5115 || $value != $defaultOption
5117 $insert_rows[] = array(
5118 'up_user' => $userId,
5119 'up_property' => $key,
5120 'up_value' => $value,
5125 $dbw = wfGetDB( DB_MASTER );
5127 $res = $dbw->select( 'user_properties',
5128 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__ );
5130 // Find prior rows that need to be removed or updated. These rows will
5131 // all be deleted (the later so that INSERT IGNORE applies the new values).
5132 $keysDelete = array();
5133 foreach ( $res as $row ) {
5134 if ( !isset( $saveOptions[$row->up_property] )
5135 || strcmp( $saveOptions[$row->up_property], $row->up_value ) != 0
5137 $keysDelete[] = $row->up_property;
5141 if ( count( $keysDelete ) ) {
5142 // Do the DELETE by PRIMARY KEY for prior rows.
5143 // In the past a very large portion of calls to this function are for setting
5144 // 'rememberpassword' for new accounts (a preference that has since been removed).
5145 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5146 // caused gap locks on [max user ID,+infinity) which caused high contention since
5147 // updates would pile up on each other as they are for higher (newer) user IDs.
5148 // It might not be necessary these days, but it shouldn't hurt either.
5149 $dbw->delete( 'user_properties',
5150 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__ );
5152 // Insert the new preference rows
5153 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, array( 'IGNORE' ) );
5157 * Lazily instantiate and return a factory object for making passwords
5159 * @return PasswordFactory
5161 public static function getPasswordFactory() {
5162 if ( self::$mPasswordFactory === null ) {
5163 self::$mPasswordFactory = new PasswordFactory();
5164 self::$mPasswordFactory->init( RequestContext::getMain()->getConfig() );
5167 return self::$mPasswordFactory;
5171 * Provide an array of HTML5 attributes to put on an input element
5172 * intended for the user to enter a new password. This may include
5173 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5175 * Do *not* use this when asking the user to enter his current password!
5176 * Regardless of configuration, users may have invalid passwords for whatever
5177 * reason (e.g., they were set before requirements were tightened up).
5178 * Only use it when asking for a new password, like on account creation or
5179 * ResetPass.
5181 * Obviously, you still need to do server-side checking.
5183 * NOTE: A combination of bugs in various browsers means that this function
5184 * actually just returns array() unconditionally at the moment. May as
5185 * well keep it around for when the browser bugs get fixed, though.
5187 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5189 * @return array Array of HTML attributes suitable for feeding to
5190 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5191 * That will get confused by the boolean attribute syntax used.)
5193 public static function passwordChangeInputAttribs() {
5194 global $wgMinimalPasswordLength;
5196 if ( $wgMinimalPasswordLength == 0 ) {
5197 return array();
5200 # Note that the pattern requirement will always be satisfied if the
5201 # input is empty, so we need required in all cases.
5203 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5204 # if e-mail confirmation is being used. Since HTML5 input validation
5205 # is b0rked anyway in some browsers, just return nothing. When it's
5206 # re-enabled, fix this code to not output required for e-mail
5207 # registration.
5208 #$ret = array( 'required' );
5209 $ret = array();
5211 # We can't actually do this right now, because Opera 9.6 will print out
5212 # the entered password visibly in its error message! When other
5213 # browsers add support for this attribute, or Opera fixes its support,
5214 # we can add support with a version check to avoid doing this on Opera
5215 # versions where it will be a problem. Reported to Opera as
5216 # DSK-262266, but they don't have a public bug tracker for us to follow.
5218 if ( $wgMinimalPasswordLength > 1 ) {
5219 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5220 $ret['title'] = wfMessage( 'passwordtooshort' )
5221 ->numParams( $wgMinimalPasswordLength )->text();
5225 return $ret;
5229 * Return the list of user fields that should be selected to create
5230 * a new user object.
5231 * @return array
5233 public static function selectFields() {
5234 return array(
5235 'user_id',
5236 'user_name',
5237 'user_real_name',
5238 'user_email',
5239 'user_touched',
5240 'user_token',
5241 'user_email_authenticated',
5242 'user_email_token',
5243 'user_email_token_expires',
5244 'user_registration',
5245 'user_editcount',
5250 * Factory function for fatal permission-denied errors
5252 * @since 1.22
5253 * @param string $permission User right required
5254 * @return Status
5256 static function newFatalPermissionDeniedStatus( $permission ) {
5257 global $wgLang;
5259 $groups = array_map(
5260 array( 'User', 'makeGroupLinkWiki' ),
5261 User::getGroupsWithPermission( $permission )
5264 if ( $groups ) {
5265 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5266 } else {
5267 return Status::newFatal( 'badaccess-group0' );
5272 * Checks if two user objects point to the same user.
5274 * @since 1.25
5275 * @param User $user
5276 * @return bool
5278 public function equals( User $user ) {
5279 return $this->getName() === $user->getName();