Removed 'Remember my login' preference
[mediawiki.git] / includes / User.php
blobfd10e9af7c3b2492d6857aba40d970ad7fed61e8
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 * Int Number of characters in user_token field.
25 * @ingroup Constants
27 define( 'USER_TOKEN_LENGTH', 32 );
29 /**
30 * Int Serialized record version.
31 * @ingroup Constants
33 define( 'MW_USER_VERSION', 9 );
35 /**
36 * String Some punctuation to prevent editing from broken text-mangling proxies.
37 * @ingroup Constants
39 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
41 /**
42 * Thrown by User::setPassword() on error.
43 * @ingroup Exception
45 class PasswordError extends MWException {
46 // NOP
49 /**
50 * The User object encapsulates all of the user-specific settings (user_id,
51 * name, rights, password, email address, options, last login time). Client
52 * classes use the getXXX() functions to access these fields. These functions
53 * do all the work of determining whether the user is logged in,
54 * whether the requested option can be satisfied from cookies or
55 * whether a database query is needed. Most of the settings needed
56 * for rendering normal pages are set in the cookie to minimize use
57 * of the database.
59 class User {
60 /**
61 * Global constants made accessible as class constants so that autoloader
62 * magic can be used.
64 const USER_TOKEN_LENGTH = USER_TOKEN_LENGTH;
65 const MW_USER_VERSION = MW_USER_VERSION;
66 const EDIT_TOKEN_SUFFIX = EDIT_TOKEN_SUFFIX;
68 /**
69 * Maximum items in $mWatchedItems
71 const MAX_WATCHED_ITEMS_CACHE = 100;
73 /**
74 * Array of Strings List of member variables which are saved to the
75 * shared cache (memcached). Any operation which changes the
76 * corresponding database fields must call a cache-clearing function.
77 * @showinitializer
79 static $mCacheVars = array(
80 // user table
81 'mId',
82 'mName',
83 'mRealName',
84 'mPassword',
85 'mNewpassword',
86 'mNewpassTime',
87 'mEmail',
88 'mTouched',
89 'mToken',
90 'mEmailAuthenticated',
91 'mEmailToken',
92 'mEmailTokenExpires',
93 'mPasswordExpires',
94 'mRegistration',
95 'mEditCount',
96 // user_groups table
97 'mGroups',
98 // user_properties table
99 'mOptionOverrides',
103 * Array of Strings Core rights.
104 * Each of these should have a corresponding message of the form
105 * "right-$right".
106 * @showinitializer
108 static $mCoreRights = array(
109 'apihighlimits',
110 'autoconfirmed',
111 'autopatrol',
112 'bigdelete',
113 'block',
114 'blockemail',
115 'bot',
116 'browsearchive',
117 'createaccount',
118 'createpage',
119 'createtalk',
120 'delete',
121 'deletedhistory',
122 'deletedtext',
123 'deletelogentry',
124 'deleterevision',
125 'edit',
126 'editinterface',
127 'editprotected',
128 'editmyoptions',
129 'editmyprivateinfo',
130 'editmyusercss',
131 'editmyuserjs',
132 'editmywatchlist',
133 'editsemiprotected',
134 'editusercssjs', #deprecated
135 'editusercss',
136 'edituserjs',
137 'hideuser',
138 'import',
139 'importupload',
140 'ipblock-exempt',
141 'markbotedits',
142 'mergehistory',
143 'minoredit',
144 'move',
145 'movefile',
146 'move-rootuserpages',
147 'move-subpages',
148 'nominornewtalk',
149 'noratelimit',
150 'override-export-depth',
151 'passwordreset',
152 'patrol',
153 'patrolmarks',
154 'protect',
155 'proxyunbannable',
156 'purge',
157 'read',
158 'reupload',
159 'reupload-own',
160 'reupload-shared',
161 'rollback',
162 'sendemail',
163 'siteadmin',
164 'suppressionlog',
165 'suppressredirect',
166 'suppressrevision',
167 'unblockself',
168 'undelete',
169 'unwatchedpages',
170 'upload',
171 'upload_by_url',
172 'userrights',
173 'userrights-interwiki',
174 'viewmyprivateinfo',
175 'viewmywatchlist',
176 'writeapi',
179 * String Cached results of getAllRights()
181 static $mAllRights = false;
183 /** @name Cache variables */
184 //@{
185 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
186 $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
187 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mEditCount,
188 $mGroups, $mOptionOverrides;
190 protected $mPasswordExpires;
191 //@}
194 * Bool Whether the cache variables have been loaded.
196 //@{
197 var $mOptionsLoaded;
200 * Array with already loaded items or true if all items have been loaded.
202 private $mLoadedItems = array();
203 //@}
206 * String Initialization data source if mLoadedItems!==true. May be one of:
207 * - 'defaults' anonymous user initialised from class defaults
208 * - 'name' initialise from mName
209 * - 'id' initialise from mId
210 * - 'session' log in from cookies or session if possible
212 * Use the User::newFrom*() family of functions to set this.
214 var $mFrom;
217 * Lazy-initialized variables, invalidated with clearInstanceCache
219 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mRights,
220 $mBlockreason, $mEffectiveGroups, $mImplicitGroups, $mFormerGroups, $mBlockedGlobally,
221 $mLocked, $mHideName, $mOptions;
224 * @var WebRequest
226 private $mRequest;
229 * @var Block
231 var $mBlock;
234 * @var bool
236 var $mAllowUsertalk;
239 * @var Block
241 private $mBlockedFromCreateAccount = false;
244 * @var Array
246 private $mWatchedItems = array();
248 static $idCacheByName = array();
251 * Lightweight constructor for an anonymous user.
252 * Use the User::newFrom* factory functions for other kinds of users.
254 * @see newFromName()
255 * @see newFromId()
256 * @see newFromConfirmationCode()
257 * @see newFromSession()
258 * @see newFromRow()
260 public function __construct() {
261 $this->clearInstanceCache( 'defaults' );
265 * @return string
267 public function __toString() {
268 return $this->getName();
272 * Load the user table data for this object from the source given by mFrom.
274 public function load() {
275 if ( $this->mLoadedItems === true ) {
276 return;
278 wfProfileIn( __METHOD__ );
280 // Set it now to avoid infinite recursion in accessors
281 $this->mLoadedItems = true;
283 switch ( $this->mFrom ) {
284 case 'defaults':
285 $this->loadDefaults();
286 break;
287 case 'name':
288 $this->mId = self::idFromName( $this->mName );
289 if ( !$this->mId ) {
290 // Nonexistent user placeholder object
291 $this->loadDefaults( $this->mName );
292 } else {
293 $this->loadFromId();
295 break;
296 case 'id':
297 $this->loadFromId();
298 break;
299 case 'session':
300 if ( !$this->loadFromSession() ) {
301 // Loading from session failed. Load defaults.
302 $this->loadDefaults();
304 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
305 break;
306 default:
307 wfProfileOut( __METHOD__ );
308 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
310 wfProfileOut( __METHOD__ );
314 * Load user table data, given mId has already been set.
315 * @return bool false if the ID does not exist, true otherwise
317 public function loadFromId() {
318 global $wgMemc;
319 if ( $this->mId == 0 ) {
320 $this->loadDefaults();
321 return false;
324 // Try cache
325 $key = wfMemcKey( 'user', 'id', $this->mId );
326 $data = $wgMemc->get( $key );
327 if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
328 // Object is expired, load from DB
329 $data = false;
332 if ( !$data ) {
333 wfDebug( "User: cache miss for user {$this->mId}\n" );
334 // Load from DB
335 if ( !$this->loadFromDatabase() ) {
336 // Can't load from ID, user is anonymous
337 return false;
339 $this->saveToCache();
340 } else {
341 wfDebug( "User: got user {$this->mId} from cache\n" );
342 // Restore from cache
343 foreach ( self::$mCacheVars as $name ) {
344 $this->$name = $data[$name];
348 $this->mLoadedItems = true;
350 return true;
354 * Save user data to the shared cache
356 public function saveToCache() {
357 $this->load();
358 $this->loadGroups();
359 $this->loadOptions();
360 if ( $this->isAnon() ) {
361 // Anonymous users are uncached
362 return;
364 $data = array();
365 foreach ( self::$mCacheVars as $name ) {
366 $data[$name] = $this->$name;
368 $data['mVersion'] = MW_USER_VERSION;
369 $key = wfMemcKey( 'user', 'id', $this->mId );
370 global $wgMemc;
371 $wgMemc->set( $key, $data );
374 /** @name newFrom*() static factory methods */
375 //@{
378 * Static factory method for creation from username.
380 * This is slightly less efficient than newFromId(), so use newFromId() if
381 * you have both an ID and a name handy.
383 * @param string $name Username, validated by Title::newFromText()
384 * @param string|bool $validate Validate username. Takes the same parameters as
385 * User::getCanonicalName(), except that true is accepted as an alias
386 * for 'valid', for BC.
388 * @return User|bool User object, or false if the username is invalid
389 * (e.g. if it contains illegal characters or is an IP address). If the
390 * username is not present in the database, the result will be a user object
391 * with a name, zero user ID and default settings.
393 public static function newFromName( $name, $validate = 'valid' ) {
394 if ( $validate === true ) {
395 $validate = 'valid';
397 $name = self::getCanonicalName( $name, $validate );
398 if ( $name === false ) {
399 return false;
400 } else {
401 // Create unloaded user object
402 $u = new User;
403 $u->mName = $name;
404 $u->mFrom = 'name';
405 $u->setItemLoaded( 'name' );
406 return $u;
411 * Static factory method for creation from a given user ID.
413 * @param int $id Valid user ID
414 * @return User The corresponding User object
416 public static function newFromId( $id ) {
417 $u = new User;
418 $u->mId = $id;
419 $u->mFrom = 'id';
420 $u->setItemLoaded( 'id' );
421 return $u;
425 * Factory method to fetch whichever user has a given email confirmation code.
426 * This code is generated when an account is created or its e-mail address
427 * has changed.
429 * If the code is invalid or has expired, returns NULL.
431 * @param string $code Confirmation code
432 * @return User|null
434 public static function newFromConfirmationCode( $code ) {
435 $dbr = wfGetDB( DB_SLAVE );
436 $id = $dbr->selectField( 'user', 'user_id', array(
437 'user_email_token' => md5( $code ),
438 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
439 ) );
440 if ( $id !== false ) {
441 return User::newFromId( $id );
442 } else {
443 return null;
448 * Create a new user object using data from session or cookies. If the
449 * login credentials are invalid, the result is an anonymous user.
451 * @param WebRequest $request Object to use; $wgRequest will be used if omitted.
452 * @return User object
454 public static function newFromSession( WebRequest $request = null ) {
455 $user = new User;
456 $user->mFrom = 'session';
457 $user->mRequest = $request;
458 return $user;
462 * Create a new user object from a user row.
463 * The row should have the following fields from the user table in it:
464 * - either user_name or user_id to load further data if needed (or both)
465 * - user_real_name
466 * - all other fields (email, password, etc.)
467 * It is useless to provide the remaining fields if either user_id,
468 * user_name and user_real_name are not provided because the whole row
469 * will be loaded once more from the database when accessing them.
471 * @param stdClass $row A row from the user table
472 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
473 * @return User
475 public static function newFromRow( $row, $data = null ) {
476 $user = new User;
477 $user->loadFromRow( $row, $data );
478 return $user;
481 //@}
484 * Get the username corresponding to a given user ID
485 * @param int $id User ID
486 * @return string|bool The corresponding username
488 public static function whoIs( $id ) {
489 return UserCache::singleton()->getProp( $id, 'name' );
493 * Get the real name of a user given their user ID
495 * @param int $id User ID
496 * @return string|bool The corresponding user's real name
498 public static function whoIsReal( $id ) {
499 return UserCache::singleton()->getProp( $id, 'real_name' );
503 * Get database id given a user name
504 * @param string $name Username
505 * @return int|null The corresponding user's ID, or null if user is nonexistent
507 public static function idFromName( $name ) {
508 $nt = Title::makeTitleSafe( NS_USER, $name );
509 if ( is_null( $nt ) ) {
510 // Illegal name
511 return null;
514 if ( isset( self::$idCacheByName[$name] ) ) {
515 return self::$idCacheByName[$name];
518 $dbr = wfGetDB( DB_SLAVE );
519 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
521 if ( $s === false ) {
522 $result = null;
523 } else {
524 $result = $s->user_id;
527 self::$idCacheByName[$name] = $result;
529 if ( count( self::$idCacheByName ) > 1000 ) {
530 self::$idCacheByName = array();
533 return $result;
537 * Reset the cache used in idFromName(). For use in tests.
539 public static function resetIdByNameCache() {
540 self::$idCacheByName = array();
544 * Does the string match an anonymous IPv4 address?
546 * This function exists for username validation, in order to reject
547 * usernames which are similar in form to IP addresses. Strings such
548 * as 300.300.300.300 will return true because it looks like an IP
549 * address, despite not being strictly valid.
551 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
552 * address because the usemod software would "cloak" anonymous IP
553 * addresses like this, if we allowed accounts like this to be created
554 * new users could get the old edits of these anonymous users.
556 * @param string $name Name to match
557 * @return bool
559 public static function isIP( $name ) {
560 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name ) || IP::isIPv6( $name );
564 * Is the input a valid username?
566 * Checks if the input is a valid username, we don't want an empty string,
567 * an IP address, anything that contains slashes (would mess up subpages),
568 * is longer than the maximum allowed username size or doesn't begin with
569 * a capital letter.
571 * @param string $name Name to match
572 * @return bool
574 public static function isValidUserName( $name ) {
575 global $wgContLang, $wgMaxNameChars;
577 if ( $name == ''
578 || User::isIP( $name )
579 || strpos( $name, '/' ) !== false
580 || strlen( $name ) > $wgMaxNameChars
581 || $name != $wgContLang->ucfirst( $name ) ) {
582 wfDebugLog( 'username', __METHOD__ .
583 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
584 return false;
587 // Ensure that the name can't be misresolved as a different title,
588 // such as with extra namespace keys at the start.
589 $parsed = Title::newFromText( $name );
590 if ( is_null( $parsed )
591 || $parsed->getNamespace()
592 || strcmp( $name, $parsed->getPrefixedText() ) ) {
593 wfDebugLog( 'username', __METHOD__ .
594 ": '$name' invalid due to ambiguous prefixes" );
595 return false;
598 // Check an additional blacklist of troublemaker characters.
599 // Should these be merged into the title char list?
600 $unicodeBlacklist = '/[' .
601 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
602 '\x{00a0}' . # non-breaking space
603 '\x{2000}-\x{200f}' . # various whitespace
604 '\x{2028}-\x{202f}' . # breaks and control chars
605 '\x{3000}' . # ideographic space
606 '\x{e000}-\x{f8ff}' . # private use
607 ']/u';
608 if ( preg_match( $unicodeBlacklist, $name ) ) {
609 wfDebugLog( 'username', __METHOD__ .
610 ": '$name' invalid due to blacklisted characters" );
611 return false;
614 return true;
618 * Usernames which fail to pass this function will be blocked
619 * from user login and new account registrations, but may be used
620 * internally by batch processes.
622 * If an account already exists in this form, login will be blocked
623 * by a failure to pass this function.
625 * @param string $name Name to match
626 * @return bool
628 public static function isUsableName( $name ) {
629 global $wgReservedUsernames;
630 // Must be a valid username, obviously ;)
631 if ( !self::isValidUserName( $name ) ) {
632 return false;
635 static $reservedUsernames = false;
636 if ( !$reservedUsernames ) {
637 $reservedUsernames = $wgReservedUsernames;
638 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
641 // Certain names may be reserved for batch processes.
642 foreach ( $reservedUsernames as $reserved ) {
643 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
644 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
646 if ( $reserved == $name ) {
647 return false;
650 return true;
654 * Usernames which fail to pass this function will be blocked
655 * from new account registrations, but may be used internally
656 * either by batch processes or by user accounts which have
657 * already been created.
659 * Additional blacklisting may be added here rather than in
660 * isValidUserName() to avoid disrupting existing accounts.
662 * @param string $name to match
663 * @return bool
665 public static function isCreatableName( $name ) {
666 global $wgInvalidUsernameCharacters;
668 // Ensure that the username isn't longer than 235 bytes, so that
669 // (at least for the builtin skins) user javascript and css files
670 // will work. (bug 23080)
671 if ( strlen( $name ) > 235 ) {
672 wfDebugLog( 'username', __METHOD__ .
673 ": '$name' invalid due to length" );
674 return false;
677 // Preg yells if you try to give it an empty string
678 if ( $wgInvalidUsernameCharacters !== '' ) {
679 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
680 wfDebugLog( 'username', __METHOD__ .
681 ": '$name' invalid due to wgInvalidUsernameCharacters" );
682 return false;
686 return self::isUsableName( $name );
690 * Is the input a valid password for this user?
692 * @param string $password Desired password
693 * @return bool
695 public function isValidPassword( $password ) {
696 //simple boolean wrapper for getPasswordValidity
697 return $this->getPasswordValidity( $password ) === true;
702 * Given unvalidated password input, return error message on failure.
704 * @param string $password Desired password
705 * @return mixed: true on success, string or array of error message on failure
707 public function getPasswordValidity( $password ) {
708 $result = $this->checkPasswordValidity( $password );
709 if ( $result->isGood() ) {
710 return true;
711 } else {
712 $messages = array();
713 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
714 $messages[] = $error['message'];
716 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
717 $messages[] = $warning['message'];
719 if ( count( $messages ) === 1 ) {
720 return $messages[0];
722 return $messages;
727 * Check if this is a valid password for this user. Status will be good if
728 * the password is valid, or have an array of error messages if not.
730 * @param string $password Desired password
731 * @return Status
732 * @since 1.23
734 public function checkPasswordValidity( $password ) {
735 global $wgMinimalPasswordLength, $wgContLang;
737 static $blockedLogins = array(
738 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
739 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
742 $status = Status::newGood();
744 $result = false; //init $result to false for the internal checks
746 if ( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) ) {
747 $status->error( $result );
748 return $status;
751 if ( $result === false ) {
752 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
753 $status->error( 'passwordtooshort', $wgMinimalPasswordLength );
754 return $status;
755 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName ) ) {
756 $status->error( 'password-name-match' );
757 return $status;
758 } elseif ( isset( $blockedLogins[$this->getName()] ) && $password == $blockedLogins[$this->getName()] ) {
759 $status->error( 'password-login-forbidden' );
760 return $status;
761 } else {
762 //it seems weird returning a Good status here, but this is because of the
763 //initialization of $result to false above. If the hook is never run or it
764 //doesn't modify $result, then we will likely get down into this if with
765 //a valid password.
766 return $status;
768 } elseif ( $result === true ) {
769 return $status;
770 } else {
771 $status->error( $result );
772 return $status; //the isValidPassword hook set a string $result and returned true
777 * Expire a user's password
778 * @since 1.23
779 * @param $ts Mixed: optional timestamp to convert, default 0 for the current time
781 public function expirePassword( $ts = 0 ) {
782 $this->load();
783 $timestamp = wfTimestamp( TS_MW, $ts );
784 $this->mPasswordExpires = $timestamp;
785 $this->saveSettings();
789 * Clear the password expiration for a user
790 * @since 1.23
791 * @param bool $load ensure user object is loaded first
793 public function resetPasswordExpiration( $load = true ) {
794 global $wgPasswordExpirationDays;
795 if ( $load ) {
796 $this->load();
798 $newExpire = null;
799 if ( $wgPasswordExpirationDays ) {
800 $newExpire = wfTimestamp(
801 TS_MW,
802 time() + ( $wgPasswordExpirationDays * 24 * 3600 )
805 // Give extensions a chance to force an expiration
806 wfRunHooks( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
807 $this->mPasswordExpires = $newExpire;
811 * Check if the user's password is expired.
812 * TODO: Put this and password length into a PasswordPolicy object
813 * @since 1.23
814 * @return string|bool The expiration type, or false if not expired
815 * hard: A password change is required to login
816 * soft: Allow login, but encourage password change
817 * false: Password is not expired
819 public function getPasswordExpired() {
820 global $wgPasswordExpireGrace;
821 $expired = false;
822 $now = wfTimestamp();
823 $expiration = $this->getPasswordExpireDate();
824 $expUnix = wfTimestamp( TS_UNIX, $expiration );
825 if ( $expiration !== null && $expUnix < $now ) {
826 $expired = ( $expUnix + $wgPasswordExpireGrace < $now ) ? 'hard' : 'soft';
828 return $expired;
832 * Get this user's password expiration date. Since this may be using
833 * the cached User object, we assume that whatever mechanism is setting
834 * the expiration date is also expiring the User cache.
835 * @since 1.23
836 * @return string|false the datestamp of the expiration, or null if not set
838 public function getPasswordExpireDate() {
839 $this->load();
840 return $this->mPasswordExpires;
844 * Does a string look like an e-mail address?
846 * This validates an email address using an HTML5 specification found at:
847 * http://www.whatwg.org/html/states-of-the-type-attribute.html#valid-e-mail-address
848 * Which as of 2011-01-24 says:
850 * A valid e-mail address is a string that matches the ABNF production
851 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
852 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
853 * 3.5.
855 * This function is an implementation of the specification as requested in
856 * bug 22449.
858 * Client-side forms will use the same standard validation rules via JS or
859 * HTML 5 validation; additional restrictions can be enforced server-side
860 * by extensions via the 'isValidEmailAddr' hook.
862 * Note that this validation doesn't 100% match RFC 2822, but is believed
863 * to be liberal enough for wide use. Some invalid addresses will still
864 * pass validation here.
866 * @param string $addr E-mail address
867 * @return bool
868 * @deprecated since 1.18 call Sanitizer::isValidEmail() directly
870 public static function isValidEmailAddr( $addr ) {
871 wfDeprecated( __METHOD__, '1.18' );
872 return Sanitizer::validateEmail( $addr );
876 * Given unvalidated user input, return a canonical username, or false if
877 * the username is invalid.
878 * @param string $name User input
879 * @param string|bool $validate type of validation to use:
880 * - false No validation
881 * - 'valid' Valid for batch processes
882 * - 'usable' Valid for batch processes and login
883 * - 'creatable' Valid for batch processes, login and account creation
885 * @throws MWException
886 * @return bool|string
888 public static function getCanonicalName( $name, $validate = 'valid' ) {
889 // Force usernames to capital
890 global $wgContLang;
891 $name = $wgContLang->ucfirst( $name );
893 # Reject names containing '#'; these will be cleaned up
894 # with title normalisation, but then it's too late to
895 # check elsewhere
896 if ( strpos( $name, '#' ) !== false ) {
897 return false;
900 // Clean up name according to title rules
901 $t = ( $validate === 'valid' ) ?
902 Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
903 // Check for invalid titles
904 if ( is_null( $t ) ) {
905 return false;
908 // Reject various classes of invalid names
909 global $wgAuth;
910 $name = $wgAuth->getCanonicalName( $t->getText() );
912 switch ( $validate ) {
913 case false:
914 break;
915 case 'valid':
916 if ( !User::isValidUserName( $name ) ) {
917 $name = false;
919 break;
920 case 'usable':
921 if ( !User::isUsableName( $name ) ) {
922 $name = false;
924 break;
925 case 'creatable':
926 if ( !User::isCreatableName( $name ) ) {
927 $name = false;
929 break;
930 default:
931 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__ );
933 return $name;
937 * Count the number of edits of a user
939 * @param int $uid User ID to check
940 * @return int The user's edit count
942 * @deprecated since 1.21 in favour of User::getEditCount
944 public static function edits( $uid ) {
945 wfDeprecated( __METHOD__, '1.21' );
946 $user = self::newFromId( $uid );
947 return $user->getEditCount();
951 * Return a random password.
953 * @return string New random password
955 public static function randomPassword() {
956 global $wgMinimalPasswordLength;
957 // Decide the final password length based on our min password length, stopping at a minimum of 10 chars
958 $length = max( 10, $wgMinimalPasswordLength );
959 // Multiply by 1.25 to get the number of hex characters we need
960 $length = $length * 1.25;
961 // Generate random hex chars
962 $hex = MWCryptRand::generateHex( $length );
963 // Convert from base 16 to base 32 to get a proper password like string
964 return wfBaseConvert( $hex, 16, 32 );
968 * Set cached properties to default.
970 * @note This no longer clears uncached lazy-initialised properties;
971 * the constructor does that instead.
973 * @param $name string|bool
975 public function loadDefaults( $name = false ) {
976 wfProfileIn( __METHOD__ );
978 $this->mId = 0;
979 $this->mName = $name;
980 $this->mRealName = '';
981 $this->mPassword = $this->mNewpassword = '';
982 $this->mNewpassTime = null;
983 $this->mEmail = '';
984 $this->mOptionOverrides = null;
985 $this->mOptionsLoaded = false;
987 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
988 if ( $loggedOut !== null ) {
989 $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
990 } else {
991 $this->mTouched = '1'; # Allow any pages to be cached
994 $this->mToken = null; // Don't run cryptographic functions till we need a token
995 $this->mEmailAuthenticated = null;
996 $this->mEmailToken = '';
997 $this->mEmailTokenExpires = null;
998 $this->mPasswordExpires = null;
999 $this->resetPasswordExpiration( false );
1000 $this->mRegistration = wfTimestamp( TS_MW );
1001 $this->mGroups = array();
1003 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
1005 wfProfileOut( __METHOD__ );
1009 * Return whether an item has been loaded.
1011 * @param string $item item to check. Current possibilities:
1012 * - id
1013 * - name
1014 * - realname
1015 * @param string $all 'all' to check if the whole object has been loaded
1016 * or any other string to check if only the item is available (e.g.
1017 * for optimisation)
1018 * @return boolean
1020 public function isItemLoaded( $item, $all = 'all' ) {
1021 return ( $this->mLoadedItems === true && $all === 'all' ) ||
1022 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
1026 * Set that an item has been loaded
1028 * @param string $item
1030 protected function setItemLoaded( $item ) {
1031 if ( is_array( $this->mLoadedItems ) ) {
1032 $this->mLoadedItems[$item] = true;
1037 * Load user data from the session or login cookie.
1038 * @return bool True if the user is logged in, false otherwise.
1040 private function loadFromSession() {
1041 $result = null;
1042 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
1043 if ( $result !== null ) {
1044 return $result;
1047 $request = $this->getRequest();
1049 $cookieId = $request->getCookie( 'UserID' );
1050 $sessId = $request->getSessionData( 'wsUserID' );
1052 if ( $cookieId !== null ) {
1053 $sId = intval( $cookieId );
1054 if ( $sessId !== null && $cookieId != $sessId ) {
1055 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1056 cookie user ID ($sId) don't match!" );
1057 return false;
1059 $request->setSessionData( 'wsUserID', $sId );
1060 } elseif ( $sessId !== null && $sessId != 0 ) {
1061 $sId = $sessId;
1062 } else {
1063 return false;
1066 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1067 $sName = $request->getSessionData( 'wsUserName' );
1068 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1069 $sName = $request->getCookie( 'UserName' );
1070 $request->setSessionData( 'wsUserName', $sName );
1071 } else {
1072 return false;
1075 $proposedUser = User::newFromId( $sId );
1076 if ( !$proposedUser->isLoggedIn() ) {
1077 // Not a valid ID
1078 return false;
1081 global $wgBlockDisablesLogin;
1082 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1083 // User blocked and we've disabled blocked user logins
1084 return false;
1087 if ( $request->getSessionData( 'wsToken' ) ) {
1088 $passwordCorrect = ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1089 $from = 'session';
1090 } elseif ( $request->getCookie( 'Token' ) ) {
1091 # Get the token from DB/cache and clean it up to remove garbage padding.
1092 # This deals with historical problems with bugs and the default column value.
1093 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1094 // Make comparison in constant time (bug 61346)
1095 $passwordCorrect = strlen( $token ) && $this->compareSecrets( $token, $request->getCookie( 'Token' ) );
1096 $from = 'cookie';
1097 } else {
1098 // No session or persistent login cookie
1099 return false;
1102 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1103 $this->loadFromUserObject( $proposedUser );
1104 $request->setSessionData( 'wsToken', $this->mToken );
1105 wfDebug( "User: logged in from $from\n" );
1106 return true;
1107 } else {
1108 // Invalid credentials
1109 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1110 return false;
1115 * A comparison of two strings, not vulnerable to timing attacks
1116 * @param string $answer the secret string that you are comparing against.
1117 * @param string $test compare this string to the $answer.
1118 * @return bool True if the strings are the same, false otherwise
1120 protected function compareSecrets( $answer, $test ) {
1121 if ( strlen( $answer ) !== strlen( $test ) ) {
1122 $passwordCorrect = false;
1123 } else {
1124 $result = 0;
1125 for ( $i = 0; $i < strlen( $answer ); $i++ ) {
1126 $result |= ord( $answer[$i] ) ^ ord( $test[$i] );
1128 $passwordCorrect = ( $result == 0 );
1130 return $passwordCorrect;
1134 * Load user and user_group data from the database.
1135 * $this->mId must be set, this is how the user is identified.
1137 * @return bool True if the user exists, false if the user is anonymous
1139 public function loadFromDatabase() {
1140 // Paranoia
1141 $this->mId = intval( $this->mId );
1143 // Anonymous user
1144 if ( !$this->mId ) {
1145 $this->loadDefaults();
1146 return false;
1149 $dbr = wfGetDB( DB_MASTER );
1150 $s = $dbr->selectRow( 'user', self::selectFields(), array( 'user_id' => $this->mId ), __METHOD__ );
1152 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1154 if ( $s !== false ) {
1155 // Initialise user table data
1156 $this->loadFromRow( $s );
1157 $this->mGroups = null; // deferred
1158 $this->getEditCount(); // revalidation for nulls
1159 return true;
1160 } else {
1161 // Invalid user_id
1162 $this->mId = 0;
1163 $this->loadDefaults();
1164 return false;
1169 * Initialize this object from a row from the user table.
1171 * @param stdClass $row Row from the user table to load.
1172 * @param array $data Further user data to load into the object
1174 * user_groups Array with groups out of the user_groups table
1175 * user_properties Array with properties out of the user_properties table
1177 public function loadFromRow( $row, $data = null ) {
1178 $all = true;
1180 $this->mGroups = null; // deferred
1182 if ( isset( $row->user_name ) ) {
1183 $this->mName = $row->user_name;
1184 $this->mFrom = 'name';
1185 $this->setItemLoaded( 'name' );
1186 } else {
1187 $all = false;
1190 if ( isset( $row->user_real_name ) ) {
1191 $this->mRealName = $row->user_real_name;
1192 $this->setItemLoaded( 'realname' );
1193 } else {
1194 $all = false;
1197 if ( isset( $row->user_id ) ) {
1198 $this->mId = intval( $row->user_id );
1199 $this->mFrom = 'id';
1200 $this->setItemLoaded( 'id' );
1201 } else {
1202 $all = false;
1205 if ( isset( $row->user_editcount ) ) {
1206 $this->mEditCount = $row->user_editcount;
1207 } else {
1208 $all = false;
1211 if ( isset( $row->user_password ) ) {
1212 $this->mPassword = $row->user_password;
1213 $this->mNewpassword = $row->user_newpassword;
1214 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
1215 $this->mEmail = $row->user_email;
1216 if ( isset( $row->user_options ) ) {
1217 $this->decodeOptions( $row->user_options );
1219 $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1220 $this->mToken = $row->user_token;
1221 if ( $this->mToken == '' ) {
1222 $this->mToken = null;
1224 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1225 $this->mEmailToken = $row->user_email_token;
1226 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1227 $this->mPasswordExpires = wfTimestampOrNull( TS_MW, $row->user_password_expires );
1228 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1229 } else {
1230 $all = false;
1233 if ( $all ) {
1234 $this->mLoadedItems = true;
1237 if ( is_array( $data ) ) {
1238 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1239 $this->mGroups = $data['user_groups'];
1241 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1242 $this->loadOptions( $data['user_properties'] );
1248 * Load the data for this user object from another user object.
1250 * @param $user User
1252 protected function loadFromUserObject( $user ) {
1253 $user->load();
1254 $user->loadGroups();
1255 $user->loadOptions();
1256 foreach ( self::$mCacheVars as $var ) {
1257 $this->$var = $user->$var;
1262 * Load the groups from the database if they aren't already loaded.
1264 private function loadGroups() {
1265 if ( is_null( $this->mGroups ) ) {
1266 $dbr = wfGetDB( DB_MASTER );
1267 $res = $dbr->select( 'user_groups',
1268 array( 'ug_group' ),
1269 array( 'ug_user' => $this->mId ),
1270 __METHOD__ );
1271 $this->mGroups = array();
1272 foreach ( $res as $row ) {
1273 $this->mGroups[] = $row->ug_group;
1279 * Add the user to the group if he/she meets given criteria.
1281 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1282 * possible to remove manually via Special:UserRights. In such case it
1283 * will not be re-added automatically. The user will also not lose the
1284 * group if they no longer meet the criteria.
1286 * @param string $event key in $wgAutopromoteOnce (each one has groups/criteria)
1288 * @return array Array of groups the user has been promoted to.
1290 * @see $wgAutopromoteOnce
1292 public function addAutopromoteOnceGroups( $event ) {
1293 global $wgAutopromoteOnceLogInRC, $wgAuth;
1295 $toPromote = array();
1296 if ( $this->getId() ) {
1297 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1298 if ( count( $toPromote ) ) {
1299 $oldGroups = $this->getGroups(); // previous groups
1301 foreach ( $toPromote as $group ) {
1302 $this->addGroup( $group );
1304 // update groups in external authentication database
1305 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1307 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1309 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1310 $logEntry->setPerformer( $this );
1311 $logEntry->setTarget( $this->getUserPage() );
1312 $logEntry->setParameters( array(
1313 '4::oldgroups' => $oldGroups,
1314 '5::newgroups' => $newGroups,
1315 ) );
1316 $logid = $logEntry->insert();
1317 if ( $wgAutopromoteOnceLogInRC ) {
1318 $logEntry->publish( $logid );
1322 return $toPromote;
1326 * Clear various cached data stored in this object. The cache of the user table
1327 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1329 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1330 * given source. May be "name", "id", "defaults", "session", or false for
1331 * no reload.
1333 public function clearInstanceCache( $reloadFrom = false ) {
1334 $this->mNewtalk = -1;
1335 $this->mDatePreference = null;
1336 $this->mBlockedby = -1; # Unset
1337 $this->mHash = false;
1338 $this->mRights = null;
1339 $this->mEffectiveGroups = null;
1340 $this->mImplicitGroups = null;
1341 $this->mGroups = null;
1342 $this->mOptions = null;
1343 $this->mOptionsLoaded = false;
1344 $this->mEditCount = null;
1346 if ( $reloadFrom ) {
1347 $this->mLoadedItems = array();
1348 $this->mFrom = $reloadFrom;
1353 * Combine the language default options with any site-specific options
1354 * and add the default language variants.
1356 * @return Array of String options
1358 public static function getDefaultOptions() {
1359 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1361 static $defOpt = null;
1362 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1363 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1364 // mid-request and see that change reflected in the return value of this function.
1365 // Which is insane and would never happen during normal MW operation
1366 return $defOpt;
1369 $defOpt = $wgDefaultUserOptions;
1370 // Default language setting
1371 $defOpt['language'] = $wgContLang->getCode();
1372 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
1373 $defOpt[$langCode == $wgContLang->getCode() ? 'variant' : "variant-$langCode"] = $langCode;
1375 foreach ( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1376 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1378 $defOpt['skin'] = $wgDefaultSkin;
1380 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1382 return $defOpt;
1386 * Get a given default option value.
1388 * @param string $opt Name of option to retrieve
1389 * @return string Default option value
1391 public static function getDefaultOption( $opt ) {
1392 $defOpts = self::getDefaultOptions();
1393 if ( isset( $defOpts[$opt] ) ) {
1394 return $defOpts[$opt];
1395 } else {
1396 return null;
1401 * Get blocking information
1402 * @param bool $bFromSlave Whether to check the slave database first. To
1403 * improve performance, non-critical checks are done
1404 * against slaves. Check when actually saving should be
1405 * done against master.
1407 private function getBlockedStatus( $bFromSlave = true ) {
1408 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1410 if ( -1 != $this->mBlockedby ) {
1411 return;
1414 wfProfileIn( __METHOD__ );
1415 wfDebug( __METHOD__ . ": checking...\n" );
1417 // Initialize data...
1418 // Otherwise something ends up stomping on $this->mBlockedby when
1419 // things get lazy-loaded later, causing false positive block hits
1420 // due to -1 !== 0. Probably session-related... Nothing should be
1421 // overwriting mBlockedby, surely?
1422 $this->load();
1424 # We only need to worry about passing the IP address to the Block generator if the
1425 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1426 # know which IP address they're actually coming from
1427 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1428 $ip = $this->getRequest()->getIP();
1429 } else {
1430 $ip = null;
1433 // User/IP blocking
1434 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1436 // Proxy blocking
1437 if ( !$block instanceof Block && $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1438 && !in_array( $ip, $wgProxyWhitelist )
1440 // Local list
1441 if ( self::isLocallyBlockedProxy( $ip ) ) {
1442 $block = new Block;
1443 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1444 $block->mReason = wfMessage( 'proxyblockreason' )->text();
1445 $block->setTarget( $ip );
1446 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1447 $block = new Block;
1448 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1449 $block->mReason = wfMessage( 'sorbsreason' )->text();
1450 $block->setTarget( $ip );
1454 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1455 if ( !$block instanceof Block
1456 && $wgApplyIpBlocksToXff
1457 && $ip !== null
1458 && !$this->isAllowed( 'proxyunbannable' )
1459 && !in_array( $ip, $wgProxyWhitelist )
1461 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1462 $xff = array_map( 'trim', explode( ',', $xff ) );
1463 $xff = array_diff( $xff, array( $ip ) );
1464 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1465 $block = Block::chooseBlock( $xffblocks, $xff );
1466 if ( $block instanceof Block ) {
1467 # Mangle the reason to alert the user that the block
1468 # originated from matching the X-Forwarded-For header.
1469 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->text();
1473 if ( $block instanceof Block ) {
1474 wfDebug( __METHOD__ . ": Found block.\n" );
1475 $this->mBlock = $block;
1476 $this->mBlockedby = $block->getByName();
1477 $this->mBlockreason = $block->mReason;
1478 $this->mHideName = $block->mHideName;
1479 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1480 } else {
1481 $this->mBlockedby = '';
1482 $this->mHideName = 0;
1483 $this->mAllowUsertalk = false;
1486 // Extensions
1487 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1489 wfProfileOut( __METHOD__ );
1493 * Whether the given IP is in a DNS blacklist.
1495 * @param string $ip IP to check
1496 * @param bool $checkWhitelist whether to check the whitelist first
1497 * @return bool True if blacklisted.
1499 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1500 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1501 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1503 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs ) {
1504 return false;
1507 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1508 return false;
1511 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1512 return $this->inDnsBlacklist( $ip, $urls );
1516 * Whether the given IP is in a given DNS blacklist.
1518 * @param string $ip IP to check
1519 * @param string|array $bases of Strings: URL of the DNS blacklist
1520 * @return bool True if blacklisted.
1522 public function inDnsBlacklist( $ip, $bases ) {
1523 wfProfileIn( __METHOD__ );
1525 $found = false;
1526 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1527 if ( IP::isIPv4( $ip ) ) {
1528 // Reverse IP, bug 21255
1529 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1531 foreach ( (array)$bases as $base ) {
1532 // Make hostname
1533 // If we have an access key, use that too (ProjectHoneypot, etc.)
1534 if ( is_array( $base ) ) {
1535 if ( count( $base ) >= 2 ) {
1536 // Access key is 1, base URL is 0
1537 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1538 } else {
1539 $host = "$ipReversed.{$base[0]}";
1541 } else {
1542 $host = "$ipReversed.$base";
1545 // Send query
1546 $ipList = gethostbynamel( $host );
1548 if ( $ipList ) {
1549 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1550 $found = true;
1551 break;
1552 } else {
1553 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1558 wfProfileOut( __METHOD__ );
1559 return $found;
1563 * Check if an IP address is in the local proxy list
1565 * @param $ip string
1567 * @return bool
1569 public static function isLocallyBlockedProxy( $ip ) {
1570 global $wgProxyList;
1572 if ( !$wgProxyList ) {
1573 return false;
1575 wfProfileIn( __METHOD__ );
1577 if ( !is_array( $wgProxyList ) ) {
1578 // Load from the specified file
1579 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1582 if ( !is_array( $wgProxyList ) ) {
1583 $ret = false;
1584 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1585 $ret = true;
1586 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1587 // Old-style flipped proxy list
1588 $ret = true;
1589 } else {
1590 $ret = false;
1592 wfProfileOut( __METHOD__ );
1593 return $ret;
1597 * Is this user subject to rate limiting?
1599 * @return bool True if rate limited
1601 public function isPingLimitable() {
1602 global $wgRateLimitsExcludedIPs;
1603 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1604 // No other good way currently to disable rate limits
1605 // for specific IPs. :P
1606 // But this is a crappy hack and should die.
1607 return false;
1609 return !$this->isAllowed( 'noratelimit' );
1613 * Primitive rate limits: enforce maximum actions per time period
1614 * to put a brake on flooding.
1616 * @note When using a shared cache like memcached, IP-address
1617 * last-hit counters will be shared across wikis.
1619 * @param string $action Action to enforce; 'edit' if unspecified
1620 * @param integer $incrBy Positive amount to increment counter by [defaults to 1]
1621 * @return bool True if a rate limiter was tripped
1623 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1624 // Call the 'PingLimiter' hook
1625 $result = false;
1626 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1627 return $result;
1630 global $wgRateLimits;
1631 if ( !isset( $wgRateLimits[$action] ) ) {
1632 return false;
1635 // Some groups shouldn't trigger the ping limiter, ever
1636 if ( !$this->isPingLimitable() ) {
1637 return false;
1640 global $wgMemc;
1641 wfProfileIn( __METHOD__ );
1643 $limits = $wgRateLimits[$action];
1644 $keys = array();
1645 $id = $this->getId();
1646 $userLimit = false;
1648 if ( isset( $limits['anon'] ) && $id == 0 ) {
1649 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1652 if ( isset( $limits['user'] ) && $id != 0 ) {
1653 $userLimit = $limits['user'];
1655 if ( $this->isNewbie() ) {
1656 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1657 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1659 if ( isset( $limits['ip'] ) ) {
1660 $ip = $this->getRequest()->getIP();
1661 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1663 if ( isset( $limits['subnet'] ) ) {
1664 $ip = $this->getRequest()->getIP();
1665 $matches = array();
1666 $subnet = false;
1667 if ( IP::isIPv6( $ip ) ) {
1668 $parts = IP::parseRange( "$ip/64" );
1669 $subnet = $parts[0];
1670 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1671 // IPv4
1672 $subnet = $matches[1];
1674 if ( $subnet !== false ) {
1675 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1679 // Check for group-specific permissions
1680 // If more than one group applies, use the group with the highest limit
1681 foreach ( $this->getGroups() as $group ) {
1682 if ( isset( $limits[$group] ) ) {
1683 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1684 $userLimit = $limits[$group];
1688 // Set the user limit key
1689 if ( $userLimit !== false ) {
1690 list( $max, $period ) = $userLimit;
1691 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
1692 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1695 $triggered = false;
1696 foreach ( $keys as $key => $limit ) {
1697 list( $max, $period ) = $limit;
1698 $summary = "(limit $max in {$period}s)";
1699 $count = $wgMemc->get( $key );
1700 // Already pinged?
1701 if ( $count ) {
1702 if ( $count >= $max ) {
1703 wfDebugLog( 'ratelimit', $this->getName() . " tripped! $key at $count $summary" );
1704 $triggered = true;
1705 } else {
1706 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1708 } else {
1709 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1710 if ( $incrBy > 0 ) {
1711 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1714 if ( $incrBy > 0 ) {
1715 $wgMemc->incr( $key, $incrBy );
1719 wfProfileOut( __METHOD__ );
1720 return $triggered;
1724 * Check if user is blocked
1726 * @param bool $bFromSlave Whether to check the slave database instead of the master
1727 * @return bool True if blocked, false otherwise
1729 public function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1730 return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
1734 * Get the block affecting the user, or null if the user is not blocked
1736 * @param bool $bFromSlave Whether to check the slave database instead of the master
1737 * @return Block|null
1739 public function getBlock( $bFromSlave = true ) {
1740 $this->getBlockedStatus( $bFromSlave );
1741 return $this->mBlock instanceof Block ? $this->mBlock : null;
1745 * Check if user is blocked from editing a particular article
1747 * @param Title $title Title to check
1748 * @param bool $bFromSlave whether to check the slave database instead of the master
1749 * @return bool
1751 public function isBlockedFrom( $title, $bFromSlave = false ) {
1752 global $wgBlockAllowsUTEdit;
1753 wfProfileIn( __METHOD__ );
1755 $blocked = $this->isBlocked( $bFromSlave );
1756 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1757 // If a user's name is suppressed, they cannot make edits anywhere
1758 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName()
1759 && $title->getNamespace() == NS_USER_TALK ) {
1760 $blocked = false;
1761 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1764 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1766 wfProfileOut( __METHOD__ );
1767 return $blocked;
1771 * If user is blocked, return the name of the user who placed the block
1772 * @return string Name of blocker
1774 public function blockedBy() {
1775 $this->getBlockedStatus();
1776 return $this->mBlockedby;
1780 * If user is blocked, return the specified reason for the block
1781 * @return string Blocking reason
1783 public function blockedFor() {
1784 $this->getBlockedStatus();
1785 return $this->mBlockreason;
1789 * If user is blocked, return the ID for the block
1790 * @return int Block ID
1792 public function getBlockId() {
1793 $this->getBlockedStatus();
1794 return ( $this->mBlock ? $this->mBlock->getId() : false );
1798 * Check if user is blocked on all wikis.
1799 * Do not use for actual edit permission checks!
1800 * This is intended for quick UI checks.
1802 * @param string $ip IP address, uses current client if none given
1803 * @return bool True if blocked, false otherwise
1805 public function isBlockedGlobally( $ip = '' ) {
1806 if ( $this->mBlockedGlobally !== null ) {
1807 return $this->mBlockedGlobally;
1809 // User is already an IP?
1810 if ( IP::isIPAddress( $this->getName() ) ) {
1811 $ip = $this->getName();
1812 } elseif ( !$ip ) {
1813 $ip = $this->getRequest()->getIP();
1815 $blocked = false;
1816 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1817 $this->mBlockedGlobally = (bool)$blocked;
1818 return $this->mBlockedGlobally;
1822 * Check if user account is locked
1824 * @return bool True if locked, false otherwise
1826 public function isLocked() {
1827 if ( $this->mLocked !== null ) {
1828 return $this->mLocked;
1830 global $wgAuth;
1831 StubObject::unstub( $wgAuth );
1832 $authUser = $wgAuth->getUserInstance( $this );
1833 $this->mLocked = (bool)$authUser->isLocked();
1834 return $this->mLocked;
1838 * Check if user account is hidden
1840 * @return bool True if hidden, false otherwise
1842 public function isHidden() {
1843 if ( $this->mHideName !== null ) {
1844 return $this->mHideName;
1846 $this->getBlockedStatus();
1847 if ( !$this->mHideName ) {
1848 global $wgAuth;
1849 StubObject::unstub( $wgAuth );
1850 $authUser = $wgAuth->getUserInstance( $this );
1851 $this->mHideName = (bool)$authUser->isHidden();
1853 return $this->mHideName;
1857 * Get the user's ID.
1858 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1860 public function getId() {
1861 if ( $this->mId === null && $this->mName !== null && User::isIP( $this->mName ) ) {
1862 // Special case, we know the user is anonymous
1863 return 0;
1864 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1865 // Don't load if this was initialized from an ID
1866 $this->load();
1868 return $this->mId;
1872 * Set the user and reload all fields according to a given ID
1873 * @param int $v User ID to reload
1875 public function setId( $v ) {
1876 $this->mId = $v;
1877 $this->clearInstanceCache( 'id' );
1881 * Get the user name, or the IP of an anonymous user
1882 * @return string User's name or IP address
1884 public function getName() {
1885 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1886 // Special case optimisation
1887 return $this->mName;
1888 } else {
1889 $this->load();
1890 if ( $this->mName === false ) {
1891 // Clean up IPs
1892 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
1894 return $this->mName;
1899 * Set the user name.
1901 * This does not reload fields from the database according to the given
1902 * name. Rather, it is used to create a temporary "nonexistent user" for
1903 * later addition to the database. It can also be used to set the IP
1904 * address for an anonymous user to something other than the current
1905 * remote IP.
1907 * @note User::newFromName() has roughly the same function, when the named user
1908 * does not exist.
1909 * @param string $str New user name to set
1911 public function setName( $str ) {
1912 $this->load();
1913 $this->mName = $str;
1917 * Get the user's name escaped by underscores.
1918 * @return string Username escaped by underscores.
1920 public function getTitleKey() {
1921 return str_replace( ' ', '_', $this->getName() );
1925 * Check if the user has new messages.
1926 * @return bool True if the user has new messages
1928 public function getNewtalk() {
1929 $this->load();
1931 // Load the newtalk status if it is unloaded (mNewtalk=-1)
1932 if ( $this->mNewtalk === -1 ) {
1933 $this->mNewtalk = false; # reset talk page status
1935 // Check memcached separately for anons, who have no
1936 // entire User object stored in there.
1937 if ( !$this->mId ) {
1938 global $wgDisableAnonTalk;
1939 if ( $wgDisableAnonTalk ) {
1940 // Anon newtalk disabled by configuration.
1941 $this->mNewtalk = false;
1942 } else {
1943 global $wgMemc;
1944 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1945 $newtalk = $wgMemc->get( $key );
1946 if ( strval( $newtalk ) !== '' ) {
1947 $this->mNewtalk = (bool)$newtalk;
1948 } else {
1949 // Since we are caching this, make sure it is up to date by getting it
1950 // from the master
1951 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1952 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1955 } else {
1956 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1960 return (bool)$this->mNewtalk;
1964 * Return the data needed to construct links for new talk page message
1965 * alerts. If there are new messages, this will return an associative array
1966 * with the following data:
1967 * wiki: The database name of the wiki
1968 * link: Root-relative link to the user's talk page
1969 * rev: The last talk page revision that the user has seen or null. This
1970 * is useful for building diff links.
1971 * If there are no new messages, it returns an empty array.
1972 * @note This function was designed to accomodate multiple talk pages, but
1973 * currently only returns a single link and revision.
1974 * @return Array
1976 public function getNewMessageLinks() {
1977 $talks = array();
1978 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
1979 return $talks;
1980 } elseif ( !$this->getNewtalk() ) {
1981 return array();
1983 $utp = $this->getTalkPage();
1984 $dbr = wfGetDB( DB_SLAVE );
1985 // Get the "last viewed rev" timestamp from the oldest message notification
1986 $timestamp = $dbr->selectField( 'user_newtalk',
1987 'MIN(user_last_timestamp)',
1988 $this->isAnon() ? array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
1989 __METHOD__ );
1990 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
1991 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
1995 * Get the revision ID for the last talk page revision viewed by the talk
1996 * page owner.
1997 * @return int|null Revision ID or null
1999 public function getNewMessageRevisionId() {
2000 $newMessageRevisionId = null;
2001 $newMessageLinks = $this->getNewMessageLinks();
2002 if ( $newMessageLinks ) {
2003 // Note: getNewMessageLinks() never returns more than a single link
2004 // and it is always for the same wiki, but we double-check here in
2005 // case that changes some time in the future.
2006 if ( count( $newMessageLinks ) === 1
2007 && $newMessageLinks[0]['wiki'] === wfWikiID()
2008 && $newMessageLinks[0]['rev']
2010 $newMessageRevision = $newMessageLinks[0]['rev'];
2011 $newMessageRevisionId = $newMessageRevision->getId();
2014 return $newMessageRevisionId;
2018 * Internal uncached check for new messages
2020 * @see getNewtalk()
2021 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2022 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2023 * @param bool $fromMaster true to fetch from the master, false for a slave
2024 * @return bool True if the user has new messages
2026 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
2027 if ( $fromMaster ) {
2028 $db = wfGetDB( DB_MASTER );
2029 } else {
2030 $db = wfGetDB( DB_SLAVE );
2032 $ok = $db->selectField( 'user_newtalk', $field,
2033 array( $field => $id ), __METHOD__ );
2034 return $ok !== false;
2038 * Add or update the new messages flag
2039 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2040 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2041 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null.
2042 * @return bool True if successful, false otherwise
2044 protected function updateNewtalk( $field, $id, $curRev = null ) {
2045 // Get timestamp of the talk page revision prior to the current one
2046 $prevRev = $curRev ? $curRev->getPrevious() : false;
2047 $ts = $prevRev ? $prevRev->getTimestamp() : null;
2048 // Mark the user as having new messages since this revision
2049 $dbw = wfGetDB( DB_MASTER );
2050 $dbw->insert( 'user_newtalk',
2051 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2052 __METHOD__,
2053 'IGNORE' );
2054 if ( $dbw->affectedRows() ) {
2055 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
2056 return true;
2057 } else {
2058 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
2059 return false;
2064 * Clear the new messages flag for the given user
2065 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2066 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2067 * @return bool True if successful, false otherwise
2069 protected function deleteNewtalk( $field, $id ) {
2070 $dbw = wfGetDB( DB_MASTER );
2071 $dbw->delete( 'user_newtalk',
2072 array( $field => $id ),
2073 __METHOD__ );
2074 if ( $dbw->affectedRows() ) {
2075 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
2076 return true;
2077 } else {
2078 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
2079 return false;
2084 * Update the 'You have new messages!' status.
2085 * @param bool $val Whether the user has new messages
2086 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null or !$val.
2088 public function setNewtalk( $val, $curRev = null ) {
2089 if ( wfReadOnly() ) {
2090 return;
2093 $this->load();
2094 $this->mNewtalk = $val;
2096 if ( $this->isAnon() ) {
2097 $field = 'user_ip';
2098 $id = $this->getName();
2099 } else {
2100 $field = 'user_id';
2101 $id = $this->getId();
2103 global $wgMemc;
2105 if ( $val ) {
2106 $changed = $this->updateNewtalk( $field, $id, $curRev );
2107 } else {
2108 $changed = $this->deleteNewtalk( $field, $id );
2111 if ( $this->isAnon() ) {
2112 // Anons have a separate memcached space, since
2113 // user records aren't kept for them.
2114 $key = wfMemcKey( 'newtalk', 'ip', $id );
2115 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
2117 if ( $changed ) {
2118 $this->invalidateCache();
2123 * Generate a current or new-future timestamp to be stored in the
2124 * user_touched field when we update things.
2125 * @return string Timestamp in TS_MW format
2127 private static function newTouchedTimestamp() {
2128 global $wgClockSkewFudge;
2129 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
2133 * Clear user data from memcached.
2134 * Use after applying fun updates to the database; caller's
2135 * responsibility to update user_touched if appropriate.
2137 * Called implicitly from invalidateCache() and saveSettings().
2139 private function clearSharedCache() {
2140 $this->load();
2141 if ( $this->mId ) {
2142 global $wgMemc;
2143 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
2148 * Immediately touch the user data cache for this account.
2149 * Updates user_touched field, and removes account data from memcached
2150 * for reload on the next hit.
2152 public function invalidateCache() {
2153 if ( wfReadOnly() ) {
2154 return;
2156 $this->load();
2157 if ( $this->mId ) {
2158 $this->mTouched = self::newTouchedTimestamp();
2160 $dbw = wfGetDB( DB_MASTER );
2161 $userid = $this->mId;
2162 $touched = $this->mTouched;
2163 $method = __METHOD__;
2164 $dbw->onTransactionIdle( function() use ( $dbw, $userid, $touched, $method ) {
2165 // Prevent contention slams by checking user_touched first
2166 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2167 $needsPurge = $dbw->selectField( 'user', '1',
2168 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2169 if ( $needsPurge ) {
2170 $dbw->update( 'user',
2171 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2172 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2173 $method
2176 } );
2177 $this->clearSharedCache();
2182 * Validate the cache for this account.
2183 * @param string $timestamp A timestamp in TS_MW format
2184 * @return bool
2186 public function validateCache( $timestamp ) {
2187 $this->load();
2188 return ( $timestamp >= $this->mTouched );
2192 * Get the user touched timestamp
2193 * @return string timestamp
2195 public function getTouched() {
2196 $this->load();
2197 return $this->mTouched;
2201 * Set the password and reset the random token.
2202 * Calls through to authentication plugin if necessary;
2203 * will have no effect if the auth plugin refuses to
2204 * pass the change through or if the legal password
2205 * checks fail.
2207 * As a special case, setting the password to null
2208 * wipes it, so the account cannot be logged in until
2209 * a new password is set, for instance via e-mail.
2211 * @param string $str New password to set
2212 * @throws PasswordError on failure
2214 * @return bool
2216 public function setPassword( $str ) {
2217 global $wgAuth;
2219 if ( $str !== null ) {
2220 if ( !$wgAuth->allowPasswordChange() ) {
2221 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2224 if ( !$this->isValidPassword( $str ) ) {
2225 global $wgMinimalPasswordLength;
2226 $valid = $this->getPasswordValidity( $str );
2227 if ( is_array( $valid ) ) {
2228 $message = array_shift( $valid );
2229 $params = $valid;
2230 } else {
2231 $message = $valid;
2232 $params = array( $wgMinimalPasswordLength );
2234 throw new PasswordError( wfMessage( $message, $params )->text() );
2238 if ( !$wgAuth->setPassword( $this, $str ) ) {
2239 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2242 $this->setInternalPassword( $str );
2244 return true;
2248 * Set the password and reset the random token unconditionally.
2250 * @param string|null $str New password to set or null to set an invalid
2251 * password hash meaning that the user will not be able to log in
2252 * through the web interface.
2254 public function setInternalPassword( $str ) {
2255 $this->load();
2256 $this->setToken();
2258 if ( $str === null ) {
2259 // Save an invalid hash...
2260 $this->mPassword = '';
2261 } else {
2262 $this->mPassword = self::crypt( $str );
2264 $this->mNewpassword = '';
2265 $this->mNewpassTime = null;
2269 * Get the user's current token.
2270 * @param bool $forceCreation Force the generation of a new token if the user doesn't have one (default=true for backwards compatibility)
2271 * @return string Token
2273 public function getToken( $forceCreation = true ) {
2274 $this->load();
2275 if ( !$this->mToken && $forceCreation ) {
2276 $this->setToken();
2278 return $this->mToken;
2282 * Set the random token (used for persistent authentication)
2283 * Called from loadDefaults() among other places.
2285 * @param string|bool $token If specified, set the token to this value
2287 public function setToken( $token = false ) {
2288 $this->load();
2289 if ( !$token ) {
2290 $this->mToken = MWCryptRand::generateHex( USER_TOKEN_LENGTH );
2291 } else {
2292 $this->mToken = $token;
2297 * Set the password for a password reminder or new account email
2299 * @param $str New password to set or null to set an invalid
2300 * password hash meaning that the user will not be able to use it
2301 * @param bool $throttle If true, reset the throttle timestamp to the present
2303 public function setNewpassword( $str, $throttle = true ) {
2304 $this->load();
2306 if ( $str === null ) {
2307 $this->mNewpassword = '';
2308 $this->mNewpassTime = null;
2309 } else {
2310 $this->mNewpassword = self::crypt( $str );
2311 if ( $throttle ) {
2312 $this->mNewpassTime = wfTimestampNow();
2318 * Has password reminder email been sent within the last
2319 * $wgPasswordReminderResendTime hours?
2320 * @return bool
2322 public function isPasswordReminderThrottled() {
2323 global $wgPasswordReminderResendTime;
2324 $this->load();
2325 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
2326 return false;
2328 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
2329 return time() < $expiry;
2333 * Get the user's e-mail address
2334 * @return string User's email address
2336 public function getEmail() {
2337 $this->load();
2338 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
2339 return $this->mEmail;
2343 * Get the timestamp of the user's e-mail authentication
2344 * @return string TS_MW timestamp
2346 public function getEmailAuthenticationTimestamp() {
2347 $this->load();
2348 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2349 return $this->mEmailAuthenticated;
2353 * Set the user's e-mail address
2354 * @param string $str New e-mail address
2356 public function setEmail( $str ) {
2357 $this->load();
2358 if ( $str == $this->mEmail ) {
2359 return;
2361 $this->mEmail = $str;
2362 $this->invalidateEmail();
2363 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
2367 * Set the user's e-mail address and a confirmation mail if needed.
2369 * @since 1.20
2370 * @param string $str New e-mail address
2371 * @return Status
2373 public function setEmailWithConfirmation( $str ) {
2374 global $wgEnableEmail, $wgEmailAuthentication;
2376 if ( !$wgEnableEmail ) {
2377 return Status::newFatal( 'emaildisabled' );
2380 $oldaddr = $this->getEmail();
2381 if ( $str === $oldaddr ) {
2382 return Status::newGood( true );
2385 $this->setEmail( $str );
2387 if ( $str !== '' && $wgEmailAuthentication ) {
2388 // Send a confirmation request to the new address if needed
2389 $type = $oldaddr != '' ? 'changed' : 'set';
2390 $result = $this->sendConfirmationMail( $type );
2391 if ( $result->isGood() ) {
2392 // Say the the caller that a confirmation mail has been sent
2393 $result->value = 'eauth';
2395 } else {
2396 $result = Status::newGood( true );
2399 return $result;
2403 * Get the user's real name
2404 * @return string User's real name
2406 public function getRealName() {
2407 if ( !$this->isItemLoaded( 'realname' ) ) {
2408 $this->load();
2411 return $this->mRealName;
2415 * Set the user's real name
2416 * @param string $str New real name
2418 public function setRealName( $str ) {
2419 $this->load();
2420 $this->mRealName = $str;
2424 * Get the user's current setting for a given option.
2426 * @param string $oname The option to check
2427 * @param string $defaultOverride A default value returned if the option does not exist
2428 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2429 * @return string User's current value for the option
2430 * @see getBoolOption()
2431 * @see getIntOption()
2433 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2434 global $wgHiddenPrefs;
2435 $this->loadOptions();
2437 # We want 'disabled' preferences to always behave as the default value for
2438 # users, even if they have set the option explicitly in their settings (ie they
2439 # set it, and then it was disabled removing their ability to change it). But
2440 # we don't want to erase the preferences in the database in case the preference
2441 # is re-enabled again. So don't touch $mOptions, just override the returned value
2442 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2443 return self::getDefaultOption( $oname );
2446 if ( array_key_exists( $oname, $this->mOptions ) ) {
2447 return $this->mOptions[$oname];
2448 } else {
2449 return $defaultOverride;
2454 * Get all user's options
2456 * @return array
2458 public function getOptions() {
2459 global $wgHiddenPrefs;
2460 $this->loadOptions();
2461 $options = $this->mOptions;
2463 # We want 'disabled' preferences to always behave as the default value for
2464 # users, even if they have set the option explicitly in their settings (ie they
2465 # set it, and then it was disabled removing their ability to change it). But
2466 # we don't want to erase the preferences in the database in case the preference
2467 # is re-enabled again. So don't touch $mOptions, just override the returned value
2468 foreach ( $wgHiddenPrefs as $pref ) {
2469 $default = self::getDefaultOption( $pref );
2470 if ( $default !== null ) {
2471 $options[$pref] = $default;
2475 return $options;
2479 * Get the user's current setting for a given option, as a boolean value.
2481 * @param string $oname The option to check
2482 * @return bool User's current value for the option
2483 * @see getOption()
2485 public function getBoolOption( $oname ) {
2486 return (bool)$this->getOption( $oname );
2490 * Get the user's current setting for a given option, as an integer value.
2492 * @param string $oname The option to check
2493 * @param int $defaultOverride A default value returned if the option does not exist
2494 * @return int User's current value for the option
2495 * @see getOption()
2497 public function getIntOption( $oname, $defaultOverride = 0 ) {
2498 $val = $this->getOption( $oname );
2499 if ( $val == '' ) {
2500 $val = $defaultOverride;
2502 return intval( $val );
2506 * Set the given option for a user.
2508 * @param string $oname The option to set
2509 * @param mixed $val New value to set
2511 public function setOption( $oname, $val ) {
2512 $this->loadOptions();
2514 // Explicitly NULL values should refer to defaults
2515 if ( is_null( $val ) ) {
2516 $val = self::getDefaultOption( $oname );
2519 $this->mOptions[$oname] = $val;
2523 * Get a token stored in the preferences (like the watchlist one),
2524 * resetting it if it's empty (and saving changes).
2526 * @param string $oname The option name to retrieve the token from
2527 * @return string|bool User's current value for the option, or false if this option is disabled.
2528 * @see resetTokenFromOption()
2529 * @see getOption()
2531 public function getTokenFromOption( $oname ) {
2532 global $wgHiddenPrefs;
2533 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2534 return false;
2537 $token = $this->getOption( $oname );
2538 if ( !$token ) {
2539 $token = $this->resetTokenFromOption( $oname );
2540 $this->saveSettings();
2542 return $token;
2546 * Reset a token stored in the preferences (like the watchlist one).
2547 * *Does not* save user's preferences (similarly to setOption()).
2549 * @param string $oname The option name to reset the token in
2550 * @return string|bool New token value, or false if this option is disabled.
2551 * @see getTokenFromOption()
2552 * @see setOption()
2554 public function resetTokenFromOption( $oname ) {
2555 global $wgHiddenPrefs;
2556 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2557 return false;
2560 $token = MWCryptRand::generateHex( 40 );
2561 $this->setOption( $oname, $token );
2562 return $token;
2566 * Return a list of the types of user options currently returned by
2567 * User::getOptionKinds().
2569 * Currently, the option kinds are:
2570 * - 'registered' - preferences which are registered in core MediaWiki or
2571 * by extensions using the UserGetDefaultOptions hook.
2572 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2573 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2574 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2575 * be used by user scripts.
2576 * - 'special' - "preferences" that are not accessible via User::getOptions
2577 * or User::setOptions.
2578 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2579 * These are usually legacy options, removed in newer versions.
2581 * The API (and possibly others) use this function to determine the possible
2582 * option types for validation purposes, so make sure to update this when a
2583 * new option kind is added.
2585 * @see User::getOptionKinds
2586 * @return array Option kinds
2588 public static function listOptionKinds() {
2589 return array(
2590 'registered',
2591 'registered-multiselect',
2592 'registered-checkmatrix',
2593 'userjs',
2594 'special',
2595 'unused'
2600 * Return an associative array mapping preferences keys to the kind of a preference they're
2601 * used for. Different kinds are handled differently when setting or reading preferences.
2603 * See User::listOptionKinds for the list of valid option types that can be provided.
2605 * @see User::listOptionKinds
2606 * @param $context IContextSource
2607 * @param array $options assoc. array with options keys to check as keys. Defaults to $this->mOptions.
2608 * @return array the key => kind mapping data
2610 public function getOptionKinds( IContextSource $context, $options = null ) {
2611 $this->loadOptions();
2612 if ( $options === null ) {
2613 $options = $this->mOptions;
2616 $prefs = Preferences::getPreferences( $this, $context );
2617 $mapping = array();
2619 // Pull out the "special" options, so they don't get converted as
2620 // multiselect or checkmatrix.
2621 $specialOptions = array_fill_keys( Preferences::getSaveBlacklist(), true );
2622 foreach ( $specialOptions as $name => $value ) {
2623 unset( $prefs[$name] );
2626 // Multiselect and checkmatrix options are stored in the database with
2627 // one key per option, each having a boolean value. Extract those keys.
2628 $multiselectOptions = array();
2629 foreach ( $prefs as $name => $info ) {
2630 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2631 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2632 $opts = HTMLFormField::flattenOptions( $info['options'] );
2633 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2635 foreach ( $opts as $value ) {
2636 $multiselectOptions["$prefix$value"] = true;
2639 unset( $prefs[$name] );
2642 $checkmatrixOptions = array();
2643 foreach ( $prefs as $name => $info ) {
2644 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2645 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2646 $columns = HTMLFormField::flattenOptions( $info['columns'] );
2647 $rows = HTMLFormField::flattenOptions( $info['rows'] );
2648 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2650 foreach ( $columns as $column ) {
2651 foreach ( $rows as $row ) {
2652 $checkmatrixOptions["$prefix-$column-$row"] = true;
2656 unset( $prefs[$name] );
2660 // $value is ignored
2661 foreach ( $options as $key => $value ) {
2662 if ( isset( $prefs[$key] ) ) {
2663 $mapping[$key] = 'registered';
2664 } elseif ( isset( $multiselectOptions[$key] ) ) {
2665 $mapping[$key] = 'registered-multiselect';
2666 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2667 $mapping[$key] = 'registered-checkmatrix';
2668 } elseif ( isset( $specialOptions[$key] ) ) {
2669 $mapping[$key] = 'special';
2670 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2671 $mapping[$key] = 'userjs';
2672 } else {
2673 $mapping[$key] = 'unused';
2677 return $mapping;
2681 * Reset certain (or all) options to the site defaults
2683 * The optional parameter determines which kinds of preferences will be reset.
2684 * Supported values are everything that can be reported by getOptionKinds()
2685 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2687 * @param array|string $resetKinds which kinds of preferences to reset. Defaults to
2688 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2689 * for backwards-compatibility.
2690 * @param $context IContextSource|null context source used when $resetKinds
2691 * does not contain 'all', passed to getOptionKinds().
2692 * Defaults to RequestContext::getMain() when null.
2694 public function resetOptions(
2695 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2696 IContextSource $context = null
2698 $this->load();
2699 $defaultOptions = self::getDefaultOptions();
2701 if ( !is_array( $resetKinds ) ) {
2702 $resetKinds = array( $resetKinds );
2705 if ( in_array( 'all', $resetKinds ) ) {
2706 $newOptions = $defaultOptions;
2707 } else {
2708 if ( $context === null ) {
2709 $context = RequestContext::getMain();
2712 $optionKinds = $this->getOptionKinds( $context );
2713 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
2714 $newOptions = array();
2716 // Use default values for the options that should be deleted, and
2717 // copy old values for the ones that shouldn't.
2718 foreach ( $this->mOptions as $key => $value ) {
2719 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2720 if ( array_key_exists( $key, $defaultOptions ) ) {
2721 $newOptions[$key] = $defaultOptions[$key];
2723 } else {
2724 $newOptions[$key] = $value;
2729 $this->mOptions = $newOptions;
2730 $this->mOptionsLoaded = true;
2734 * Get the user's preferred date format.
2735 * @return string User's preferred date format
2737 public function getDatePreference() {
2738 // Important migration for old data rows
2739 if ( is_null( $this->mDatePreference ) ) {
2740 global $wgLang;
2741 $value = $this->getOption( 'date' );
2742 $map = $wgLang->getDatePreferenceMigrationMap();
2743 if ( isset( $map[$value] ) ) {
2744 $value = $map[$value];
2746 $this->mDatePreference = $value;
2748 return $this->mDatePreference;
2752 * Determine based on the wiki configuration and the user's options,
2753 * whether this user must be over HTTPS no matter what.
2755 * @return bool
2757 public function requiresHTTPS() {
2758 global $wgSecureLogin;
2759 if ( !$wgSecureLogin ) {
2760 return false;
2761 } else {
2762 $https = $this->getBoolOption( 'prefershttps' );
2763 wfRunHooks( 'UserRequiresHTTPS', array( $this, &$https ) );
2764 if ( $https ) {
2765 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2767 return $https;
2772 * Get the user preferred stub threshold
2774 * @return int
2776 public function getStubThreshold() {
2777 global $wgMaxArticleSize; # Maximum article size, in Kb
2778 $threshold = $this->getIntOption( 'stubthreshold' );
2779 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2780 // If they have set an impossible value, disable the preference
2781 // so we can use the parser cache again.
2782 $threshold = 0;
2784 return $threshold;
2788 * Get the permissions this user has.
2789 * @return Array of String permission names
2791 public function getRights() {
2792 if ( is_null( $this->mRights ) ) {
2793 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2794 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
2795 // Force reindexation of rights when a hook has unset one of them
2796 $this->mRights = array_values( array_unique( $this->mRights ) );
2798 return $this->mRights;
2802 * Get the list of explicit group memberships this user has.
2803 * The implicit * and user groups are not included.
2804 * @return Array of String internal group names
2806 public function getGroups() {
2807 $this->load();
2808 $this->loadGroups();
2809 return $this->mGroups;
2813 * Get the list of implicit group memberships this user has.
2814 * This includes all explicit groups, plus 'user' if logged in,
2815 * '*' for all accounts, and autopromoted groups
2816 * @param bool $recache Whether to avoid the cache
2817 * @return Array of String internal group names
2819 public function getEffectiveGroups( $recache = false ) {
2820 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
2821 wfProfileIn( __METHOD__ );
2822 $this->mEffectiveGroups = array_unique( array_merge(
2823 $this->getGroups(), // explicit groups
2824 $this->getAutomaticGroups( $recache ) // implicit groups
2825 ) );
2826 // Hook for additional groups
2827 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
2828 // Force reindexation of groups when a hook has unset one of them
2829 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
2830 wfProfileOut( __METHOD__ );
2832 return $this->mEffectiveGroups;
2836 * Get the list of implicit group memberships this user has.
2837 * This includes 'user' if logged in, '*' for all accounts,
2838 * and autopromoted groups
2839 * @param bool $recache Whether to avoid the cache
2840 * @return Array of String internal group names
2842 public function getAutomaticGroups( $recache = false ) {
2843 if ( $recache || is_null( $this->mImplicitGroups ) ) {
2844 wfProfileIn( __METHOD__ );
2845 $this->mImplicitGroups = array( '*' );
2846 if ( $this->getId() ) {
2847 $this->mImplicitGroups[] = 'user';
2849 $this->mImplicitGroups = array_unique( array_merge(
2850 $this->mImplicitGroups,
2851 Autopromote::getAutopromoteGroups( $this )
2852 ) );
2854 if ( $recache ) {
2855 // Assure data consistency with rights/groups,
2856 // as getEffectiveGroups() depends on this function
2857 $this->mEffectiveGroups = null;
2859 wfProfileOut( __METHOD__ );
2861 return $this->mImplicitGroups;
2865 * Returns the groups the user has belonged to.
2867 * The user may still belong to the returned groups. Compare with getGroups().
2869 * The function will not return groups the user had belonged to before MW 1.17
2871 * @return array Names of the groups the user has belonged to.
2873 public function getFormerGroups() {
2874 if ( is_null( $this->mFormerGroups ) ) {
2875 $dbr = wfGetDB( DB_MASTER );
2876 $res = $dbr->select( 'user_former_groups',
2877 array( 'ufg_group' ),
2878 array( 'ufg_user' => $this->mId ),
2879 __METHOD__ );
2880 $this->mFormerGroups = array();
2881 foreach ( $res as $row ) {
2882 $this->mFormerGroups[] = $row->ufg_group;
2885 return $this->mFormerGroups;
2889 * Get the user's edit count.
2890 * @return int, null for anonymous users
2892 public function getEditCount() {
2893 if ( !$this->getId() ) {
2894 return null;
2897 if ( !isset( $this->mEditCount ) ) {
2898 /* Populate the count, if it has not been populated yet */
2899 wfProfileIn( __METHOD__ );
2900 $dbr = wfGetDB( DB_SLAVE );
2901 // check if the user_editcount field has been initialized
2902 $count = $dbr->selectField(
2903 'user', 'user_editcount',
2904 array( 'user_id' => $this->mId ),
2905 __METHOD__
2908 if ( $count === null ) {
2909 // it has not been initialized. do so.
2910 $count = $this->initEditCount();
2912 $this->mEditCount = $count;
2913 wfProfileOut( __METHOD__ );
2915 return (int)$this->mEditCount;
2919 * Add the user to the given group.
2920 * This takes immediate effect.
2921 * @param string $group Name of the group to add
2923 public function addGroup( $group ) {
2924 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2925 $dbw = wfGetDB( DB_MASTER );
2926 if ( $this->getId() ) {
2927 $dbw->insert( 'user_groups',
2928 array(
2929 'ug_user' => $this->getID(),
2930 'ug_group' => $group,
2932 __METHOD__,
2933 array( 'IGNORE' ) );
2936 $this->loadGroups();
2937 $this->mGroups[] = $group;
2938 // In case loadGroups was not called before, we now have the right twice.
2939 // Get rid of the duplicate.
2940 $this->mGroups = array_unique( $this->mGroups );
2942 // Refresh the groups caches, and clear the rights cache so it will be
2943 // refreshed on the next call to $this->getRights().
2944 $this->getEffectiveGroups( true );
2945 $this->mRights = null;
2947 $this->invalidateCache();
2951 * Remove the user from the given group.
2952 * This takes immediate effect.
2953 * @param string $group Name of the group to remove
2955 public function removeGroup( $group ) {
2956 $this->load();
2957 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
2958 $dbw = wfGetDB( DB_MASTER );
2959 $dbw->delete( 'user_groups',
2960 array(
2961 'ug_user' => $this->getID(),
2962 'ug_group' => $group,
2963 ), __METHOD__ );
2964 // Remember that the user was in this group
2965 $dbw->insert( 'user_former_groups',
2966 array(
2967 'ufg_user' => $this->getID(),
2968 'ufg_group' => $group,
2970 __METHOD__,
2971 array( 'IGNORE' ) );
2973 $this->loadGroups();
2974 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
2976 // Refresh the groups caches, and clear the rights cache so it will be
2977 // refreshed on the next call to $this->getRights().
2978 $this->getEffectiveGroups( true );
2979 $this->mRights = null;
2981 $this->invalidateCache();
2985 * Get whether the user is logged in
2986 * @return bool
2988 public function isLoggedIn() {
2989 return $this->getID() != 0;
2993 * Get whether the user is anonymous
2994 * @return bool
2996 public function isAnon() {
2997 return !$this->isLoggedIn();
3001 * Check if user is allowed to access a feature / make an action
3003 * @internal param \String $varargs permissions to test
3004 * @return boolean: True if user is allowed to perform *any* of the given actions
3006 * @return bool
3008 public function isAllowedAny( /*...*/ ) {
3009 $permissions = func_get_args();
3010 foreach ( $permissions as $permission ) {
3011 if ( $this->isAllowed( $permission ) ) {
3012 return true;
3015 return false;
3020 * @internal param $varargs string
3021 * @return bool True if the user is allowed to perform *all* of the given actions
3023 public function isAllowedAll( /*...*/ ) {
3024 $permissions = func_get_args();
3025 foreach ( $permissions as $permission ) {
3026 if ( !$this->isAllowed( $permission ) ) {
3027 return false;
3030 return true;
3034 * Internal mechanics of testing a permission
3035 * @param string $action
3036 * @return bool
3038 public function isAllowed( $action = '' ) {
3039 if ( $action === '' ) {
3040 return true; // In the spirit of DWIM
3042 // Patrolling may not be enabled
3043 if ( $action === 'patrol' || $action === 'autopatrol' ) {
3044 global $wgUseRCPatrol, $wgUseNPPatrol;
3045 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3046 return false;
3049 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3050 // by misconfiguration: 0 == 'foo'
3051 return in_array( $action, $this->getRights(), true );
3055 * Check whether to enable recent changes patrol features for this user
3056 * @return boolean: True or false
3058 public function useRCPatrol() {
3059 global $wgUseRCPatrol;
3060 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3064 * Check whether to enable new pages patrol features for this user
3065 * @return bool True or false
3067 public function useNPPatrol() {
3068 global $wgUseRCPatrol, $wgUseNPPatrol;
3069 return (
3070 ( $wgUseRCPatrol || $wgUseNPPatrol )
3071 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3076 * Get the WebRequest object to use with this object
3078 * @return WebRequest
3080 public function getRequest() {
3081 if ( $this->mRequest ) {
3082 return $this->mRequest;
3083 } else {
3084 global $wgRequest;
3085 return $wgRequest;
3090 * Get the current skin, loading it if required
3091 * @return Skin The current skin
3092 * @todo FIXME: Need to check the old failback system [AV]
3093 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3095 public function getSkin() {
3096 wfDeprecated( __METHOD__, '1.18' );
3097 return RequestContext::getMain()->getSkin();
3101 * Get a WatchedItem for this user and $title.
3103 * @since 1.22 $checkRights parameter added
3104 * @param $title Title
3105 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3106 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3107 * @return WatchedItem
3109 public function getWatchedItem( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3110 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3112 if ( isset( $this->mWatchedItems[$key] ) ) {
3113 return $this->mWatchedItems[$key];
3116 if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
3117 $this->mWatchedItems = array();
3120 $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title, $checkRights );
3121 return $this->mWatchedItems[$key];
3125 * Check the watched status of an article.
3126 * @since 1.22 $checkRights parameter added
3127 * @param $title Title of the article to look at
3128 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3129 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3130 * @return bool
3132 public function isWatched( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3133 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3137 * Watch an article.
3138 * @since 1.22 $checkRights parameter added
3139 * @param $title Title of the article to look at
3140 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3141 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3143 public function addWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3144 $this->getWatchedItem( $title, $checkRights )->addWatch();
3145 $this->invalidateCache();
3149 * Stop watching an article.
3150 * @since 1.22 $checkRights parameter added
3151 * @param $title Title of the article to look at
3152 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3153 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3155 public function removeWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3156 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3157 $this->invalidateCache();
3161 * Clear the user's notification timestamp for the given title.
3162 * If e-notif e-mails are on, they will receive notification mails on
3163 * the next change of the page if it's watched etc.
3164 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3165 * @param $title Title of the article to look at
3166 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3168 public function clearNotification( &$title, $oldid = 0 ) {
3169 global $wgUseEnotif, $wgShowUpdatedMarker;
3171 // Do nothing if the database is locked to writes
3172 if ( wfReadOnly() ) {
3173 return;
3176 // Do nothing if not allowed to edit the watchlist
3177 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3178 return;
3181 // If we're working on user's talk page, we should update the talk page message indicator
3182 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3183 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3184 return;
3187 $nextid = $oldid ? $title->getNextRevisionID( $oldid ) : null;
3189 if ( !$oldid || !$nextid ) {
3190 // If we're looking at the latest revision, we should definitely clear it
3191 $this->setNewtalk( false );
3192 } else {
3193 // Otherwise we should update its revision, if it's present
3194 if ( $this->getNewtalk() ) {
3195 // Naturally the other one won't clear by itself
3196 $this->setNewtalk( false );
3197 $this->setNewtalk( true, Revision::newFromId( $nextid ) );
3202 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3203 return;
3206 if ( $this->isAnon() ) {
3207 // Nothing else to do...
3208 return;
3211 // Only update the timestamp if the page is being watched.
3212 // The query to find out if it is watched is cached both in memcached and per-invocation,
3213 // and when it does have to be executed, it can be on a slave
3214 // If this is the user's newtalk page, we always update the timestamp
3215 $force = '';
3216 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3217 $force = 'force';
3220 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3224 * Resets all of the given user's page-change notification timestamps.
3225 * If e-notif e-mails are on, they will receive notification mails on
3226 * the next change of any watched page.
3227 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3229 public function clearAllNotifications() {
3230 if ( wfReadOnly() ) {
3231 return;
3234 // Do nothing if not allowed to edit the watchlist
3235 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3236 return;
3239 global $wgUseEnotif, $wgShowUpdatedMarker;
3240 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3241 $this->setNewtalk( false );
3242 return;
3244 $id = $this->getId();
3245 if ( $id != 0 ) {
3246 $dbw = wfGetDB( DB_MASTER );
3247 $dbw->update( 'watchlist',
3248 array( /* SET */ 'wl_notificationtimestamp' => null ),
3249 array( /* WHERE */ 'wl_user' => $id ),
3250 __METHOD__
3252 // We also need to clear here the "you have new message" notification for the own user_talk page;
3253 // it's cleared one page view later in WikiPage::doViewUpdates().
3258 * Set this user's options from an encoded string
3259 * @param string $str Encoded options to import
3261 * @deprecated in 1.19 due to removal of user_options from the user table
3263 private function decodeOptions( $str ) {
3264 wfDeprecated( __METHOD__, '1.19' );
3265 if ( !$str ) {
3266 return;
3269 $this->mOptionsLoaded = true;
3270 $this->mOptionOverrides = array();
3272 // If an option is not set in $str, use the default value
3273 $this->mOptions = self::getDefaultOptions();
3275 $a = explode( "\n", $str );
3276 foreach ( $a as $s ) {
3277 $m = array();
3278 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
3279 $this->mOptions[$m[1]] = $m[2];
3280 $this->mOptionOverrides[$m[1]] = $m[2];
3286 * Set a cookie on the user's client. Wrapper for
3287 * WebResponse::setCookie
3288 * @param string $name Name of the cookie to set
3289 * @param string $value Value to set
3290 * @param int $exp Expiration time, as a UNIX time value;
3291 * if 0 or not specified, use the default $wgCookieExpiration
3292 * @param bool $secure
3293 * true: Force setting the secure attribute when setting the cookie
3294 * false: Force NOT setting the secure attribute when setting the cookie
3295 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3296 * @param array $params Array of options sent passed to WebResponse::setcookie()
3298 protected function setCookie( $name, $value, $exp = 0, $secure = null, $params = array() ) {
3299 $params['secure'] = $secure;
3300 $this->getRequest()->response()->setcookie( $name, $value, $exp, $params );
3304 * Clear a cookie on the user's client
3305 * @param string $name Name of the cookie to clear
3306 * @param bool $secure
3307 * true: Force setting the secure attribute when setting the cookie
3308 * false: Force NOT setting the secure attribute when setting the cookie
3309 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3310 * @param array $params Array of options sent passed to WebResponse::setcookie()
3312 protected function clearCookie( $name, $secure = null, $params = array() ) {
3313 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3317 * Set the default cookies for this session on the user's client.
3319 * @param $request WebRequest object to use; $wgRequest will be used if null
3320 * is passed.
3321 * @param bool $secure Whether to force secure/insecure cookies or use default
3322 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3324 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3325 if ( $request === null ) {
3326 $request = $this->getRequest();
3329 $this->load();
3330 if ( 0 == $this->mId ) {
3331 return;
3333 if ( !$this->mToken ) {
3334 // When token is empty or NULL generate a new one and then save it to the database
3335 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3336 // Simply by setting every cell in the user_token column to NULL and letting them be
3337 // regenerated as users log back into the wiki.
3338 $this->setToken();
3339 $this->saveSettings();
3341 $session = array(
3342 'wsUserID' => $this->mId,
3343 'wsToken' => $this->mToken,
3344 'wsUserName' => $this->getName()
3346 $cookies = array(
3347 'UserID' => $this->mId,
3348 'UserName' => $this->getName(),
3350 if ( $rememberMe ) {
3351 $cookies['Token'] = $this->mToken;
3352 } else {
3353 $cookies['Token'] = false;
3356 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3358 foreach ( $session as $name => $value ) {
3359 $request->setSessionData( $name, $value );
3361 foreach ( $cookies as $name => $value ) {
3362 if ( $value === false ) {
3363 $this->clearCookie( $name );
3364 } else {
3365 $this->setCookie( $name, $value, 0, $secure );
3370 * If wpStickHTTPS was selected, also set an insecure cookie that
3371 * will cause the site to redirect the user to HTTPS, if they access
3372 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3373 * as the one set by centralauth (bug 53538). Also set it to session, or
3374 * standard time setting, based on if rememberme was set.
3376 if ( $request->getCheck( 'wpStickHTTPS' ) || $this->requiresHTTPS() ) {
3377 $this->setCookie(
3378 'forceHTTPS',
3379 'true',
3380 $rememberMe ? 0 : null,
3381 false,
3382 array( 'prefix' => '' ) // no prefix
3388 * Log this user out.
3390 public function logout() {
3391 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3392 $this->doLogout();
3397 * Clear the user's cookies and session, and reset the instance cache.
3398 * @see logout()
3400 public function doLogout() {
3401 $this->clearInstanceCache( 'defaults' );
3403 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3405 $this->clearCookie( 'UserID' );
3406 $this->clearCookie( 'Token' );
3407 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3409 // Remember when user logged out, to prevent seeing cached pages
3410 $this->setCookie( 'LoggedOut', time(), time() + 86400 );
3414 * Save this user's settings into the database.
3415 * @todo Only rarely do all these fields need to be set!
3417 public function saveSettings() {
3418 global $wgAuth;
3420 $this->load();
3421 if ( wfReadOnly() ) {
3422 return;
3424 if ( 0 == $this->mId ) {
3425 return;
3428 $this->mTouched = self::newTouchedTimestamp();
3429 if ( !$wgAuth->allowSetLocalPassword() ) {
3430 $this->mPassword = '';
3433 $dbw = wfGetDB( DB_MASTER );
3434 $dbw->update( 'user',
3435 array( /* SET */
3436 'user_name' => $this->mName,
3437 'user_password' => $this->mPassword,
3438 'user_newpassword' => $this->mNewpassword,
3439 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3440 'user_real_name' => $this->mRealName,
3441 'user_email' => $this->mEmail,
3442 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3443 'user_touched' => $dbw->timestamp( $this->mTouched ),
3444 'user_token' => strval( $this->mToken ),
3445 'user_email_token' => $this->mEmailToken,
3446 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3447 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires ),
3448 ), array( /* WHERE */
3449 'user_id' => $this->mId
3450 ), __METHOD__
3453 $this->saveOptions();
3455 wfRunHooks( 'UserSaveSettings', array( $this ) );
3456 $this->clearSharedCache();
3457 $this->getUserPage()->invalidateCache();
3461 * If only this user's username is known, and it exists, return the user ID.
3462 * @return int
3464 public function idForName() {
3465 $s = trim( $this->getName() );
3466 if ( $s === '' ) {
3467 return 0;
3470 $dbr = wfGetDB( DB_SLAVE );
3471 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
3472 if ( $id === false ) {
3473 $id = 0;
3475 return $id;
3479 * Add a user to the database, return the user object
3481 * @param string $name Username to add
3482 * @param array $params of Strings Non-default parameters to save to the database as user_* fields:
3483 * - password The user's password hash. Password logins will be disabled if this is omitted.
3484 * - newpassword Hash for a temporary password that has been mailed to the user
3485 * - email The user's email address
3486 * - email_authenticated The email authentication timestamp
3487 * - real_name The user's real name
3488 * - options An associative array of non-default options
3489 * - token Random authentication token. Do not set.
3490 * - registration Registration timestamp. Do not set.
3492 * @return User object, or null if the username already exists
3494 public static function createNew( $name, $params = array() ) {
3495 $user = new User;
3496 $user->load();
3497 $user->setToken(); // init token
3498 if ( isset( $params['options'] ) ) {
3499 $user->mOptions = $params['options'] + (array)$user->mOptions;
3500 unset( $params['options'] );
3502 $dbw = wfGetDB( DB_MASTER );
3503 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3505 $fields = array(
3506 'user_id' => $seqVal,
3507 'user_name' => $name,
3508 'user_password' => $user->mPassword,
3509 'user_newpassword' => $user->mNewpassword,
3510 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
3511 'user_email' => $user->mEmail,
3512 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3513 'user_real_name' => $user->mRealName,
3514 'user_token' => strval( $user->mToken ),
3515 'user_registration' => $dbw->timestamp( $user->mRegistration ),
3516 'user_editcount' => 0,
3517 'user_touched' => $dbw->timestamp( self::newTouchedTimestamp() ),
3519 foreach ( $params as $name => $value ) {
3520 $fields["user_$name"] = $value;
3522 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
3523 if ( $dbw->affectedRows() ) {
3524 $newUser = User::newFromId( $dbw->insertId() );
3525 } else {
3526 $newUser = null;
3528 return $newUser;
3532 * Add this existing user object to the database. If the user already
3533 * exists, a fatal status object is returned, and the user object is
3534 * initialised with the data from the database.
3536 * Previously, this function generated a DB error due to a key conflict
3537 * if the user already existed. Many extension callers use this function
3538 * in code along the lines of:
3540 * $user = User::newFromName( $name );
3541 * if ( !$user->isLoggedIn() ) {
3542 * $user->addToDatabase();
3544 * // do something with $user...
3546 * However, this was vulnerable to a race condition (bug 16020). By
3547 * initialising the user object if the user exists, we aim to support this
3548 * calling sequence as far as possible.
3550 * Note that if the user exists, this function will acquire a write lock,
3551 * so it is still advisable to make the call conditional on isLoggedIn(),
3552 * and to commit the transaction after calling.
3554 * @throws MWException
3555 * @return Status
3557 public function addToDatabase() {
3558 $this->load();
3559 if ( !$this->mToken ) {
3560 $this->setToken(); // init token
3563 $this->mTouched = self::newTouchedTimestamp();
3565 $dbw = wfGetDB( DB_MASTER );
3566 $inWrite = $dbw->writesOrCallbacksPending();
3567 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3568 $dbw->insert( 'user',
3569 array(
3570 'user_id' => $seqVal,
3571 'user_name' => $this->mName,
3572 'user_password' => $this->mPassword,
3573 'user_newpassword' => $this->mNewpassword,
3574 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3575 'user_email' => $this->mEmail,
3576 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3577 'user_real_name' => $this->mRealName,
3578 'user_token' => strval( $this->mToken ),
3579 'user_registration' => $dbw->timestamp( $this->mRegistration ),
3580 'user_editcount' => 0,
3581 'user_touched' => $dbw->timestamp( $this->mTouched ),
3582 ), __METHOD__,
3583 array( 'IGNORE' )
3585 if ( !$dbw->affectedRows() ) {
3586 if ( !$inWrite ) {
3587 // XXX: Get out of REPEATABLE-READ so the SELECT below works.
3588 // Often this case happens early in views before any writes.
3589 // This shows up at least with CentralAuth.
3590 $dbw->commit( __METHOD__, 'flush' );
3592 $this->mId = $dbw->selectField( 'user', 'user_id',
3593 array( 'user_name' => $this->mName ), __METHOD__ );
3594 $loaded = false;
3595 if ( $this->mId ) {
3596 if ( $this->loadFromDatabase() ) {
3597 $loaded = true;
3600 if ( !$loaded ) {
3601 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
3602 "to insert user '{$this->mName}' row, but it was not present in select!" );
3604 return Status::newFatal( 'userexists' );
3606 $this->mId = $dbw->insertId();
3608 // Clear instance cache other than user table data, which is already accurate
3609 $this->clearInstanceCache();
3611 $this->saveOptions();
3612 return Status::newGood();
3616 * If this user is logged-in and blocked,
3617 * block any IP address they've successfully logged in from.
3618 * @return bool A block was spread
3620 public function spreadAnyEditBlock() {
3621 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3622 return $this->spreadBlock();
3624 return false;
3628 * If this (non-anonymous) user is blocked,
3629 * block the IP address they've successfully logged in from.
3630 * @return bool A block was spread
3632 protected function spreadBlock() {
3633 wfDebug( __METHOD__ . "()\n" );
3634 $this->load();
3635 if ( $this->mId == 0 ) {
3636 return false;
3639 $userblock = Block::newFromTarget( $this->getName() );
3640 if ( !$userblock ) {
3641 return false;
3644 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3648 * Get whether the user is explicitly blocked from account creation.
3649 * @return bool|Block
3651 public function isBlockedFromCreateAccount() {
3652 $this->getBlockedStatus();
3653 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
3654 return $this->mBlock;
3657 # bug 13611: if the IP address the user is trying to create an account from is
3658 # blocked with createaccount disabled, prevent new account creation there even
3659 # when the user is logged in
3660 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3661 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
3663 return $this->mBlockedFromCreateAccount instanceof Block && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
3664 ? $this->mBlockedFromCreateAccount
3665 : false;
3669 * Get whether the user is blocked from using Special:Emailuser.
3670 * @return bool
3672 public function isBlockedFromEmailuser() {
3673 $this->getBlockedStatus();
3674 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
3678 * Get whether the user is allowed to create an account.
3679 * @return bool
3681 public function isAllowedToCreateAccount() {
3682 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3686 * Get this user's personal page title.
3688 * @return Title: User's personal page title
3690 public function getUserPage() {
3691 return Title::makeTitle( NS_USER, $this->getName() );
3695 * Get this user's talk page title.
3697 * @return Title: User's talk page title
3699 public function getTalkPage() {
3700 $title = $this->getUserPage();
3701 return $title->getTalkPage();
3705 * Determine whether the user is a newbie. Newbies are either
3706 * anonymous IPs, or the most recently created accounts.
3707 * @return bool
3709 public function isNewbie() {
3710 return !$this->isAllowed( 'autoconfirmed' );
3714 * Check to see if the given clear-text password is one of the accepted passwords
3715 * @param string $password user password.
3716 * @return boolean: True if the given password is correct, otherwise False.
3718 public function checkPassword( $password ) {
3719 global $wgAuth, $wgLegacyEncoding;
3720 $this->load();
3722 // Certain authentication plugins do NOT want to save
3723 // domain passwords in a mysql database, so we should
3724 // check this (in case $wgAuth->strict() is false).
3726 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3727 return true;
3728 } elseif ( $wgAuth->strict() ) {
3729 // Auth plugin doesn't allow local authentication
3730 return false;
3731 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3732 // Auth plugin doesn't allow local authentication for this user name
3733 return false;
3735 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
3736 return true;
3737 } elseif ( $wgLegacyEncoding ) {
3738 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3739 // Check for this with iconv
3740 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3741 if ( $cp1252Password != $password
3742 && self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId )
3744 return true;
3747 return false;
3751 * Check if the given clear-text password matches the temporary password
3752 * sent by e-mail for password reset operations.
3754 * @param $plaintext string
3756 * @return boolean: True if matches, false otherwise
3758 public function checkTemporaryPassword( $plaintext ) {
3759 global $wgNewPasswordExpiry;
3761 $this->load();
3762 if ( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) {
3763 if ( is_null( $this->mNewpassTime ) ) {
3764 return true;
3766 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
3767 return ( time() < $expiry );
3768 } else {
3769 return false;
3774 * Alias for getEditToken.
3775 * @deprecated since 1.19, use getEditToken instead.
3777 * @param string|array $salt of Strings Optional function-specific data for hashing
3778 * @param $request WebRequest object to use or null to use $wgRequest
3779 * @return string The new edit token
3781 public function editToken( $salt = '', $request = null ) {
3782 wfDeprecated( __METHOD__, '1.19' );
3783 return $this->getEditToken( $salt, $request );
3787 * Initialize (if necessary) and return a session token value
3788 * which can be used in edit forms to show that the user's
3789 * login credentials aren't being hijacked with a foreign form
3790 * submission.
3792 * @since 1.19
3794 * @param string|array $salt of Strings Optional function-specific data for hashing
3795 * @param $request WebRequest object to use or null to use $wgRequest
3796 * @return string The new edit token
3798 public function getEditToken( $salt = '', $request = null ) {
3799 if ( $request == null ) {
3800 $request = $this->getRequest();
3803 if ( $this->isAnon() ) {
3804 return EDIT_TOKEN_SUFFIX;
3805 } else {
3806 $token = $request->getSessionData( 'wsEditToken' );
3807 if ( $token === null ) {
3808 $token = MWCryptRand::generateHex( 32 );
3809 $request->setSessionData( 'wsEditToken', $token );
3811 if ( is_array( $salt ) ) {
3812 $salt = implode( '|', $salt );
3814 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
3819 * Generate a looking random token for various uses.
3821 * @return string The new random token
3822 * @deprecated since 1.20: Use MWCryptRand for secure purposes or wfRandomString for pseudo-randomness
3824 public static function generateToken() {
3825 return MWCryptRand::generateHex( 32 );
3829 * Check given value against the token value stored in the session.
3830 * A match should confirm that the form was submitted from the
3831 * user's own login session, not a form submission from a third-party
3832 * site.
3834 * @param string $val Input value to compare
3835 * @param string $salt Optional function-specific data for hashing
3836 * @param WebRequest $request Object to use or null to use $wgRequest
3837 * @return boolean: Whether the token matches
3839 public function matchEditToken( $val, $salt = '', $request = null ) {
3840 $sessionToken = $this->getEditToken( $salt, $request );
3841 if ( $val != $sessionToken ) {
3842 wfDebug( "User::matchEditToken: broken session data\n" );
3844 return $val == $sessionToken;
3848 * Check given value against the token value stored in the session,
3849 * ignoring the suffix.
3851 * @param string $val Input value to compare
3852 * @param string $salt Optional function-specific data for hashing
3853 * @param WebRequest $request object to use or null to use $wgRequest
3854 * @return boolean: Whether the token matches
3856 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3857 $sessionToken = $this->getEditToken( $salt, $request );
3858 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3862 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3863 * mail to the user's given address.
3865 * @param string $type message to send, either "created", "changed" or "set"
3866 * @return Status object
3868 public function sendConfirmationMail( $type = 'created' ) {
3869 global $wgLang;
3870 $expiration = null; // gets passed-by-ref and defined in next line.
3871 $token = $this->confirmationToken( $expiration );
3872 $url = $this->confirmationTokenUrl( $token );
3873 $invalidateURL = $this->invalidationTokenUrl( $token );
3874 $this->saveSettings();
3876 if ( $type == 'created' || $type === false ) {
3877 $message = 'confirmemail_body';
3878 } elseif ( $type === true ) {
3879 $message = 'confirmemail_body_changed';
3880 } else {
3881 // Messages: confirmemail_body_changed, confirmemail_body_set
3882 $message = 'confirmemail_body_' . $type;
3885 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3886 wfMessage( $message,
3887 $this->getRequest()->getIP(),
3888 $this->getName(),
3889 $url,
3890 $wgLang->timeanddate( $expiration, false ),
3891 $invalidateURL,
3892 $wgLang->date( $expiration, false ),
3893 $wgLang->time( $expiration, false ) )->text() );
3897 * Send an e-mail to this user's account. Does not check for
3898 * confirmed status or validity.
3900 * @param string $subject Message subject
3901 * @param string $body Message body
3902 * @param string $from Optional From address; if unspecified, default $wgPasswordSender will be used
3903 * @param string $replyto Reply-To address
3904 * @return Status
3906 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3907 if ( is_null( $from ) ) {
3908 global $wgPasswordSender;
3909 $sender = new MailAddress( $wgPasswordSender,
3910 wfMessage( 'emailsender' )->inContentLanguage()->text() );
3911 } else {
3912 $sender = new MailAddress( $from );
3915 $to = new MailAddress( $this );
3916 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
3920 * Generate, store, and return a new e-mail confirmation code.
3921 * A hash (unsalted, since it's used as a key) is stored.
3923 * @note Call saveSettings() after calling this function to commit
3924 * this change to the database.
3926 * @param &$expiration \mixed Accepts the expiration time
3927 * @return string New token
3929 protected function confirmationToken( &$expiration ) {
3930 global $wgUserEmailConfirmationTokenExpiry;
3931 $now = time();
3932 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
3933 $expiration = wfTimestamp( TS_MW, $expires );
3934 $this->load();
3935 $token = MWCryptRand::generateHex( 32 );
3936 $hash = md5( $token );
3937 $this->mEmailToken = $hash;
3938 $this->mEmailTokenExpires = $expiration;
3939 return $token;
3943 * Return a URL the user can use to confirm their email address.
3944 * @param string $token Accepts the email confirmation token
3945 * @return string New token URL
3947 protected function confirmationTokenUrl( $token ) {
3948 return $this->getTokenUrl( 'ConfirmEmail', $token );
3952 * Return a URL the user can use to invalidate their email address.
3953 * @param string $token Accepts the email confirmation token
3954 * @return string New token URL
3956 protected function invalidationTokenUrl( $token ) {
3957 return $this->getTokenUrl( 'InvalidateEmail', $token );
3961 * Internal function to format the e-mail validation/invalidation URLs.
3962 * This uses a quickie hack to use the
3963 * hardcoded English names of the Special: pages, for ASCII safety.
3965 * @note Since these URLs get dropped directly into emails, using the
3966 * short English names avoids insanely long URL-encoded links, which
3967 * also sometimes can get corrupted in some browsers/mailers
3968 * (bug 6957 with Gmail and Internet Explorer).
3970 * @param string $page Special page
3971 * @param string $token Token
3972 * @return string Formatted URL
3974 protected function getTokenUrl( $page, $token ) {
3975 // Hack to bypass localization of 'Special:'
3976 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
3977 return $title->getCanonicalURL();
3981 * Mark the e-mail address confirmed.
3983 * @note Call saveSettings() after calling this function to commit the change.
3985 * @return bool
3987 public function confirmEmail() {
3988 // Check if it's already confirmed, so we don't touch the database
3989 // and fire the ConfirmEmailComplete hook on redundant confirmations.
3990 if ( !$this->isEmailConfirmed() ) {
3991 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3992 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3994 return true;
3998 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3999 * address if it was already confirmed.
4001 * @note Call saveSettings() after calling this function to commit the change.
4002 * @return bool Returns true
4004 public function invalidateEmail() {
4005 $this->load();
4006 $this->mEmailToken = null;
4007 $this->mEmailTokenExpires = null;
4008 $this->setEmailAuthenticationTimestamp( null );
4009 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
4010 return true;
4014 * Set the e-mail authentication timestamp.
4015 * @param string $timestamp TS_MW timestamp
4017 public function setEmailAuthenticationTimestamp( $timestamp ) {
4018 $this->load();
4019 $this->mEmailAuthenticated = $timestamp;
4020 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
4024 * Is this user allowed to send e-mails within limits of current
4025 * site configuration?
4026 * @return bool
4028 public function canSendEmail() {
4029 global $wgEnableEmail, $wgEnableUserEmail;
4030 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4031 return false;
4033 $canSend = $this->isEmailConfirmed();
4034 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
4035 return $canSend;
4039 * Is this user allowed to receive e-mails within limits of current
4040 * site configuration?
4041 * @return bool
4043 public function canReceiveEmail() {
4044 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4048 * Is this user's e-mail address valid-looking and confirmed within
4049 * limits of the current site configuration?
4051 * @note If $wgEmailAuthentication is on, this may require the user to have
4052 * confirmed their address by returning a code or using a password
4053 * sent to the address from the wiki.
4055 * @return bool
4057 public function isEmailConfirmed() {
4058 global $wgEmailAuthentication;
4059 $this->load();
4060 $confirmed = true;
4061 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4062 if ( $this->isAnon() ) {
4063 return false;
4065 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4066 return false;
4068 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4069 return false;
4071 return true;
4072 } else {
4073 return $confirmed;
4078 * Check whether there is an outstanding request for e-mail confirmation.
4079 * @return bool
4081 public function isEmailConfirmationPending() {
4082 global $wgEmailAuthentication;
4083 return $wgEmailAuthentication &&
4084 !$this->isEmailConfirmed() &&
4085 $this->mEmailToken &&
4086 $this->mEmailTokenExpires > wfTimestamp();
4090 * Get the timestamp of account creation.
4092 * @return string|bool|null Timestamp of account creation, false for
4093 * non-existent/anonymous user accounts, or null if existing account
4094 * but information is not in database.
4096 public function getRegistration() {
4097 if ( $this->isAnon() ) {
4098 return false;
4100 $this->load();
4101 return $this->mRegistration;
4105 * Get the timestamp of the first edit
4107 * @return string|bool Timestamp of first edit, or false for
4108 * non-existent/anonymous user accounts.
4110 public function getFirstEditTimestamp() {
4111 if ( $this->getId() == 0 ) {
4112 return false; // anons
4114 $dbr = wfGetDB( DB_SLAVE );
4115 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4116 array( 'rev_user' => $this->getId() ),
4117 __METHOD__,
4118 array( 'ORDER BY' => 'rev_timestamp ASC' )
4120 if ( !$time ) {
4121 return false; // no edits
4123 return wfTimestamp( TS_MW, $time );
4127 * Get the permissions associated with a given list of groups
4129 * @param array $groups of Strings List of internal group names
4130 * @return Array of Strings List of permission key names for given groups combined
4132 public static function getGroupPermissions( $groups ) {
4133 global $wgGroupPermissions, $wgRevokePermissions;
4134 $rights = array();
4135 // grant every granted permission first
4136 foreach ( $groups as $group ) {
4137 if ( isset( $wgGroupPermissions[$group] ) ) {
4138 $rights = array_merge( $rights,
4139 // array_filter removes empty items
4140 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4143 // now revoke the revoked permissions
4144 foreach ( $groups as $group ) {
4145 if ( isset( $wgRevokePermissions[$group] ) ) {
4146 $rights = array_diff( $rights,
4147 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4150 return array_unique( $rights );
4154 * Get all the groups who have a given permission
4156 * @param string $role Role to check
4157 * @return Array of Strings List of internal group names with the given permission
4159 public static function getGroupsWithPermission( $role ) {
4160 global $wgGroupPermissions;
4161 $allowedGroups = array();
4162 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4163 if ( self::groupHasPermission( $group, $role ) ) {
4164 $allowedGroups[] = $group;
4167 return $allowedGroups;
4171 * Check, if the given group has the given permission
4173 * If you're wanting to check whether all users have a permission, use
4174 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4175 * from anyone.
4177 * @since 1.21
4178 * @param string $group Group to check
4179 * @param string $role Role to check
4180 * @return bool
4182 public static function groupHasPermission( $group, $role ) {
4183 global $wgGroupPermissions, $wgRevokePermissions;
4184 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4185 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4189 * Check if all users have the given permission
4191 * @since 1.22
4192 * @param string $right Right to check
4193 * @return bool
4195 public static function isEveryoneAllowed( $right ) {
4196 global $wgGroupPermissions, $wgRevokePermissions;
4197 static $cache = array();
4199 // Use the cached results, except in unit tests which rely on
4200 // being able change the permission mid-request
4201 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4202 return $cache[$right];
4205 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
4206 $cache[$right] = false;
4207 return false;
4210 // If it's revoked anywhere, then everyone doesn't have it
4211 foreach ( $wgRevokePermissions as $rights ) {
4212 if ( isset( $rights[$right] ) && $rights[$right] ) {
4213 $cache[$right] = false;
4214 return false;
4218 // Allow extensions (e.g. OAuth) to say false
4219 if ( !wfRunHooks( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4220 $cache[$right] = false;
4221 return false;
4224 $cache[$right] = true;
4225 return true;
4229 * Get the localized descriptive name for a group, if it exists
4231 * @param string $group Internal group name
4232 * @return string Localized descriptive group name
4234 public static function getGroupName( $group ) {
4235 $msg = wfMessage( "group-$group" );
4236 return $msg->isBlank() ? $group : $msg->text();
4240 * Get the localized descriptive name for a member of a group, if it exists
4242 * @param string $group Internal group name
4243 * @param string $username Username for gender (since 1.19)
4244 * @return string Localized name for group member
4246 public static function getGroupMember( $group, $username = '#' ) {
4247 $msg = wfMessage( "group-$group-member", $username );
4248 return $msg->isBlank() ? $group : $msg->text();
4252 * Return the set of defined explicit groups.
4253 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4254 * are not included, as they are defined automatically, not in the database.
4255 * @return Array of internal group names
4257 public static function getAllGroups() {
4258 global $wgGroupPermissions, $wgRevokePermissions;
4259 return array_diff(
4260 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4261 self::getImplicitGroups()
4266 * Get a list of all available permissions.
4267 * @return Array of permission names
4269 public static function getAllRights() {
4270 if ( self::$mAllRights === false ) {
4271 global $wgAvailableRights;
4272 if ( count( $wgAvailableRights ) ) {
4273 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
4274 } else {
4275 self::$mAllRights = self::$mCoreRights;
4277 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
4279 return self::$mAllRights;
4283 * Get a list of implicit groups
4284 * @return Array of Strings Array of internal group names
4286 public static function getImplicitGroups() {
4287 global $wgImplicitGroups;
4288 $groups = $wgImplicitGroups;
4289 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
4290 return $groups;
4294 * Get the title of a page describing a particular group
4296 * @param string $group Internal group name
4297 * @return Title|bool Title of the page if it exists, false otherwise
4299 public static function getGroupPage( $group ) {
4300 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4301 if ( $msg->exists() ) {
4302 $title = Title::newFromText( $msg->text() );
4303 if ( is_object( $title ) ) {
4304 return $title;
4307 return false;
4311 * Create a link to the group in HTML, if available;
4312 * else return the group name.
4314 * @param string $group Internal name of the group
4315 * @param string $text The text of the link
4316 * @return string HTML link to the group
4318 public static function makeGroupLinkHTML( $group, $text = '' ) {
4319 if ( $text == '' ) {
4320 $text = self::getGroupName( $group );
4322 $title = self::getGroupPage( $group );
4323 if ( $title ) {
4324 return Linker::link( $title, htmlspecialchars( $text ) );
4325 } else {
4326 return $text;
4331 * Create a link to the group in Wikitext, if available;
4332 * else return the group name.
4334 * @param string $group Internal name of the group
4335 * @param string $text The text of the link
4336 * @return string Wikilink to the group
4338 public static function makeGroupLinkWiki( $group, $text = '' ) {
4339 if ( $text == '' ) {
4340 $text = self::getGroupName( $group );
4342 $title = self::getGroupPage( $group );
4343 if ( $title ) {
4344 $page = $title->getPrefixedText();
4345 return "[[$page|$text]]";
4346 } else {
4347 return $text;
4352 * Returns an array of the groups that a particular group can add/remove.
4354 * @param string $group the group to check for whether it can add/remove
4355 * @return Array array( 'add' => array( addablegroups ),
4356 * 'remove' => array( removablegroups ),
4357 * 'add-self' => array( addablegroups to self),
4358 * 'remove-self' => array( removable groups from self) )
4360 public static function changeableByGroup( $group ) {
4361 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4363 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
4364 if ( empty( $wgAddGroups[$group] ) ) {
4365 // Don't add anything to $groups
4366 } elseif ( $wgAddGroups[$group] === true ) {
4367 // You get everything
4368 $groups['add'] = self::getAllGroups();
4369 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4370 $groups['add'] = $wgAddGroups[$group];
4373 // Same thing for remove
4374 if ( empty( $wgRemoveGroups[$group] ) ) {
4375 } elseif ( $wgRemoveGroups[$group] === true ) {
4376 $groups['remove'] = self::getAllGroups();
4377 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4378 $groups['remove'] = $wgRemoveGroups[$group];
4381 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4382 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4383 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4384 if ( is_int( $key ) ) {
4385 $wgGroupsAddToSelf['user'][] = $value;
4390 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4391 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4392 if ( is_int( $key ) ) {
4393 $wgGroupsRemoveFromSelf['user'][] = $value;
4398 // Now figure out what groups the user can add to him/herself
4399 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4400 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4401 // No idea WHY this would be used, but it's there
4402 $groups['add-self'] = User::getAllGroups();
4403 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4404 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4407 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4408 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4409 $groups['remove-self'] = User::getAllGroups();
4410 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4411 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4414 return $groups;
4418 * Returns an array of groups that this user can add and remove
4419 * @return Array array( 'add' => array( addablegroups ),
4420 * 'remove' => array( removablegroups ),
4421 * 'add-self' => array( addablegroups to self),
4422 * 'remove-self' => array( removable groups from self) )
4424 public function changeableGroups() {
4425 if ( $this->isAllowed( 'userrights' ) ) {
4426 // This group gives the right to modify everything (reverse-
4427 // compatibility with old "userrights lets you change
4428 // everything")
4429 // Using array_merge to make the groups reindexed
4430 $all = array_merge( User::getAllGroups() );
4431 return array(
4432 'add' => $all,
4433 'remove' => $all,
4434 'add-self' => array(),
4435 'remove-self' => array()
4439 // Okay, it's not so simple, we will have to go through the arrays
4440 $groups = array(
4441 'add' => array(),
4442 'remove' => array(),
4443 'add-self' => array(),
4444 'remove-self' => array()
4446 $addergroups = $this->getEffectiveGroups();
4448 foreach ( $addergroups as $addergroup ) {
4449 $groups = array_merge_recursive(
4450 $groups, $this->changeableByGroup( $addergroup )
4452 $groups['add'] = array_unique( $groups['add'] );
4453 $groups['remove'] = array_unique( $groups['remove'] );
4454 $groups['add-self'] = array_unique( $groups['add-self'] );
4455 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4457 return $groups;
4461 * Increment the user's edit-count field.
4462 * Will have no effect for anonymous users.
4464 public function incEditCount() {
4465 if ( !$this->isAnon() ) {
4466 $dbw = wfGetDB( DB_MASTER );
4467 $dbw->update(
4468 'user',
4469 array( 'user_editcount=user_editcount+1' ),
4470 array( 'user_id' => $this->getId() ),
4471 __METHOD__
4474 // Lazy initialization check...
4475 if ( $dbw->affectedRows() == 0 ) {
4476 // Now here's a goddamn hack...
4477 $dbr = wfGetDB( DB_SLAVE );
4478 if ( $dbr !== $dbw ) {
4479 // If we actually have a slave server, the count is
4480 // at least one behind because the current transaction
4481 // has not been committed and replicated.
4482 $this->initEditCount( 1 );
4483 } else {
4484 // But if DB_SLAVE is selecting the master, then the
4485 // count we just read includes the revision that was
4486 // just added in the working transaction.
4487 $this->initEditCount();
4491 // edit count in user cache too
4492 $this->invalidateCache();
4496 * Initialize user_editcount from data out of the revision table
4498 * @param $add Integer Edits to add to the count from the revision table
4499 * @return integer Number of edits
4501 protected function initEditCount( $add = 0 ) {
4502 // Pull from a slave to be less cruel to servers
4503 // Accuracy isn't the point anyway here
4504 $dbr = wfGetDB( DB_SLAVE );
4505 $count = (int)$dbr->selectField(
4506 'revision',
4507 'COUNT(rev_user)',
4508 array( 'rev_user' => $this->getId() ),
4509 __METHOD__
4511 $count = $count + $add;
4513 $dbw = wfGetDB( DB_MASTER );
4514 $dbw->update(
4515 'user',
4516 array( 'user_editcount' => $count ),
4517 array( 'user_id' => $this->getId() ),
4518 __METHOD__
4521 return $count;
4525 * Get the description of a given right
4527 * @param string $right Right to query
4528 * @return string Localized description of the right
4530 public static function getRightDescription( $right ) {
4531 $key = "right-$right";
4532 $msg = wfMessage( $key );
4533 return $msg->isBlank() ? $right : $msg->text();
4537 * Make an old-style password hash
4539 * @param string $password Plain-text password
4540 * @param string $userId User ID
4541 * @return string Password hash
4543 public static function oldCrypt( $password, $userId ) {
4544 global $wgPasswordSalt;
4545 if ( $wgPasswordSalt ) {
4546 return md5( $userId . '-' . md5( $password ) );
4547 } else {
4548 return md5( $password );
4553 * Make a new-style password hash
4555 * @param string $password Plain-text password
4556 * @param bool|string $salt Optional salt, may be random or the user ID.
4557 * If unspecified or false, will generate one automatically
4558 * @return string Password hash
4560 public static function crypt( $password, $salt = false ) {
4561 global $wgPasswordSalt;
4563 $hash = '';
4564 if ( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
4565 return $hash;
4568 if ( $wgPasswordSalt ) {
4569 if ( $salt === false ) {
4570 $salt = MWCryptRand::generateHex( 8 );
4572 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
4573 } else {
4574 return ':A:' . md5( $password );
4579 * Compare a password hash with a plain-text password. Requires the user
4580 * ID if there's a chance that the hash is an old-style hash.
4582 * @param string $hash Password hash
4583 * @param string $password Plain-text password to compare
4584 * @param string|bool $userId User ID for old-style password salt
4586 * @return boolean
4588 public static function comparePasswords( $hash, $password, $userId = false ) {
4589 $type = substr( $hash, 0, 3 );
4591 $result = false;
4592 if ( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
4593 return $result;
4596 if ( $type == ':A:' ) {
4597 // Unsalted
4598 return md5( $password ) === substr( $hash, 3 );
4599 } elseif ( $type == ':B:' ) {
4600 // Salted
4601 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
4602 return md5( $salt . '-' . md5( $password ) ) === $realHash;
4603 } else {
4604 // Old-style
4605 return self::oldCrypt( $password, $userId ) === $hash;
4610 * Add a newuser log entry for this user.
4611 * Before 1.19 the return value was always true.
4613 * @param string|bool $action account creation type.
4614 * - String, one of the following values:
4615 * - 'create' for an anonymous user creating an account for himself.
4616 * This will force the action's performer to be the created user itself,
4617 * no matter the value of $wgUser
4618 * - 'create2' for a logged in user creating an account for someone else
4619 * - 'byemail' when the created user will receive its password by e-mail
4620 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4621 * - Boolean means whether the account was created by e-mail (deprecated):
4622 * - true will be converted to 'byemail'
4623 * - false will be converted to 'create' if this object is the same as
4624 * $wgUser and to 'create2' otherwise
4626 * @param string $reason user supplied reason
4628 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4630 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4631 global $wgUser, $wgNewUserLog;
4632 if ( empty( $wgNewUserLog ) ) {
4633 return true; // disabled
4636 if ( $action === true ) {
4637 $action = 'byemail';
4638 } elseif ( $action === false ) {
4639 if ( $this->getName() == $wgUser->getName() ) {
4640 $action = 'create';
4641 } else {
4642 $action = 'create2';
4646 if ( $action === 'create' || $action === 'autocreate' ) {
4647 $performer = $this;
4648 } else {
4649 $performer = $wgUser;
4652 $logEntry = new ManualLogEntry( 'newusers', $action );
4653 $logEntry->setPerformer( $performer );
4654 $logEntry->setTarget( $this->getUserPage() );
4655 $logEntry->setComment( $reason );
4656 $logEntry->setParameters( array(
4657 '4::userid' => $this->getId(),
4658 ) );
4659 $logid = $logEntry->insert();
4661 if ( $action !== 'autocreate' ) {
4662 $logEntry->publish( $logid );
4665 return (int)$logid;
4669 * Add an autocreate newuser log entry for this user
4670 * Used by things like CentralAuth and perhaps other authplugins.
4671 * Consider calling addNewUserLogEntry() directly instead.
4673 * @return bool
4675 public function addNewUserLogEntryAutoCreate() {
4676 $this->addNewUserLogEntry( 'autocreate' );
4678 return true;
4682 * Load the user options either from cache, the database or an array
4684 * @param array $data Rows for the current user out of the user_properties table
4686 protected function loadOptions( $data = null ) {
4687 global $wgContLang;
4689 $this->load();
4691 if ( $this->mOptionsLoaded ) {
4692 return;
4695 $this->mOptions = self::getDefaultOptions();
4697 if ( !$this->getId() ) {
4698 // For unlogged-in users, load language/variant options from request.
4699 // There's no need to do it for logged-in users: they can set preferences,
4700 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4701 // so don't override user's choice (especially when the user chooses site default).
4702 $variant = $wgContLang->getDefaultVariant();
4703 $this->mOptions['variant'] = $variant;
4704 $this->mOptions['language'] = $variant;
4705 $this->mOptionsLoaded = true;
4706 return;
4709 // Maybe load from the object
4710 if ( !is_null( $this->mOptionOverrides ) ) {
4711 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4712 foreach ( $this->mOptionOverrides as $key => $value ) {
4713 $this->mOptions[$key] = $value;
4715 } else {
4716 if ( !is_array( $data ) ) {
4717 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4718 // Load from database
4719 $dbr = wfGetDB( DB_SLAVE );
4721 $res = $dbr->select(
4722 'user_properties',
4723 array( 'up_property', 'up_value' ),
4724 array( 'up_user' => $this->getId() ),
4725 __METHOD__
4728 $this->mOptionOverrides = array();
4729 $data = array();
4730 foreach ( $res as $row ) {
4731 $data[$row->up_property] = $row->up_value;
4734 foreach ( $data as $property => $value ) {
4735 $this->mOptionOverrides[$property] = $value;
4736 $this->mOptions[$property] = $value;
4740 $this->mOptionsLoaded = true;
4742 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
4746 * @todo document
4748 protected function saveOptions() {
4749 $this->loadOptions();
4751 // Not using getOptions(), to keep hidden preferences in database
4752 $saveOptions = $this->mOptions;
4754 // Allow hooks to abort, for instance to save to a global profile.
4755 // Reset options to default state before saving.
4756 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4757 return;
4760 $userId = $this->getId();
4761 $insert_rows = array();
4762 foreach ( $saveOptions as $key => $value ) {
4763 // Don't bother storing default values
4764 $defaultOption = self::getDefaultOption( $key );
4765 if ( ( is_null( $defaultOption ) &&
4766 !( $value === false || is_null( $value ) ) ) ||
4767 $value != $defaultOption
4769 $insert_rows[] = array(
4770 'up_user' => $userId,
4771 'up_property' => $key,
4772 'up_value' => $value,
4777 $dbw = wfGetDB( DB_MASTER );
4778 // Find and delete any prior preference rows...
4779 $res = $dbw->select( 'user_properties',
4780 array( 'up_property' ), array( 'up_user' => $userId ), __METHOD__ );
4781 $priorKeys = array();
4782 foreach ( $res as $row ) {
4783 $priorKeys[] = $row->up_property;
4785 if ( count( $priorKeys ) ) {
4786 // Do the DELETE by PRIMARY KEY for prior rows.
4787 // In the past a very large portion of calls to this function are for setting
4788 // 'rememberpassword' for new accounts (a preference that has since been removed).
4789 // Doing a blanket per-user DELETE for new accounts with no rows in the table
4790 // caused gap locks on [max user ID,+infinity) which caused high contention since
4791 // updates would pile up on each other as they are for higher (newer) user IDs.
4792 // It might not be necessary these days, but it shouldn't hurt either.
4793 $dbw->delete( 'user_properties',
4794 array( 'up_user' => $userId, 'up_property' => $priorKeys ), __METHOD__ );
4796 // Insert the new preference rows
4797 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, array( 'IGNORE' ) );
4801 * Provide an array of HTML5 attributes to put on an input element
4802 * intended for the user to enter a new password. This may include
4803 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4805 * Do *not* use this when asking the user to enter his current password!
4806 * Regardless of configuration, users may have invalid passwords for whatever
4807 * reason (e.g., they were set before requirements were tightened up).
4808 * Only use it when asking for a new password, like on account creation or
4809 * ResetPass.
4811 * Obviously, you still need to do server-side checking.
4813 * NOTE: A combination of bugs in various browsers means that this function
4814 * actually just returns array() unconditionally at the moment. May as
4815 * well keep it around for when the browser bugs get fixed, though.
4817 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4819 * @return array Array of HTML attributes suitable for feeding to
4820 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4821 * That will get confused by the boolean attribute syntax used.)
4823 public static function passwordChangeInputAttribs() {
4824 global $wgMinimalPasswordLength;
4826 if ( $wgMinimalPasswordLength == 0 ) {
4827 return array();
4830 # Note that the pattern requirement will always be satisfied if the
4831 # input is empty, so we need required in all cases.
4833 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4834 # if e-mail confirmation is being used. Since HTML5 input validation
4835 # is b0rked anyway in some browsers, just return nothing. When it's
4836 # re-enabled, fix this code to not output required for e-mail
4837 # registration.
4838 #$ret = array( 'required' );
4839 $ret = array();
4841 # We can't actually do this right now, because Opera 9.6 will print out
4842 # the entered password visibly in its error message! When other
4843 # browsers add support for this attribute, or Opera fixes its support,
4844 # we can add support with a version check to avoid doing this on Opera
4845 # versions where it will be a problem. Reported to Opera as
4846 # DSK-262266, but they don't have a public bug tracker for us to follow.
4848 if ( $wgMinimalPasswordLength > 1 ) {
4849 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4850 $ret['title'] = wfMessage( 'passwordtooshort' )
4851 ->numParams( $wgMinimalPasswordLength )->text();
4855 return $ret;
4859 * Return the list of user fields that should be selected to create
4860 * a new user object.
4861 * @return array
4863 public static function selectFields() {
4864 return array(
4865 'user_id',
4866 'user_name',
4867 'user_real_name',
4868 'user_password',
4869 'user_newpassword',
4870 'user_newpass_time',
4871 'user_email',
4872 'user_touched',
4873 'user_token',
4874 'user_email_authenticated',
4875 'user_email_token',
4876 'user_email_token_expires',
4877 'user_password_expires',
4878 'user_registration',
4879 'user_editcount',
4884 * Factory function for fatal permission-denied errors
4886 * @since 1.22
4887 * @param string $permission User right required
4888 * @return Status
4890 static function newFatalPermissionDeniedStatus( $permission ) {
4891 global $wgLang;
4893 $groups = array_map(
4894 array( 'User', 'makeGroupLinkWiki' ),
4895 User::getGroupsWithPermission( $permission )
4898 if ( $groups ) {
4899 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
4900 } else {
4901 return Status::newFatal( 'badaccess-group0' );