Merge "Localisation updates from https://translatewiki.net."
[mediawiki.git] / includes / User.php
blobf5768afefd0ce8e06dd6302a97a2a14a958525aa
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|null $request Object to use; $wgRequest will be used if omitted.
452 * @return User
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 String 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 bool|string|array 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 int $ts 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|bool 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 string|bool $name
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 bool
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 no reload.
1332 public function clearInstanceCache( $reloadFrom = false ) {
1333 $this->mNewtalk = -1;
1334 $this->mDatePreference = null;
1335 $this->mBlockedby = -1; # Unset
1336 $this->mHash = false;
1337 $this->mRights = null;
1338 $this->mEffectiveGroups = null;
1339 $this->mImplicitGroups = null;
1340 $this->mGroups = null;
1341 $this->mOptions = null;
1342 $this->mOptionsLoaded = false;
1343 $this->mEditCount = null;
1345 if ( $reloadFrom ) {
1346 $this->mLoadedItems = array();
1347 $this->mFrom = $reloadFrom;
1352 * Combine the language default options with any site-specific options
1353 * and add the default language variants.
1355 * @return array Array of String options
1357 public static function getDefaultOptions() {
1358 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1360 static $defOpt = null;
1361 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1362 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1363 // mid-request and see that change reflected in the return value of this function.
1364 // Which is insane and would never happen during normal MW operation
1365 return $defOpt;
1368 $defOpt = $wgDefaultUserOptions;
1369 // Default language setting
1370 $defOpt['language'] = $wgContLang->getCode();
1371 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
1372 $defOpt[$langCode == $wgContLang->getCode() ? 'variant' : "variant-$langCode"] = $langCode;
1374 foreach ( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1375 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1377 $defOpt['skin'] = $wgDefaultSkin;
1379 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1381 return $defOpt;
1385 * Get a given default option value.
1387 * @param string $opt Name of option to retrieve
1388 * @return string Default option value
1390 public static function getDefaultOption( $opt ) {
1391 $defOpts = self::getDefaultOptions();
1392 if ( isset( $defOpts[$opt] ) ) {
1393 return $defOpts[$opt];
1394 } else {
1395 return null;
1400 * Get blocking information
1401 * @param bool $bFromSlave Whether to check the slave database first.
1402 * To improve performance, non-critical checks are done against slaves.
1403 * Check when actually saving should be done against master.
1405 private function getBlockedStatus( $bFromSlave = true ) {
1406 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1408 if ( -1 != $this->mBlockedby ) {
1409 return;
1412 wfProfileIn( __METHOD__ );
1413 wfDebug( __METHOD__ . ": checking...\n" );
1415 // Initialize data...
1416 // Otherwise something ends up stomping on $this->mBlockedby when
1417 // things get lazy-loaded later, causing false positive block hits
1418 // due to -1 !== 0. Probably session-related... Nothing should be
1419 // overwriting mBlockedby, surely?
1420 $this->load();
1422 # We only need to worry about passing the IP address to the Block generator if the
1423 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1424 # know which IP address they're actually coming from
1425 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1426 $ip = $this->getRequest()->getIP();
1427 } else {
1428 $ip = null;
1431 // User/IP blocking
1432 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1434 // Proxy blocking
1435 if ( !$block instanceof Block && $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1436 && !in_array( $ip, $wgProxyWhitelist )
1438 // Local list
1439 if ( self::isLocallyBlockedProxy( $ip ) ) {
1440 $block = new Block;
1441 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1442 $block->mReason = wfMessage( 'proxyblockreason' )->text();
1443 $block->setTarget( $ip );
1444 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1445 $block = new Block;
1446 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1447 $block->mReason = wfMessage( 'sorbsreason' )->text();
1448 $block->setTarget( $ip );
1452 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1453 if ( !$block instanceof Block
1454 && $wgApplyIpBlocksToXff
1455 && $ip !== null
1456 && !$this->isAllowed( 'proxyunbannable' )
1457 && !in_array( $ip, $wgProxyWhitelist )
1459 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1460 $xff = array_map( 'trim', explode( ',', $xff ) );
1461 $xff = array_diff( $xff, array( $ip ) );
1462 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1463 $block = Block::chooseBlock( $xffblocks, $xff );
1464 if ( $block instanceof Block ) {
1465 # Mangle the reason to alert the user that the block
1466 # originated from matching the X-Forwarded-For header.
1467 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->text();
1471 if ( $block instanceof Block ) {
1472 wfDebug( __METHOD__ . ": Found block.\n" );
1473 $this->mBlock = $block;
1474 $this->mBlockedby = $block->getByName();
1475 $this->mBlockreason = $block->mReason;
1476 $this->mHideName = $block->mHideName;
1477 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1478 } else {
1479 $this->mBlockedby = '';
1480 $this->mHideName = 0;
1481 $this->mAllowUsertalk = false;
1484 // Extensions
1485 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1487 wfProfileOut( __METHOD__ );
1491 * Whether the given IP is in a DNS blacklist.
1493 * @param string $ip IP to check
1494 * @param bool $checkWhitelist Whether to check the whitelist first
1495 * @return bool True if blacklisted.
1497 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1498 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1499 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1501 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs ) {
1502 return false;
1505 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1506 return false;
1509 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1510 return $this->inDnsBlacklist( $ip, $urls );
1514 * Whether the given IP is in a given DNS blacklist.
1516 * @param string $ip IP to check
1517 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1518 * @return bool True if blacklisted.
1520 public function inDnsBlacklist( $ip, $bases ) {
1521 wfProfileIn( __METHOD__ );
1523 $found = false;
1524 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1525 if ( IP::isIPv4( $ip ) ) {
1526 // Reverse IP, bug 21255
1527 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1529 foreach ( (array)$bases as $base ) {
1530 // Make hostname
1531 // If we have an access key, use that too (ProjectHoneypot, etc.)
1532 if ( is_array( $base ) ) {
1533 if ( count( $base ) >= 2 ) {
1534 // Access key is 1, base URL is 0
1535 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1536 } else {
1537 $host = "$ipReversed.{$base[0]}";
1539 } else {
1540 $host = "$ipReversed.$base";
1543 // Send query
1544 $ipList = gethostbynamel( $host );
1546 if ( $ipList ) {
1547 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1548 $found = true;
1549 break;
1550 } else {
1551 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1556 wfProfileOut( __METHOD__ );
1557 return $found;
1561 * Check if an IP address is in the local proxy list
1563 * @param string $ip
1565 * @return bool
1567 public static function isLocallyBlockedProxy( $ip ) {
1568 global $wgProxyList;
1570 if ( !$wgProxyList ) {
1571 return false;
1573 wfProfileIn( __METHOD__ );
1575 if ( !is_array( $wgProxyList ) ) {
1576 // Load from the specified file
1577 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1580 if ( !is_array( $wgProxyList ) ) {
1581 $ret = false;
1582 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1583 $ret = true;
1584 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1585 // Old-style flipped proxy list
1586 $ret = true;
1587 } else {
1588 $ret = false;
1590 wfProfileOut( __METHOD__ );
1591 return $ret;
1595 * Is this user subject to rate limiting?
1597 * @return bool True if rate limited
1599 public function isPingLimitable() {
1600 global $wgRateLimitsExcludedIPs;
1601 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1602 // No other good way currently to disable rate limits
1603 // for specific IPs. :P
1604 // But this is a crappy hack and should die.
1605 return false;
1607 return !$this->isAllowed( 'noratelimit' );
1611 * Primitive rate limits: enforce maximum actions per time period
1612 * to put a brake on flooding.
1614 * @note When using a shared cache like memcached, IP-address
1615 * last-hit counters will be shared across wikis.
1617 * @param string $action Action to enforce; 'edit' if unspecified
1618 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1619 * @return bool True if a rate limiter was tripped
1621 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1622 // Call the 'PingLimiter' hook
1623 $result = false;
1624 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1625 return $result;
1628 global $wgRateLimits;
1629 if ( !isset( $wgRateLimits[$action] ) ) {
1630 return false;
1633 // Some groups shouldn't trigger the ping limiter, ever
1634 if ( !$this->isPingLimitable() ) {
1635 return false;
1638 global $wgMemc;
1639 wfProfileIn( __METHOD__ );
1641 $limits = $wgRateLimits[$action];
1642 $keys = array();
1643 $id = $this->getId();
1644 $userLimit = false;
1646 if ( isset( $limits['anon'] ) && $id == 0 ) {
1647 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1650 if ( isset( $limits['user'] ) && $id != 0 ) {
1651 $userLimit = $limits['user'];
1653 if ( $this->isNewbie() ) {
1654 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1655 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1657 if ( isset( $limits['ip'] ) ) {
1658 $ip = $this->getRequest()->getIP();
1659 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1661 if ( isset( $limits['subnet'] ) ) {
1662 $ip = $this->getRequest()->getIP();
1663 $matches = array();
1664 $subnet = false;
1665 if ( IP::isIPv6( $ip ) ) {
1666 $parts = IP::parseRange( "$ip/64" );
1667 $subnet = $parts[0];
1668 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1669 // IPv4
1670 $subnet = $matches[1];
1672 if ( $subnet !== false ) {
1673 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1677 // Check for group-specific permissions
1678 // If more than one group applies, use the group with the highest limit
1679 foreach ( $this->getGroups() as $group ) {
1680 if ( isset( $limits[$group] ) ) {
1681 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1682 $userLimit = $limits[$group];
1686 // Set the user limit key
1687 if ( $userLimit !== false ) {
1688 list( $max, $period ) = $userLimit;
1689 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
1690 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1693 $triggered = false;
1694 foreach ( $keys as $key => $limit ) {
1695 list( $max, $period ) = $limit;
1696 $summary = "(limit $max in {$period}s)";
1697 $count = $wgMemc->get( $key );
1698 // Already pinged?
1699 if ( $count ) {
1700 if ( $count >= $max ) {
1701 wfDebugLog( 'ratelimit', $this->getName() . " tripped! $key at $count $summary" );
1702 $triggered = true;
1703 } else {
1704 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1706 } else {
1707 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1708 if ( $incrBy > 0 ) {
1709 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1712 if ( $incrBy > 0 ) {
1713 $wgMemc->incr( $key, $incrBy );
1717 wfProfileOut( __METHOD__ );
1718 return $triggered;
1722 * Check if user is blocked
1724 * @param bool $bFromSlave Whether to check the slave database instead of the master
1725 * @return bool True if blocked, false otherwise
1727 public function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1728 return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
1732 * Get the block affecting the user, or null if the user is not blocked
1734 * @param bool $bFromSlave Whether to check the slave database instead of the master
1735 * @return Block|null
1737 public function getBlock( $bFromSlave = true ) {
1738 $this->getBlockedStatus( $bFromSlave );
1739 return $this->mBlock instanceof Block ? $this->mBlock : null;
1743 * Check if user is blocked from editing a particular article
1745 * @param Title $title Title to check
1746 * @param bool $bFromSlave Whether to check the slave database instead of the master
1747 * @return bool
1749 public function isBlockedFrom( $title, $bFromSlave = false ) {
1750 global $wgBlockAllowsUTEdit;
1751 wfProfileIn( __METHOD__ );
1753 $blocked = $this->isBlocked( $bFromSlave );
1754 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1755 // If a user's name is suppressed, they cannot make edits anywhere
1756 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName()
1757 && $title->getNamespace() == NS_USER_TALK ) {
1758 $blocked = false;
1759 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1762 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1764 wfProfileOut( __METHOD__ );
1765 return $blocked;
1769 * If user is blocked, return the name of the user who placed the block
1770 * @return string Name of blocker
1772 public function blockedBy() {
1773 $this->getBlockedStatus();
1774 return $this->mBlockedby;
1778 * If user is blocked, return the specified reason for the block
1779 * @return string Blocking reason
1781 public function blockedFor() {
1782 $this->getBlockedStatus();
1783 return $this->mBlockreason;
1787 * If user is blocked, return the ID for the block
1788 * @return int Block ID
1790 public function getBlockId() {
1791 $this->getBlockedStatus();
1792 return ( $this->mBlock ? $this->mBlock->getId() : false );
1796 * Check if user is blocked on all wikis.
1797 * Do not use for actual edit permission checks!
1798 * This is intended for quick UI checks.
1800 * @param string $ip IP address, uses current client if none given
1801 * @return bool True if blocked, false otherwise
1803 public function isBlockedGlobally( $ip = '' ) {
1804 if ( $this->mBlockedGlobally !== null ) {
1805 return $this->mBlockedGlobally;
1807 // User is already an IP?
1808 if ( IP::isIPAddress( $this->getName() ) ) {
1809 $ip = $this->getName();
1810 } elseif ( !$ip ) {
1811 $ip = $this->getRequest()->getIP();
1813 $blocked = false;
1814 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1815 $this->mBlockedGlobally = (bool)$blocked;
1816 return $this->mBlockedGlobally;
1820 * Check if user account is locked
1822 * @return bool True if locked, false otherwise
1824 public function isLocked() {
1825 if ( $this->mLocked !== null ) {
1826 return $this->mLocked;
1828 global $wgAuth;
1829 StubObject::unstub( $wgAuth );
1830 $authUser = $wgAuth->getUserInstance( $this );
1831 $this->mLocked = (bool)$authUser->isLocked();
1832 return $this->mLocked;
1836 * Check if user account is hidden
1838 * @return bool True if hidden, false otherwise
1840 public function isHidden() {
1841 if ( $this->mHideName !== null ) {
1842 return $this->mHideName;
1844 $this->getBlockedStatus();
1845 if ( !$this->mHideName ) {
1846 global $wgAuth;
1847 StubObject::unstub( $wgAuth );
1848 $authUser = $wgAuth->getUserInstance( $this );
1849 $this->mHideName = (bool)$authUser->isHidden();
1851 return $this->mHideName;
1855 * Get the user's ID.
1856 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1858 public function getId() {
1859 if ( $this->mId === null && $this->mName !== null && User::isIP( $this->mName ) ) {
1860 // Special case, we know the user is anonymous
1861 return 0;
1862 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1863 // Don't load if this was initialized from an ID
1864 $this->load();
1866 return $this->mId;
1870 * Set the user and reload all fields according to a given ID
1871 * @param int $v User ID to reload
1873 public function setId( $v ) {
1874 $this->mId = $v;
1875 $this->clearInstanceCache( 'id' );
1879 * Get the user name, or the IP of an anonymous user
1880 * @return string User's name or IP address
1882 public function getName() {
1883 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1884 // Special case optimisation
1885 return $this->mName;
1886 } else {
1887 $this->load();
1888 if ( $this->mName === false ) {
1889 // Clean up IPs
1890 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
1892 return $this->mName;
1897 * Set the user name.
1899 * This does not reload fields from the database according to the given
1900 * name. Rather, it is used to create a temporary "nonexistent user" for
1901 * later addition to the database. It can also be used to set the IP
1902 * address for an anonymous user to something other than the current
1903 * remote IP.
1905 * @note User::newFromName() has roughly the same function, when the named user
1906 * does not exist.
1907 * @param string $str New user name to set
1909 public function setName( $str ) {
1910 $this->load();
1911 $this->mName = $str;
1915 * Get the user's name escaped by underscores.
1916 * @return string Username escaped by underscores.
1918 public function getTitleKey() {
1919 return str_replace( ' ', '_', $this->getName() );
1923 * Check if the user has new messages.
1924 * @return bool True if the user has new messages
1926 public function getNewtalk() {
1927 $this->load();
1929 // Load the newtalk status if it is unloaded (mNewtalk=-1)
1930 if ( $this->mNewtalk === -1 ) {
1931 $this->mNewtalk = false; # reset talk page status
1933 // Check memcached separately for anons, who have no
1934 // entire User object stored in there.
1935 if ( !$this->mId ) {
1936 global $wgDisableAnonTalk;
1937 if ( $wgDisableAnonTalk ) {
1938 // Anon newtalk disabled by configuration.
1939 $this->mNewtalk = false;
1940 } else {
1941 global $wgMemc;
1942 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1943 $newtalk = $wgMemc->get( $key );
1944 if ( strval( $newtalk ) !== '' ) {
1945 $this->mNewtalk = (bool)$newtalk;
1946 } else {
1947 // Since we are caching this, make sure it is up to date by getting it
1948 // from the master
1949 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1950 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1953 } else {
1954 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1958 return (bool)$this->mNewtalk;
1962 * Return the data needed to construct links for new talk page message
1963 * alerts. If there are new messages, this will return an associative array
1964 * with the following data:
1965 * wiki: The database name of the wiki
1966 * link: Root-relative link to the user's talk page
1967 * rev: The last talk page revision that the user has seen or null. This
1968 * is useful for building diff links.
1969 * If there are no new messages, it returns an empty array.
1970 * @note This function was designed to accomodate multiple talk pages, but
1971 * currently only returns a single link and revision.
1972 * @return array
1974 public function getNewMessageLinks() {
1975 $talks = array();
1976 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
1977 return $talks;
1978 } elseif ( !$this->getNewtalk() ) {
1979 return array();
1981 $utp = $this->getTalkPage();
1982 $dbr = wfGetDB( DB_SLAVE );
1983 // Get the "last viewed rev" timestamp from the oldest message notification
1984 $timestamp = $dbr->selectField( 'user_newtalk',
1985 'MIN(user_last_timestamp)',
1986 $this->isAnon() ? array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
1987 __METHOD__ );
1988 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
1989 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
1993 * Get the revision ID for the last talk page revision viewed by the talk
1994 * page owner.
1995 * @return int|null Revision ID or null
1997 public function getNewMessageRevisionId() {
1998 $newMessageRevisionId = null;
1999 $newMessageLinks = $this->getNewMessageLinks();
2000 if ( $newMessageLinks ) {
2001 // Note: getNewMessageLinks() never returns more than a single link
2002 // and it is always for the same wiki, but we double-check here in
2003 // case that changes some time in the future.
2004 if ( count( $newMessageLinks ) === 1
2005 && $newMessageLinks[0]['wiki'] === wfWikiID()
2006 && $newMessageLinks[0]['rev']
2008 $newMessageRevision = $newMessageLinks[0]['rev'];
2009 $newMessageRevisionId = $newMessageRevision->getId();
2012 return $newMessageRevisionId;
2016 * Internal uncached check for new messages
2018 * @see getNewtalk()
2019 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2020 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2021 * @param bool $fromMaster true to fetch from the master, false for a slave
2022 * @return bool True if the user has new messages
2024 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
2025 if ( $fromMaster ) {
2026 $db = wfGetDB( DB_MASTER );
2027 } else {
2028 $db = wfGetDB( DB_SLAVE );
2030 $ok = $db->selectField( 'user_newtalk', $field,
2031 array( $field => $id ), __METHOD__ );
2032 return $ok !== false;
2036 * Add or update the new messages flag
2037 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2038 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2039 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2040 * @return bool True if successful, false otherwise
2042 protected function updateNewtalk( $field, $id, $curRev = null ) {
2043 // Get timestamp of the talk page revision prior to the current one
2044 $prevRev = $curRev ? $curRev->getPrevious() : false;
2045 $ts = $prevRev ? $prevRev->getTimestamp() : null;
2046 // Mark the user as having new messages since this revision
2047 $dbw = wfGetDB( DB_MASTER );
2048 $dbw->insert( 'user_newtalk',
2049 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2050 __METHOD__,
2051 'IGNORE' );
2052 if ( $dbw->affectedRows() ) {
2053 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
2054 return true;
2055 } else {
2056 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
2057 return false;
2062 * Clear the new messages flag for the given user
2063 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2064 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2065 * @return bool True if successful, false otherwise
2067 protected function deleteNewtalk( $field, $id ) {
2068 $dbw = wfGetDB( DB_MASTER );
2069 $dbw->delete( 'user_newtalk',
2070 array( $field => $id ),
2071 __METHOD__ );
2072 if ( $dbw->affectedRows() ) {
2073 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
2074 return true;
2075 } else {
2076 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
2077 return false;
2082 * Update the 'You have new messages!' status.
2083 * @param bool $val Whether the user has new messages
2084 * @param Revision $curRev New, as yet unseen revision of the user talk page. Ignored if null or !$val.
2086 public function setNewtalk( $val, $curRev = null ) {
2087 if ( wfReadOnly() ) {
2088 return;
2091 $this->load();
2092 $this->mNewtalk = $val;
2094 if ( $this->isAnon() ) {
2095 $field = 'user_ip';
2096 $id = $this->getName();
2097 } else {
2098 $field = 'user_id';
2099 $id = $this->getId();
2101 global $wgMemc;
2103 if ( $val ) {
2104 $changed = $this->updateNewtalk( $field, $id, $curRev );
2105 } else {
2106 $changed = $this->deleteNewtalk( $field, $id );
2109 if ( $this->isAnon() ) {
2110 // Anons have a separate memcached space, since
2111 // user records aren't kept for them.
2112 $key = wfMemcKey( 'newtalk', 'ip', $id );
2113 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
2115 if ( $changed ) {
2116 $this->invalidateCache();
2121 * Generate a current or new-future timestamp to be stored in the
2122 * user_touched field when we update things.
2123 * @return string Timestamp in TS_MW format
2125 private static function newTouchedTimestamp() {
2126 global $wgClockSkewFudge;
2127 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
2131 * Clear user data from memcached.
2132 * Use after applying fun updates to the database; caller's
2133 * responsibility to update user_touched if appropriate.
2135 * Called implicitly from invalidateCache() and saveSettings().
2137 private function clearSharedCache() {
2138 $this->load();
2139 if ( $this->mId ) {
2140 global $wgMemc;
2141 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
2146 * Immediately touch the user data cache for this account.
2147 * Updates user_touched field, and removes account data from memcached
2148 * for reload on the next hit.
2150 public function invalidateCache() {
2151 if ( wfReadOnly() ) {
2152 return;
2154 $this->load();
2155 if ( $this->mId ) {
2156 $this->mTouched = self::newTouchedTimestamp();
2158 $dbw = wfGetDB( DB_MASTER );
2159 $userid = $this->mId;
2160 $touched = $this->mTouched;
2161 $method = __METHOD__;
2162 $dbw->onTransactionIdle( function() use ( $dbw, $userid, $touched, $method ) {
2163 // Prevent contention slams by checking user_touched first
2164 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2165 $needsPurge = $dbw->selectField( 'user', '1',
2166 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2167 if ( $needsPurge ) {
2168 $dbw->update( 'user',
2169 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2170 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2171 $method
2174 } );
2175 $this->clearSharedCache();
2180 * Validate the cache for this account.
2181 * @param string $timestamp A timestamp in TS_MW format
2182 * @return bool
2184 public function validateCache( $timestamp ) {
2185 $this->load();
2186 return ( $timestamp >= $this->mTouched );
2190 * Get the user touched timestamp
2191 * @return string Timestamp
2193 public function getTouched() {
2194 $this->load();
2195 return $this->mTouched;
2199 * Set the password and reset the random token.
2200 * Calls through to authentication plugin if necessary;
2201 * will have no effect if the auth plugin refuses to
2202 * pass the change through or if the legal password
2203 * checks fail.
2205 * As a special case, setting the password to null
2206 * wipes it, so the account cannot be logged in until
2207 * a new password is set, for instance via e-mail.
2209 * @param string $str New password to set
2210 * @throws PasswordError on failure
2212 * @return bool
2214 public function setPassword( $str ) {
2215 global $wgAuth;
2217 if ( $str !== null ) {
2218 if ( !$wgAuth->allowPasswordChange() ) {
2219 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2222 if ( !$this->isValidPassword( $str ) ) {
2223 global $wgMinimalPasswordLength;
2224 $valid = $this->getPasswordValidity( $str );
2225 if ( is_array( $valid ) ) {
2226 $message = array_shift( $valid );
2227 $params = $valid;
2228 } else {
2229 $message = $valid;
2230 $params = array( $wgMinimalPasswordLength );
2232 throw new PasswordError( wfMessage( $message, $params )->text() );
2236 if ( !$wgAuth->setPassword( $this, $str ) ) {
2237 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2240 $this->setInternalPassword( $str );
2242 return true;
2246 * Set the password and reset the random token unconditionally.
2248 * @param string|null $str New password to set or null to set an invalid
2249 * password hash meaning that the user will not be able to log in
2250 * through the web interface.
2252 public function setInternalPassword( $str ) {
2253 $this->load();
2254 $this->setToken();
2256 if ( $str === null ) {
2257 // Save an invalid hash...
2258 $this->mPassword = '';
2259 } else {
2260 $this->mPassword = self::crypt( $str );
2262 $this->mNewpassword = '';
2263 $this->mNewpassTime = null;
2267 * Get the user's current token.
2268 * @param bool $forceCreation Force the generation of a new token if the user doesn't have one (default=true for backwards compatibility)
2269 * @return string Token
2271 public function getToken( $forceCreation = true ) {
2272 $this->load();
2273 if ( !$this->mToken && $forceCreation ) {
2274 $this->setToken();
2276 return $this->mToken;
2280 * Set the random token (used for persistent authentication)
2281 * Called from loadDefaults() among other places.
2283 * @param string|bool $token If specified, set the token to this value
2285 public function setToken( $token = false ) {
2286 $this->load();
2287 if ( !$token ) {
2288 $this->mToken = MWCryptRand::generateHex( USER_TOKEN_LENGTH );
2289 } else {
2290 $this->mToken = $token;
2295 * Set the password for a password reminder or new account email
2297 * @param string $str New password to set or null to set an invalid
2298 * password hash meaning that the user will not be able to use it
2299 * @param bool $throttle If true, reset the throttle timestamp to the present
2301 public function setNewpassword( $str, $throttle = true ) {
2302 $this->load();
2304 if ( $str === null ) {
2305 $this->mNewpassword = '';
2306 $this->mNewpassTime = null;
2307 } else {
2308 $this->mNewpassword = self::crypt( $str );
2309 if ( $throttle ) {
2310 $this->mNewpassTime = wfTimestampNow();
2316 * Has password reminder email been sent within the last
2317 * $wgPasswordReminderResendTime hours?
2318 * @return bool
2320 public function isPasswordReminderThrottled() {
2321 global $wgPasswordReminderResendTime;
2322 $this->load();
2323 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
2324 return false;
2326 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
2327 return time() < $expiry;
2331 * Get the user's e-mail address
2332 * @return string User's email address
2334 public function getEmail() {
2335 $this->load();
2336 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
2337 return $this->mEmail;
2341 * Get the timestamp of the user's e-mail authentication
2342 * @return string TS_MW timestamp
2344 public function getEmailAuthenticationTimestamp() {
2345 $this->load();
2346 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2347 return $this->mEmailAuthenticated;
2351 * Set the user's e-mail address
2352 * @param string $str New e-mail address
2354 public function setEmail( $str ) {
2355 $this->load();
2356 if ( $str == $this->mEmail ) {
2357 return;
2359 $this->mEmail = $str;
2360 $this->invalidateEmail();
2361 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
2365 * Set the user's e-mail address and a confirmation mail if needed.
2367 * @since 1.20
2368 * @param string $str New e-mail address
2369 * @return Status
2371 public function setEmailWithConfirmation( $str ) {
2372 global $wgEnableEmail, $wgEmailAuthentication;
2374 if ( !$wgEnableEmail ) {
2375 return Status::newFatal( 'emaildisabled' );
2378 $oldaddr = $this->getEmail();
2379 if ( $str === $oldaddr ) {
2380 return Status::newGood( true );
2383 $this->setEmail( $str );
2385 if ( $str !== '' && $wgEmailAuthentication ) {
2386 // Send a confirmation request to the new address if needed
2387 $type = $oldaddr != '' ? 'changed' : 'set';
2388 $result = $this->sendConfirmationMail( $type );
2389 if ( $result->isGood() ) {
2390 // Say the the caller that a confirmation mail has been sent
2391 $result->value = 'eauth';
2393 } else {
2394 $result = Status::newGood( true );
2397 return $result;
2401 * Get the user's real name
2402 * @return string User's real name
2404 public function getRealName() {
2405 if ( !$this->isItemLoaded( 'realname' ) ) {
2406 $this->load();
2409 return $this->mRealName;
2413 * Set the user's real name
2414 * @param string $str New real name
2416 public function setRealName( $str ) {
2417 $this->load();
2418 $this->mRealName = $str;
2422 * Get the user's current setting for a given option.
2424 * @param string $oname The option to check
2425 * @param string $defaultOverride A default value returned if the option does not exist
2426 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2427 * @return string User's current value for the option
2428 * @see getBoolOption()
2429 * @see getIntOption()
2431 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2432 global $wgHiddenPrefs;
2433 $this->loadOptions();
2435 # We want 'disabled' preferences to always behave as the default value for
2436 # users, even if they have set the option explicitly in their settings (ie they
2437 # set it, and then it was disabled removing their ability to change it). But
2438 # we don't want to erase the preferences in the database in case the preference
2439 # is re-enabled again. So don't touch $mOptions, just override the returned value
2440 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2441 return self::getDefaultOption( $oname );
2444 if ( array_key_exists( $oname, $this->mOptions ) ) {
2445 return $this->mOptions[$oname];
2446 } else {
2447 return $defaultOverride;
2452 * Get all user's options
2454 * @return array
2456 public function getOptions() {
2457 global $wgHiddenPrefs;
2458 $this->loadOptions();
2459 $options = $this->mOptions;
2461 # We want 'disabled' preferences to always behave as the default value for
2462 # users, even if they have set the option explicitly in their settings (ie they
2463 # set it, and then it was disabled removing their ability to change it). But
2464 # we don't want to erase the preferences in the database in case the preference
2465 # is re-enabled again. So don't touch $mOptions, just override the returned value
2466 foreach ( $wgHiddenPrefs as $pref ) {
2467 $default = self::getDefaultOption( $pref );
2468 if ( $default !== null ) {
2469 $options[$pref] = $default;
2473 return $options;
2477 * Get the user's current setting for a given option, as a boolean value.
2479 * @param string $oname The option to check
2480 * @return bool User's current value for the option
2481 * @see getOption()
2483 public function getBoolOption( $oname ) {
2484 return (bool)$this->getOption( $oname );
2488 * Get the user's current setting for a given option, as an integer value.
2490 * @param string $oname The option to check
2491 * @param int $defaultOverride A default value returned if the option does not exist
2492 * @return int User's current value for the option
2493 * @see getOption()
2495 public function getIntOption( $oname, $defaultOverride = 0 ) {
2496 $val = $this->getOption( $oname );
2497 if ( $val == '' ) {
2498 $val = $defaultOverride;
2500 return intval( $val );
2504 * Set the given option for a user.
2506 * @param string $oname The option to set
2507 * @param mixed $val New value to set
2509 public function setOption( $oname, $val ) {
2510 $this->loadOptions();
2512 // Explicitly NULL values should refer to defaults
2513 if ( is_null( $val ) ) {
2514 $val = self::getDefaultOption( $oname );
2517 $this->mOptions[$oname] = $val;
2521 * Get a token stored in the preferences (like the watchlist one),
2522 * resetting it if it's empty (and saving changes).
2524 * @param string $oname The option name to retrieve the token from
2525 * @return string|bool User's current value for the option, or false if this option is disabled.
2526 * @see resetTokenFromOption()
2527 * @see getOption()
2529 public function getTokenFromOption( $oname ) {
2530 global $wgHiddenPrefs;
2531 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2532 return false;
2535 $token = $this->getOption( $oname );
2536 if ( !$token ) {
2537 $token = $this->resetTokenFromOption( $oname );
2538 $this->saveSettings();
2540 return $token;
2544 * Reset a token stored in the preferences (like the watchlist one).
2545 * *Does not* save user's preferences (similarly to setOption()).
2547 * @param string $oname The option name to reset the token in
2548 * @return string|bool New token value, or false if this option is disabled.
2549 * @see getTokenFromOption()
2550 * @see setOption()
2552 public function resetTokenFromOption( $oname ) {
2553 global $wgHiddenPrefs;
2554 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2555 return false;
2558 $token = MWCryptRand::generateHex( 40 );
2559 $this->setOption( $oname, $token );
2560 return $token;
2564 * Return a list of the types of user options currently returned by
2565 * User::getOptionKinds().
2567 * Currently, the option kinds are:
2568 * - 'registered' - preferences which are registered in core MediaWiki or
2569 * by extensions using the UserGetDefaultOptions hook.
2570 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2571 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2572 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2573 * be used by user scripts.
2574 * - 'special' - "preferences" that are not accessible via User::getOptions
2575 * or User::setOptions.
2576 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2577 * These are usually legacy options, removed in newer versions.
2579 * The API (and possibly others) use this function to determine the possible
2580 * option types for validation purposes, so make sure to update this when a
2581 * new option kind is added.
2583 * @see User::getOptionKinds
2584 * @return array Option kinds
2586 public static function listOptionKinds() {
2587 return array(
2588 'registered',
2589 'registered-multiselect',
2590 'registered-checkmatrix',
2591 'userjs',
2592 'special',
2593 'unused'
2598 * Return an associative array mapping preferences keys to the kind of a preference they're
2599 * used for. Different kinds are handled differently when setting or reading preferences.
2601 * See User::listOptionKinds for the list of valid option types that can be provided.
2603 * @see User::listOptionKinds
2604 * @param IContextSource $context
2605 * @param array $options Assoc. array with options keys to check as keys. Defaults to $this->mOptions.
2606 * @return array the key => kind mapping data
2608 public function getOptionKinds( IContextSource $context, $options = null ) {
2609 $this->loadOptions();
2610 if ( $options === null ) {
2611 $options = $this->mOptions;
2614 $prefs = Preferences::getPreferences( $this, $context );
2615 $mapping = array();
2617 // Pull out the "special" options, so they don't get converted as
2618 // multiselect or checkmatrix.
2619 $specialOptions = array_fill_keys( Preferences::getSaveBlacklist(), true );
2620 foreach ( $specialOptions as $name => $value ) {
2621 unset( $prefs[$name] );
2624 // Multiselect and checkmatrix options are stored in the database with
2625 // one key per option, each having a boolean value. Extract those keys.
2626 $multiselectOptions = array();
2627 foreach ( $prefs as $name => $info ) {
2628 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2629 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2630 $opts = HTMLFormField::flattenOptions( $info['options'] );
2631 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2633 foreach ( $opts as $value ) {
2634 $multiselectOptions["$prefix$value"] = true;
2637 unset( $prefs[$name] );
2640 $checkmatrixOptions = array();
2641 foreach ( $prefs as $name => $info ) {
2642 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2643 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2644 $columns = HTMLFormField::flattenOptions( $info['columns'] );
2645 $rows = HTMLFormField::flattenOptions( $info['rows'] );
2646 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2648 foreach ( $columns as $column ) {
2649 foreach ( $rows as $row ) {
2650 $checkmatrixOptions["$prefix-$column-$row"] = true;
2654 unset( $prefs[$name] );
2658 // $value is ignored
2659 foreach ( $options as $key => $value ) {
2660 if ( isset( $prefs[$key] ) ) {
2661 $mapping[$key] = 'registered';
2662 } elseif ( isset( $multiselectOptions[$key] ) ) {
2663 $mapping[$key] = 'registered-multiselect';
2664 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2665 $mapping[$key] = 'registered-checkmatrix';
2666 } elseif ( isset( $specialOptions[$key] ) ) {
2667 $mapping[$key] = 'special';
2668 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2669 $mapping[$key] = 'userjs';
2670 } else {
2671 $mapping[$key] = 'unused';
2675 return $mapping;
2679 * Reset certain (or all) options to the site defaults
2681 * The optional parameter determines which kinds of preferences will be reset.
2682 * Supported values are everything that can be reported by getOptionKinds()
2683 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2685 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2686 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2687 * for backwards-compatibility.
2688 * @param IContextSource|null $context Context source used when $resetKinds
2689 * does not contain 'all', passed to getOptionKinds().
2690 * Defaults to RequestContext::getMain() when null.
2692 public function resetOptions(
2693 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2694 IContextSource $context = null
2696 $this->load();
2697 $defaultOptions = self::getDefaultOptions();
2699 if ( !is_array( $resetKinds ) ) {
2700 $resetKinds = array( $resetKinds );
2703 if ( in_array( 'all', $resetKinds ) ) {
2704 $newOptions = $defaultOptions;
2705 } else {
2706 if ( $context === null ) {
2707 $context = RequestContext::getMain();
2710 $optionKinds = $this->getOptionKinds( $context );
2711 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
2712 $newOptions = array();
2714 // Use default values for the options that should be deleted, and
2715 // copy old values for the ones that shouldn't.
2716 foreach ( $this->mOptions as $key => $value ) {
2717 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2718 if ( array_key_exists( $key, $defaultOptions ) ) {
2719 $newOptions[$key] = $defaultOptions[$key];
2721 } else {
2722 $newOptions[$key] = $value;
2727 $this->mOptions = $newOptions;
2728 $this->mOptionsLoaded = true;
2732 * Get the user's preferred date format.
2733 * @return string User's preferred date format
2735 public function getDatePreference() {
2736 // Important migration for old data rows
2737 if ( is_null( $this->mDatePreference ) ) {
2738 global $wgLang;
2739 $value = $this->getOption( 'date' );
2740 $map = $wgLang->getDatePreferenceMigrationMap();
2741 if ( isset( $map[$value] ) ) {
2742 $value = $map[$value];
2744 $this->mDatePreference = $value;
2746 return $this->mDatePreference;
2750 * Determine based on the wiki configuration and the user's options,
2751 * whether this user must be over HTTPS no matter what.
2753 * @return bool
2755 public function requiresHTTPS() {
2756 global $wgSecureLogin;
2757 if ( !$wgSecureLogin ) {
2758 return false;
2759 } else {
2760 $https = $this->getBoolOption( 'prefershttps' );
2761 wfRunHooks( 'UserRequiresHTTPS', array( $this, &$https ) );
2762 if ( $https ) {
2763 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2765 return $https;
2770 * Get the user preferred stub threshold
2772 * @return int
2774 public function getStubThreshold() {
2775 global $wgMaxArticleSize; # Maximum article size, in Kb
2776 $threshold = $this->getIntOption( 'stubthreshold' );
2777 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2778 // If they have set an impossible value, disable the preference
2779 // so we can use the parser cache again.
2780 $threshold = 0;
2782 return $threshold;
2786 * Get the permissions this user has.
2787 * @return array Array of String permission names
2789 public function getRights() {
2790 if ( is_null( $this->mRights ) ) {
2791 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2792 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
2793 // Force reindexation of rights when a hook has unset one of them
2794 $this->mRights = array_values( array_unique( $this->mRights ) );
2796 return $this->mRights;
2800 * Get the list of explicit group memberships this user has.
2801 * The implicit * and user groups are not included.
2802 * @return array Array of String internal group names
2804 public function getGroups() {
2805 $this->load();
2806 $this->loadGroups();
2807 return $this->mGroups;
2811 * Get the list of implicit group memberships this user has.
2812 * This includes all explicit groups, plus 'user' if logged in,
2813 * '*' for all accounts, and autopromoted groups
2814 * @param bool $recache Whether to avoid the cache
2815 * @return array Array of String internal group names
2817 public function getEffectiveGroups( $recache = false ) {
2818 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
2819 wfProfileIn( __METHOD__ );
2820 $this->mEffectiveGroups = array_unique( array_merge(
2821 $this->getGroups(), // explicit groups
2822 $this->getAutomaticGroups( $recache ) // implicit groups
2823 ) );
2824 // Hook for additional groups
2825 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
2826 // Force reindexation of groups when a hook has unset one of them
2827 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
2828 wfProfileOut( __METHOD__ );
2830 return $this->mEffectiveGroups;
2834 * Get the list of implicit group memberships this user has.
2835 * This includes 'user' if logged in, '*' for all accounts,
2836 * and autopromoted groups
2837 * @param bool $recache Whether to avoid the cache
2838 * @return array Array of String internal group names
2840 public function getAutomaticGroups( $recache = false ) {
2841 if ( $recache || is_null( $this->mImplicitGroups ) ) {
2842 wfProfileIn( __METHOD__ );
2843 $this->mImplicitGroups = array( '*' );
2844 if ( $this->getId() ) {
2845 $this->mImplicitGroups[] = 'user';
2847 $this->mImplicitGroups = array_unique( array_merge(
2848 $this->mImplicitGroups,
2849 Autopromote::getAutopromoteGroups( $this )
2850 ) );
2852 if ( $recache ) {
2853 // Assure data consistency with rights/groups,
2854 // as getEffectiveGroups() depends on this function
2855 $this->mEffectiveGroups = null;
2857 wfProfileOut( __METHOD__ );
2859 return $this->mImplicitGroups;
2863 * Returns the groups the user has belonged to.
2865 * The user may still belong to the returned groups. Compare with getGroups().
2867 * The function will not return groups the user had belonged to before MW 1.17
2869 * @return array Names of the groups the user has belonged to.
2871 public function getFormerGroups() {
2872 if ( is_null( $this->mFormerGroups ) ) {
2873 $dbr = wfGetDB( DB_MASTER );
2874 $res = $dbr->select( 'user_former_groups',
2875 array( 'ufg_group' ),
2876 array( 'ufg_user' => $this->mId ),
2877 __METHOD__ );
2878 $this->mFormerGroups = array();
2879 foreach ( $res as $row ) {
2880 $this->mFormerGroups[] = $row->ufg_group;
2883 return $this->mFormerGroups;
2887 * Get the user's edit count.
2888 * @return int|null null for anonymous users
2890 public function getEditCount() {
2891 if ( !$this->getId() ) {
2892 return null;
2895 if ( !isset( $this->mEditCount ) ) {
2896 /* Populate the count, if it has not been populated yet */
2897 wfProfileIn( __METHOD__ );
2898 $dbr = wfGetDB( DB_SLAVE );
2899 // check if the user_editcount field has been initialized
2900 $count = $dbr->selectField(
2901 'user', 'user_editcount',
2902 array( 'user_id' => $this->mId ),
2903 __METHOD__
2906 if ( $count === null ) {
2907 // it has not been initialized. do so.
2908 $count = $this->initEditCount();
2910 $this->mEditCount = $count;
2911 wfProfileOut( __METHOD__ );
2913 return (int)$this->mEditCount;
2917 * Add the user to the given group.
2918 * This takes immediate effect.
2919 * @param string $group Name of the group to add
2921 public function addGroup( $group ) {
2922 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2923 $dbw = wfGetDB( DB_MASTER );
2924 if ( $this->getId() ) {
2925 $dbw->insert( 'user_groups',
2926 array(
2927 'ug_user' => $this->getID(),
2928 'ug_group' => $group,
2930 __METHOD__,
2931 array( 'IGNORE' ) );
2934 $this->loadGroups();
2935 $this->mGroups[] = $group;
2936 // In case loadGroups was not called before, we now have the right twice.
2937 // Get rid of the duplicate.
2938 $this->mGroups = array_unique( $this->mGroups );
2940 // Refresh the groups caches, and clear the rights cache so it will be
2941 // refreshed on the next call to $this->getRights().
2942 $this->getEffectiveGroups( true );
2943 $this->mRights = null;
2945 $this->invalidateCache();
2949 * Remove the user from the given group.
2950 * This takes immediate effect.
2951 * @param string $group Name of the group to remove
2953 public function removeGroup( $group ) {
2954 $this->load();
2955 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
2956 $dbw = wfGetDB( DB_MASTER );
2957 $dbw->delete( 'user_groups',
2958 array(
2959 'ug_user' => $this->getID(),
2960 'ug_group' => $group,
2961 ), __METHOD__ );
2962 // Remember that the user was in this group
2963 $dbw->insert( 'user_former_groups',
2964 array(
2965 'ufg_user' => $this->getID(),
2966 'ufg_group' => $group,
2968 __METHOD__,
2969 array( 'IGNORE' ) );
2971 $this->loadGroups();
2972 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
2974 // Refresh the groups caches, and clear the rights cache so it will be
2975 // refreshed on the next call to $this->getRights().
2976 $this->getEffectiveGroups( true );
2977 $this->mRights = null;
2979 $this->invalidateCache();
2983 * Get whether the user is logged in
2984 * @return bool
2986 public function isLoggedIn() {
2987 return $this->getID() != 0;
2991 * Get whether the user is anonymous
2992 * @return bool
2994 public function isAnon() {
2995 return !$this->isLoggedIn();
2999 * Check if user is allowed to access a feature / make an action
3001 * @internal param \String $varargs permissions to test
3002 * @return bool True if user is allowed to perform *any* of the given actions
3004 * @return bool
3006 public function isAllowedAny( /*...*/ ) {
3007 $permissions = func_get_args();
3008 foreach ( $permissions as $permission ) {
3009 if ( $this->isAllowed( $permission ) ) {
3010 return true;
3013 return false;
3018 * @internal param $varargs string
3019 * @return bool True if the user is allowed to perform *all* of the given actions
3021 public function isAllowedAll( /*...*/ ) {
3022 $permissions = func_get_args();
3023 foreach ( $permissions as $permission ) {
3024 if ( !$this->isAllowed( $permission ) ) {
3025 return false;
3028 return true;
3032 * Internal mechanics of testing a permission
3033 * @param string $action
3034 * @return bool
3036 public function isAllowed( $action = '' ) {
3037 if ( $action === '' ) {
3038 return true; // In the spirit of DWIM
3040 // Patrolling may not be enabled
3041 if ( $action === 'patrol' || $action === 'autopatrol' ) {
3042 global $wgUseRCPatrol, $wgUseNPPatrol;
3043 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3044 return false;
3047 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3048 // by misconfiguration: 0 == 'foo'
3049 return in_array( $action, $this->getRights(), true );
3053 * Check whether to enable recent changes patrol features for this user
3054 * @return bool True or false
3056 public function useRCPatrol() {
3057 global $wgUseRCPatrol;
3058 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3062 * Check whether to enable new pages patrol features for this user
3063 * @return bool True or false
3065 public function useNPPatrol() {
3066 global $wgUseRCPatrol, $wgUseNPPatrol;
3067 return (
3068 ( $wgUseRCPatrol || $wgUseNPPatrol )
3069 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3074 * Get the WebRequest object to use with this object
3076 * @return WebRequest
3078 public function getRequest() {
3079 if ( $this->mRequest ) {
3080 return $this->mRequest;
3081 } else {
3082 global $wgRequest;
3083 return $wgRequest;
3088 * Get the current skin, loading it if required
3089 * @return Skin The current skin
3090 * @todo FIXME: Need to check the old failback system [AV]
3091 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3093 public function getSkin() {
3094 wfDeprecated( __METHOD__, '1.18' );
3095 return RequestContext::getMain()->getSkin();
3099 * Get a WatchedItem for this user and $title.
3101 * @since 1.22 $checkRights parameter added
3102 * @param Title $title
3103 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3104 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3105 * @return WatchedItem
3107 public function getWatchedItem( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3108 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3110 if ( isset( $this->mWatchedItems[$key] ) ) {
3111 return $this->mWatchedItems[$key];
3114 if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
3115 $this->mWatchedItems = array();
3118 $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title, $checkRights );
3119 return $this->mWatchedItems[$key];
3123 * Check the watched status of an article.
3124 * @since 1.22 $checkRights parameter added
3125 * @param Title $title Title of the article to look at
3126 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3127 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3128 * @return bool
3130 public function isWatched( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3131 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3135 * Watch an article.
3136 * @since 1.22 $checkRights parameter added
3137 * @param Title $title Title of the article to look at
3138 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3139 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3141 public function addWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3142 $this->getWatchedItem( $title, $checkRights )->addWatch();
3143 $this->invalidateCache();
3147 * Stop watching an article.
3148 * @since 1.22 $checkRights parameter added
3149 * @param Title $title Title of the article to look at
3150 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3151 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3153 public function removeWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3154 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3155 $this->invalidateCache();
3159 * Clear the user's notification timestamp for the given title.
3160 * If e-notif e-mails are on, they will receive notification mails on
3161 * the next change of the page if it's watched etc.
3162 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3163 * @param Title $title Title of the article to look at
3164 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3166 public function clearNotification( &$title, $oldid = 0 ) {
3167 global $wgUseEnotif, $wgShowUpdatedMarker;
3169 // Do nothing if the database is locked to writes
3170 if ( wfReadOnly() ) {
3171 return;
3174 // Do nothing if not allowed to edit the watchlist
3175 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3176 return;
3179 // If we're working on user's talk page, we should update the talk page message indicator
3180 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3181 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3182 return;
3185 $nextid = $oldid ? $title->getNextRevisionID( $oldid ) : null;
3187 if ( !$oldid || !$nextid ) {
3188 // If we're looking at the latest revision, we should definitely clear it
3189 $this->setNewtalk( false );
3190 } else {
3191 // Otherwise we should update its revision, if it's present
3192 if ( $this->getNewtalk() ) {
3193 // Naturally the other one won't clear by itself
3194 $this->setNewtalk( false );
3195 $this->setNewtalk( true, Revision::newFromId( $nextid ) );
3200 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3201 return;
3204 if ( $this->isAnon() ) {
3205 // Nothing else to do...
3206 return;
3209 // Only update the timestamp if the page is being watched.
3210 // The query to find out if it is watched is cached both in memcached and per-invocation,
3211 // and when it does have to be executed, it can be on a slave
3212 // If this is the user's newtalk page, we always update the timestamp
3213 $force = '';
3214 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3215 $force = 'force';
3218 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3222 * Resets all of the given user's page-change notification timestamps.
3223 * If e-notif e-mails are on, they will receive notification mails on
3224 * the next change of any watched page.
3225 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3227 public function clearAllNotifications() {
3228 if ( wfReadOnly() ) {
3229 return;
3232 // Do nothing if not allowed to edit the watchlist
3233 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3234 return;
3237 global $wgUseEnotif, $wgShowUpdatedMarker;
3238 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3239 $this->setNewtalk( false );
3240 return;
3242 $id = $this->getId();
3243 if ( $id != 0 ) {
3244 $dbw = wfGetDB( DB_MASTER );
3245 $dbw->update( 'watchlist',
3246 array( /* SET */ 'wl_notificationtimestamp' => null ),
3247 array( /* WHERE */ 'wl_user' => $id ),
3248 __METHOD__
3250 // We also need to clear here the "you have new message" notification for the own user_talk page;
3251 // it's cleared one page view later in WikiPage::doViewUpdates().
3256 * Set this user's options from an encoded string
3257 * @param string $str Encoded options to import
3259 * @deprecated since 1.19 due to removal of user_options from the user table
3261 private function decodeOptions( $str ) {
3262 wfDeprecated( __METHOD__, '1.19' );
3263 if ( !$str ) {
3264 return;
3267 $this->mOptionsLoaded = true;
3268 $this->mOptionOverrides = array();
3270 // If an option is not set in $str, use the default value
3271 $this->mOptions = self::getDefaultOptions();
3273 $a = explode( "\n", $str );
3274 foreach ( $a as $s ) {
3275 $m = array();
3276 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
3277 $this->mOptions[$m[1]] = $m[2];
3278 $this->mOptionOverrides[$m[1]] = $m[2];
3284 * Set a cookie on the user's client. Wrapper for
3285 * WebResponse::setCookie
3286 * @param string $name Name of the cookie to set
3287 * @param string $value Value to set
3288 * @param int $exp Expiration time, as a UNIX time value;
3289 * if 0 or not specified, use the default $wgCookieExpiration
3290 * @param bool $secure
3291 * true: Force setting the secure attribute when setting the cookie
3292 * false: Force NOT setting the secure attribute when setting the cookie
3293 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3294 * @param array $params Array of options sent passed to WebResponse::setcookie()
3296 protected function setCookie( $name, $value, $exp = 0, $secure = null, $params = array() ) {
3297 $params['secure'] = $secure;
3298 $this->getRequest()->response()->setcookie( $name, $value, $exp, $params );
3302 * Clear a cookie on the user's client
3303 * @param string $name Name of the cookie to clear
3304 * @param bool $secure
3305 * true: Force setting the secure attribute when setting the cookie
3306 * false: Force NOT setting the secure attribute when setting the cookie
3307 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3308 * @param array $params Array of options sent passed to WebResponse::setcookie()
3310 protected function clearCookie( $name, $secure = null, $params = array() ) {
3311 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3315 * Set the default cookies for this session on the user's client.
3317 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3318 * is passed.
3319 * @param bool $secure Whether to force secure/insecure cookies or use default
3320 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3322 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3323 if ( $request === null ) {
3324 $request = $this->getRequest();
3327 $this->load();
3328 if ( 0 == $this->mId ) {
3329 return;
3331 if ( !$this->mToken ) {
3332 // When token is empty or NULL generate a new one and then save it to the database
3333 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3334 // Simply by setting every cell in the user_token column to NULL and letting them be
3335 // regenerated as users log back into the wiki.
3336 $this->setToken();
3337 $this->saveSettings();
3339 $session = array(
3340 'wsUserID' => $this->mId,
3341 'wsToken' => $this->mToken,
3342 'wsUserName' => $this->getName()
3344 $cookies = array(
3345 'UserID' => $this->mId,
3346 'UserName' => $this->getName(),
3348 if ( $rememberMe ) {
3349 $cookies['Token'] = $this->mToken;
3350 } else {
3351 $cookies['Token'] = false;
3354 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3356 foreach ( $session as $name => $value ) {
3357 $request->setSessionData( $name, $value );
3359 foreach ( $cookies as $name => $value ) {
3360 if ( $value === false ) {
3361 $this->clearCookie( $name );
3362 } else {
3363 $this->setCookie( $name, $value, 0, $secure );
3368 * If wpStickHTTPS was selected, also set an insecure cookie that
3369 * will cause the site to redirect the user to HTTPS, if they access
3370 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3371 * as the one set by centralauth (bug 53538). Also set it to session, or
3372 * standard time setting, based on if rememberme was set.
3374 if ( $request->getCheck( 'wpStickHTTPS' ) || $this->requiresHTTPS() ) {
3375 $this->setCookie(
3376 'forceHTTPS',
3377 'true',
3378 $rememberMe ? 0 : null,
3379 false,
3380 array( 'prefix' => '' ) // no prefix
3386 * Log this user out.
3388 public function logout() {
3389 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3390 $this->doLogout();
3395 * Clear the user's cookies and session, and reset the instance cache.
3396 * @see logout()
3398 public function doLogout() {
3399 $this->clearInstanceCache( 'defaults' );
3401 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3403 $this->clearCookie( 'UserID' );
3404 $this->clearCookie( 'Token' );
3405 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3407 // Remember when user logged out, to prevent seeing cached pages
3408 $this->setCookie( 'LoggedOut', time(), time() + 86400 );
3412 * Save this user's settings into the database.
3413 * @todo Only rarely do all these fields need to be set!
3415 public function saveSettings() {
3416 global $wgAuth;
3418 $this->load();
3419 if ( wfReadOnly() ) {
3420 return;
3422 if ( 0 == $this->mId ) {
3423 return;
3426 $this->mTouched = self::newTouchedTimestamp();
3427 if ( !$wgAuth->allowSetLocalPassword() ) {
3428 $this->mPassword = '';
3431 $dbw = wfGetDB( DB_MASTER );
3432 $dbw->update( 'user',
3433 array( /* SET */
3434 'user_name' => $this->mName,
3435 'user_password' => $this->mPassword,
3436 'user_newpassword' => $this->mNewpassword,
3437 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3438 'user_real_name' => $this->mRealName,
3439 'user_email' => $this->mEmail,
3440 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3441 'user_touched' => $dbw->timestamp( $this->mTouched ),
3442 'user_token' => strval( $this->mToken ),
3443 'user_email_token' => $this->mEmailToken,
3444 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3445 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires ),
3446 ), array( /* WHERE */
3447 'user_id' => $this->mId
3448 ), __METHOD__
3451 $this->saveOptions();
3453 wfRunHooks( 'UserSaveSettings', array( $this ) );
3454 $this->clearSharedCache();
3455 $this->getUserPage()->invalidateCache();
3459 * If only this user's username is known, and it exists, return the user ID.
3460 * @return int
3462 public function idForName() {
3463 $s = trim( $this->getName() );
3464 if ( $s === '' ) {
3465 return 0;
3468 $dbr = wfGetDB( DB_SLAVE );
3469 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
3470 if ( $id === false ) {
3471 $id = 0;
3473 return $id;
3477 * Add a user to the database, return the user object
3479 * @param string $name Username to add
3480 * @param array $params Array of Strings Non-default parameters to save to the database as user_* fields:
3481 * - password The user's password hash. Password logins will be disabled if this is omitted.
3482 * - newpassword Hash for a temporary password that has been mailed to the user
3483 * - email The user's email address
3484 * - email_authenticated The email authentication timestamp
3485 * - real_name The user's real name
3486 * - options An associative array of non-default options
3487 * - token Random authentication token. Do not set.
3488 * - registration Registration timestamp. Do not set.
3490 * @return User|null User object, or null if the username already exists
3492 public static function createNew( $name, $params = array() ) {
3493 $user = new User;
3494 $user->load();
3495 $user->setToken(); // init token
3496 if ( isset( $params['options'] ) ) {
3497 $user->mOptions = $params['options'] + (array)$user->mOptions;
3498 unset( $params['options'] );
3500 $dbw = wfGetDB( DB_MASTER );
3501 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3503 $fields = array(
3504 'user_id' => $seqVal,
3505 'user_name' => $name,
3506 'user_password' => $user->mPassword,
3507 'user_newpassword' => $user->mNewpassword,
3508 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
3509 'user_email' => $user->mEmail,
3510 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3511 'user_real_name' => $user->mRealName,
3512 'user_token' => strval( $user->mToken ),
3513 'user_registration' => $dbw->timestamp( $user->mRegistration ),
3514 'user_editcount' => 0,
3515 'user_touched' => $dbw->timestamp( self::newTouchedTimestamp() ),
3517 foreach ( $params as $name => $value ) {
3518 $fields["user_$name"] = $value;
3520 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
3521 if ( $dbw->affectedRows() ) {
3522 $newUser = User::newFromId( $dbw->insertId() );
3523 } else {
3524 $newUser = null;
3526 return $newUser;
3530 * Add this existing user object to the database. If the user already
3531 * exists, a fatal status object is returned, and the user object is
3532 * initialised with the data from the database.
3534 * Previously, this function generated a DB error due to a key conflict
3535 * if the user already existed. Many extension callers use this function
3536 * in code along the lines of:
3538 * $user = User::newFromName( $name );
3539 * if ( !$user->isLoggedIn() ) {
3540 * $user->addToDatabase();
3542 * // do something with $user...
3544 * However, this was vulnerable to a race condition (bug 16020). By
3545 * initialising the user object if the user exists, we aim to support this
3546 * calling sequence as far as possible.
3548 * Note that if the user exists, this function will acquire a write lock,
3549 * so it is still advisable to make the call conditional on isLoggedIn(),
3550 * and to commit the transaction after calling.
3552 * @throws MWException
3553 * @return Status
3555 public function addToDatabase() {
3556 $this->load();
3557 if ( !$this->mToken ) {
3558 $this->setToken(); // init token
3561 $this->mTouched = self::newTouchedTimestamp();
3563 $dbw = wfGetDB( DB_MASTER );
3564 $inWrite = $dbw->writesOrCallbacksPending();
3565 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3566 $dbw->insert( 'user',
3567 array(
3568 'user_id' => $seqVal,
3569 'user_name' => $this->mName,
3570 'user_password' => $this->mPassword,
3571 'user_newpassword' => $this->mNewpassword,
3572 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3573 'user_email' => $this->mEmail,
3574 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3575 'user_real_name' => $this->mRealName,
3576 'user_token' => strval( $this->mToken ),
3577 'user_registration' => $dbw->timestamp( $this->mRegistration ),
3578 'user_editcount' => 0,
3579 'user_touched' => $dbw->timestamp( $this->mTouched ),
3580 ), __METHOD__,
3581 array( 'IGNORE' )
3583 if ( !$dbw->affectedRows() ) {
3584 if ( !$inWrite ) {
3585 // XXX: Get out of REPEATABLE-READ so the SELECT below works.
3586 // Often this case happens early in views before any writes.
3587 // This shows up at least with CentralAuth.
3588 $dbw->commit( __METHOD__, 'flush' );
3590 $this->mId = $dbw->selectField( 'user', 'user_id',
3591 array( 'user_name' => $this->mName ), __METHOD__ );
3592 $loaded = false;
3593 if ( $this->mId ) {
3594 if ( $this->loadFromDatabase() ) {
3595 $loaded = true;
3598 if ( !$loaded ) {
3599 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
3600 "to insert user '{$this->mName}' row, but it was not present in select!" );
3602 return Status::newFatal( 'userexists' );
3604 $this->mId = $dbw->insertId();
3606 // Clear instance cache other than user table data, which is already accurate
3607 $this->clearInstanceCache();
3609 $this->saveOptions();
3610 return Status::newGood();
3614 * If this user is logged-in and blocked,
3615 * block any IP address they've successfully logged in from.
3616 * @return bool A block was spread
3618 public function spreadAnyEditBlock() {
3619 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3620 return $this->spreadBlock();
3622 return false;
3626 * If this (non-anonymous) user is blocked,
3627 * block the IP address they've successfully logged in from.
3628 * @return bool A block was spread
3630 protected function spreadBlock() {
3631 wfDebug( __METHOD__ . "()\n" );
3632 $this->load();
3633 if ( $this->mId == 0 ) {
3634 return false;
3637 $userblock = Block::newFromTarget( $this->getName() );
3638 if ( !$userblock ) {
3639 return false;
3642 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3646 * Get whether the user is explicitly blocked from account creation.
3647 * @return bool|Block
3649 public function isBlockedFromCreateAccount() {
3650 $this->getBlockedStatus();
3651 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
3652 return $this->mBlock;
3655 # bug 13611: if the IP address the user is trying to create an account from is
3656 # blocked with createaccount disabled, prevent new account creation there even
3657 # when the user is logged in
3658 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3659 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
3661 return $this->mBlockedFromCreateAccount instanceof Block && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
3662 ? $this->mBlockedFromCreateAccount
3663 : false;
3667 * Get whether the user is blocked from using Special:Emailuser.
3668 * @return bool
3670 public function isBlockedFromEmailuser() {
3671 $this->getBlockedStatus();
3672 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
3676 * Get whether the user is allowed to create an account.
3677 * @return bool
3679 public function isAllowedToCreateAccount() {
3680 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3684 * Get this user's personal page title.
3686 * @return Title User's personal page title
3688 public function getUserPage() {
3689 return Title::makeTitle( NS_USER, $this->getName() );
3693 * Get this user's talk page title.
3695 * @return Title User's talk page title
3697 public function getTalkPage() {
3698 $title = $this->getUserPage();
3699 return $title->getTalkPage();
3703 * Determine whether the user is a newbie. Newbies are either
3704 * anonymous IPs, or the most recently created accounts.
3705 * @return bool
3707 public function isNewbie() {
3708 return !$this->isAllowed( 'autoconfirmed' );
3712 * Check to see if the given clear-text password is one of the accepted passwords
3713 * @param string $password user password.
3714 * @return bool True if the given password is correct, otherwise False.
3716 public function checkPassword( $password ) {
3717 global $wgAuth, $wgLegacyEncoding;
3718 $this->load();
3720 // Certain authentication plugins do NOT want to save
3721 // domain passwords in a mysql database, so we should
3722 // check this (in case $wgAuth->strict() is false).
3724 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3725 return true;
3726 } elseif ( $wgAuth->strict() ) {
3727 // Auth plugin doesn't allow local authentication
3728 return false;
3729 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3730 // Auth plugin doesn't allow local authentication for this user name
3731 return false;
3733 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
3734 return true;
3735 } elseif ( $wgLegacyEncoding ) {
3736 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3737 // Check for this with iconv
3738 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3739 if ( $cp1252Password != $password
3740 && self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId )
3742 return true;
3745 return false;
3749 * Check if the given clear-text password matches the temporary password
3750 * sent by e-mail for password reset operations.
3752 * @param string $plaintext
3754 * @return bool True if matches, false otherwise
3756 public function checkTemporaryPassword( $plaintext ) {
3757 global $wgNewPasswordExpiry;
3759 $this->load();
3760 if ( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) {
3761 if ( is_null( $this->mNewpassTime ) ) {
3762 return true;
3764 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
3765 return ( time() < $expiry );
3766 } else {
3767 return false;
3772 * Alias for getEditToken.
3773 * @deprecated since 1.19, use getEditToken instead.
3775 * @param string|array $salt of Strings Optional function-specific data for hashing
3776 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3777 * @return string The new edit token
3779 public function editToken( $salt = '', $request = null ) {
3780 wfDeprecated( __METHOD__, '1.19' );
3781 return $this->getEditToken( $salt, $request );
3785 * Initialize (if necessary) and return a session token value
3786 * which can be used in edit forms to show that the user's
3787 * login credentials aren't being hijacked with a foreign form
3788 * submission.
3790 * @since 1.19
3792 * @param string|array $salt of Strings Optional function-specific data for hashing
3793 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3794 * @return string The new edit token
3796 public function getEditToken( $salt = '', $request = null ) {
3797 if ( $request == null ) {
3798 $request = $this->getRequest();
3801 if ( $this->isAnon() ) {
3802 return EDIT_TOKEN_SUFFIX;
3803 } else {
3804 $token = $request->getSessionData( 'wsEditToken' );
3805 if ( $token === null ) {
3806 $token = MWCryptRand::generateHex( 32 );
3807 $request->setSessionData( 'wsEditToken', $token );
3809 if ( is_array( $salt ) ) {
3810 $salt = implode( '|', $salt );
3812 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
3817 * Generate a looking random token for various uses.
3819 * @return string The new random token
3820 * @deprecated since 1.20: Use MWCryptRand for secure purposes or wfRandomString for pseudo-randomness
3822 public static function generateToken() {
3823 return MWCryptRand::generateHex( 32 );
3827 * Check given value against the token value stored in the session.
3828 * A match should confirm that the form was submitted from the
3829 * user's own login session, not a form submission from a third-party
3830 * site.
3832 * @param string $val Input value to compare
3833 * @param string $salt Optional function-specific data for hashing
3834 * @param WebRequest|null $request Object to use or null to use $wgRequest
3835 * @return bool Whether the token matches
3837 public function matchEditToken( $val, $salt = '', $request = null ) {
3838 $sessionToken = $this->getEditToken( $salt, $request );
3839 if ( $val != $sessionToken ) {
3840 wfDebug( "User::matchEditToken: broken session data\n" );
3842 return $val == $sessionToken;
3846 * Check given value against the token value stored in the session,
3847 * ignoring the suffix.
3849 * @param string $val Input value to compare
3850 * @param string $salt Optional function-specific data for hashing
3851 * @param WebRequest|null $request object to use or null to use $wgRequest
3852 * @return bool Whether the token matches
3854 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3855 $sessionToken = $this->getEditToken( $salt, $request );
3856 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3860 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3861 * mail to the user's given address.
3863 * @param string $type Message to send, either "created", "changed" or "set"
3864 * @return Status
3866 public function sendConfirmationMail( $type = 'created' ) {
3867 global $wgLang;
3868 $expiration = null; // gets passed-by-ref and defined in next line.
3869 $token = $this->confirmationToken( $expiration );
3870 $url = $this->confirmationTokenUrl( $token );
3871 $invalidateURL = $this->invalidationTokenUrl( $token );
3872 $this->saveSettings();
3874 if ( $type == 'created' || $type === false ) {
3875 $message = 'confirmemail_body';
3876 } elseif ( $type === true ) {
3877 $message = 'confirmemail_body_changed';
3878 } else {
3879 // Messages: confirmemail_body_changed, confirmemail_body_set
3880 $message = 'confirmemail_body_' . $type;
3883 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3884 wfMessage( $message,
3885 $this->getRequest()->getIP(),
3886 $this->getName(),
3887 $url,
3888 $wgLang->timeanddate( $expiration, false ),
3889 $invalidateURL,
3890 $wgLang->date( $expiration, false ),
3891 $wgLang->time( $expiration, false ) )->text() );
3895 * Send an e-mail to this user's account. Does not check for
3896 * confirmed status or validity.
3898 * @param string $subject Message subject
3899 * @param string $body Message body
3900 * @param string $from Optional From address; if unspecified, default $wgPasswordSender will be used
3901 * @param string $replyto Reply-To address
3902 * @return Status
3904 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3905 if ( is_null( $from ) ) {
3906 global $wgPasswordSender;
3907 $sender = new MailAddress( $wgPasswordSender,
3908 wfMessage( 'emailsender' )->inContentLanguage()->text() );
3909 } else {
3910 $sender = new MailAddress( $from );
3913 $to = new MailAddress( $this );
3914 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
3918 * Generate, store, and return a new e-mail confirmation code.
3919 * A hash (unsalted, since it's used as a key) is stored.
3921 * @note Call saveSettings() after calling this function to commit
3922 * this change to the database.
3924 * @param string &$expiration Accepts the expiration time
3925 * @return string New token
3927 protected function confirmationToken( &$expiration ) {
3928 global $wgUserEmailConfirmationTokenExpiry;
3929 $now = time();
3930 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
3931 $expiration = wfTimestamp( TS_MW, $expires );
3932 $this->load();
3933 $token = MWCryptRand::generateHex( 32 );
3934 $hash = md5( $token );
3935 $this->mEmailToken = $hash;
3936 $this->mEmailTokenExpires = $expiration;
3937 return $token;
3941 * Return a URL the user can use to confirm their email address.
3942 * @param string $token Accepts the email confirmation token
3943 * @return string New token URL
3945 protected function confirmationTokenUrl( $token ) {
3946 return $this->getTokenUrl( 'ConfirmEmail', $token );
3950 * Return a URL the user can use to invalidate their email address.
3951 * @param string $token Accepts the email confirmation token
3952 * @return string New token URL
3954 protected function invalidationTokenUrl( $token ) {
3955 return $this->getTokenUrl( 'InvalidateEmail', $token );
3959 * Internal function to format the e-mail validation/invalidation URLs.
3960 * This uses a quickie hack to use the
3961 * hardcoded English names of the Special: pages, for ASCII safety.
3963 * @note Since these URLs get dropped directly into emails, using the
3964 * short English names avoids insanely long URL-encoded links, which
3965 * also sometimes can get corrupted in some browsers/mailers
3966 * (bug 6957 with Gmail and Internet Explorer).
3968 * @param string $page Special page
3969 * @param string $token Token
3970 * @return string Formatted URL
3972 protected function getTokenUrl( $page, $token ) {
3973 // Hack to bypass localization of 'Special:'
3974 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
3975 return $title->getCanonicalURL();
3979 * Mark the e-mail address confirmed.
3981 * @note Call saveSettings() after calling this function to commit the change.
3983 * @return bool
3985 public function confirmEmail() {
3986 // Check if it's already confirmed, so we don't touch the database
3987 // and fire the ConfirmEmailComplete hook on redundant confirmations.
3988 if ( !$this->isEmailConfirmed() ) {
3989 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3990 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3992 return true;
3996 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3997 * address if it was already confirmed.
3999 * @note Call saveSettings() after calling this function to commit the change.
4000 * @return bool Returns true
4002 public function invalidateEmail() {
4003 $this->load();
4004 $this->mEmailToken = null;
4005 $this->mEmailTokenExpires = null;
4006 $this->setEmailAuthenticationTimestamp( null );
4007 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
4008 return true;
4012 * Set the e-mail authentication timestamp.
4013 * @param string $timestamp TS_MW timestamp
4015 public function setEmailAuthenticationTimestamp( $timestamp ) {
4016 $this->load();
4017 $this->mEmailAuthenticated = $timestamp;
4018 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
4022 * Is this user allowed to send e-mails within limits of current
4023 * site configuration?
4024 * @return bool
4026 public function canSendEmail() {
4027 global $wgEnableEmail, $wgEnableUserEmail;
4028 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4029 return false;
4031 $canSend = $this->isEmailConfirmed();
4032 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
4033 return $canSend;
4037 * Is this user allowed to receive e-mails within limits of current
4038 * site configuration?
4039 * @return bool
4041 public function canReceiveEmail() {
4042 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4046 * Is this user's e-mail address valid-looking and confirmed within
4047 * limits of the current site configuration?
4049 * @note If $wgEmailAuthentication is on, this may require the user to have
4050 * confirmed their address by returning a code or using a password
4051 * sent to the address from the wiki.
4053 * @return bool
4055 public function isEmailConfirmed() {
4056 global $wgEmailAuthentication;
4057 $this->load();
4058 $confirmed = true;
4059 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4060 if ( $this->isAnon() ) {
4061 return false;
4063 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4064 return false;
4066 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4067 return false;
4069 return true;
4070 } else {
4071 return $confirmed;
4076 * Check whether there is an outstanding request for e-mail confirmation.
4077 * @return bool
4079 public function isEmailConfirmationPending() {
4080 global $wgEmailAuthentication;
4081 return $wgEmailAuthentication &&
4082 !$this->isEmailConfirmed() &&
4083 $this->mEmailToken &&
4084 $this->mEmailTokenExpires > wfTimestamp();
4088 * Get the timestamp of account creation.
4090 * @return string|bool|null Timestamp of account creation, false for
4091 * non-existent/anonymous user accounts, or null if existing account
4092 * but information is not in database.
4094 public function getRegistration() {
4095 if ( $this->isAnon() ) {
4096 return false;
4098 $this->load();
4099 return $this->mRegistration;
4103 * Get the timestamp of the first edit
4105 * @return string|bool Timestamp of first edit, or false for
4106 * non-existent/anonymous user accounts.
4108 public function getFirstEditTimestamp() {
4109 if ( $this->getId() == 0 ) {
4110 return false; // anons
4112 $dbr = wfGetDB( DB_SLAVE );
4113 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4114 array( 'rev_user' => $this->getId() ),
4115 __METHOD__,
4116 array( 'ORDER BY' => 'rev_timestamp ASC' )
4118 if ( !$time ) {
4119 return false; // no edits
4121 return wfTimestamp( TS_MW, $time );
4125 * Get the permissions associated with a given list of groups
4127 * @param array $groups Array of Strings List of internal group names
4128 * @return array Array of Strings List of permission key names for given groups combined
4130 public static function getGroupPermissions( $groups ) {
4131 global $wgGroupPermissions, $wgRevokePermissions;
4132 $rights = array();
4133 // grant every granted permission first
4134 foreach ( $groups as $group ) {
4135 if ( isset( $wgGroupPermissions[$group] ) ) {
4136 $rights = array_merge( $rights,
4137 // array_filter removes empty items
4138 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4141 // now revoke the revoked permissions
4142 foreach ( $groups as $group ) {
4143 if ( isset( $wgRevokePermissions[$group] ) ) {
4144 $rights = array_diff( $rights,
4145 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4148 return array_unique( $rights );
4152 * Get all the groups who have a given permission
4154 * @param string $role Role to check
4155 * @return array Array of Strings List of internal group names with the given permission
4157 public static function getGroupsWithPermission( $role ) {
4158 global $wgGroupPermissions;
4159 $allowedGroups = array();
4160 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4161 if ( self::groupHasPermission( $group, $role ) ) {
4162 $allowedGroups[] = $group;
4165 return $allowedGroups;
4169 * Check, if the given group has the given permission
4171 * If you're wanting to check whether all users have a permission, use
4172 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4173 * from anyone.
4175 * @since 1.21
4176 * @param string $group Group to check
4177 * @param string $role Role to check
4178 * @return bool
4180 public static function groupHasPermission( $group, $role ) {
4181 global $wgGroupPermissions, $wgRevokePermissions;
4182 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4183 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4187 * Check if all users have the given permission
4189 * @since 1.22
4190 * @param string $right Right to check
4191 * @return bool
4193 public static function isEveryoneAllowed( $right ) {
4194 global $wgGroupPermissions, $wgRevokePermissions;
4195 static $cache = array();
4197 // Use the cached results, except in unit tests which rely on
4198 // being able change the permission mid-request
4199 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4200 return $cache[$right];
4203 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
4204 $cache[$right] = false;
4205 return false;
4208 // If it's revoked anywhere, then everyone doesn't have it
4209 foreach ( $wgRevokePermissions as $rights ) {
4210 if ( isset( $rights[$right] ) && $rights[$right] ) {
4211 $cache[$right] = false;
4212 return false;
4216 // Allow extensions (e.g. OAuth) to say false
4217 if ( !wfRunHooks( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4218 $cache[$right] = false;
4219 return false;
4222 $cache[$right] = true;
4223 return true;
4227 * Get the localized descriptive name for a group, if it exists
4229 * @param string $group Internal group name
4230 * @return string Localized descriptive group name
4232 public static function getGroupName( $group ) {
4233 $msg = wfMessage( "group-$group" );
4234 return $msg->isBlank() ? $group : $msg->text();
4238 * Get the localized descriptive name for a member of a group, if it exists
4240 * @param string $group Internal group name
4241 * @param string $username Username for gender (since 1.19)
4242 * @return string Localized name for group member
4244 public static function getGroupMember( $group, $username = '#' ) {
4245 $msg = wfMessage( "group-$group-member", $username );
4246 return $msg->isBlank() ? $group : $msg->text();
4250 * Return the set of defined explicit groups.
4251 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4252 * are not included, as they are defined automatically, not in the database.
4253 * @return array Array of internal group names
4255 public static function getAllGroups() {
4256 global $wgGroupPermissions, $wgRevokePermissions;
4257 return array_diff(
4258 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4259 self::getImplicitGroups()
4264 * Get a list of all available permissions.
4265 * @return array Array of permission names
4267 public static function getAllRights() {
4268 if ( self::$mAllRights === false ) {
4269 global $wgAvailableRights;
4270 if ( count( $wgAvailableRights ) ) {
4271 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
4272 } else {
4273 self::$mAllRights = self::$mCoreRights;
4275 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
4277 return self::$mAllRights;
4281 * Get a list of implicit groups
4282 * @return array Array of Strings Array of internal group names
4284 public static function getImplicitGroups() {
4285 global $wgImplicitGroups;
4286 $groups = $wgImplicitGroups;
4287 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
4288 return $groups;
4292 * Get the title of a page describing a particular group
4294 * @param string $group Internal group name
4295 * @return Title|bool Title of the page if it exists, false otherwise
4297 public static function getGroupPage( $group ) {
4298 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4299 if ( $msg->exists() ) {
4300 $title = Title::newFromText( $msg->text() );
4301 if ( is_object( $title ) ) {
4302 return $title;
4305 return false;
4309 * Create a link to the group in HTML, if available;
4310 * else return the group name.
4312 * @param string $group Internal name of the group
4313 * @param string $text The text of the link
4314 * @return string HTML link to the group
4316 public static function makeGroupLinkHTML( $group, $text = '' ) {
4317 if ( $text == '' ) {
4318 $text = self::getGroupName( $group );
4320 $title = self::getGroupPage( $group );
4321 if ( $title ) {
4322 return Linker::link( $title, htmlspecialchars( $text ) );
4323 } else {
4324 return $text;
4329 * Create a link to the group in Wikitext, if available;
4330 * else return the group name.
4332 * @param string $group Internal name of the group
4333 * @param string $text The text of the link
4334 * @return string Wikilink to the group
4336 public static function makeGroupLinkWiki( $group, $text = '' ) {
4337 if ( $text == '' ) {
4338 $text = self::getGroupName( $group );
4340 $title = self::getGroupPage( $group );
4341 if ( $title ) {
4342 $page = $title->getPrefixedText();
4343 return "[[$page|$text]]";
4344 } else {
4345 return $text;
4350 * Returns an array of the groups that a particular group can add/remove.
4352 * @param string $group The group to check for whether it can add/remove
4353 * @return array array( 'add' => array( addablegroups ),
4354 * 'remove' => array( removablegroups ),
4355 * 'add-self' => array( addablegroups to self),
4356 * 'remove-self' => array( removable groups from self) )
4358 public static function changeableByGroup( $group ) {
4359 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4361 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
4362 if ( empty( $wgAddGroups[$group] ) ) {
4363 // Don't add anything to $groups
4364 } elseif ( $wgAddGroups[$group] === true ) {
4365 // You get everything
4366 $groups['add'] = self::getAllGroups();
4367 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4368 $groups['add'] = $wgAddGroups[$group];
4371 // Same thing for remove
4372 if ( empty( $wgRemoveGroups[$group] ) ) {
4373 } elseif ( $wgRemoveGroups[$group] === true ) {
4374 $groups['remove'] = self::getAllGroups();
4375 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4376 $groups['remove'] = $wgRemoveGroups[$group];
4379 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4380 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4381 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4382 if ( is_int( $key ) ) {
4383 $wgGroupsAddToSelf['user'][] = $value;
4388 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4389 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4390 if ( is_int( $key ) ) {
4391 $wgGroupsRemoveFromSelf['user'][] = $value;
4396 // Now figure out what groups the user can add to him/herself
4397 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4398 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4399 // No idea WHY this would be used, but it's there
4400 $groups['add-self'] = User::getAllGroups();
4401 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4402 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4405 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4406 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4407 $groups['remove-self'] = User::getAllGroups();
4408 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4409 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4412 return $groups;
4416 * Returns an array of groups that this user can add and remove
4417 * @return array array( 'add' => array( addablegroups ),
4418 * 'remove' => array( removablegroups ),
4419 * 'add-self' => array( addablegroups to self),
4420 * 'remove-self' => array( removable groups from self) )
4422 public function changeableGroups() {
4423 if ( $this->isAllowed( 'userrights' ) ) {
4424 // This group gives the right to modify everything (reverse-
4425 // compatibility with old "userrights lets you change
4426 // everything")
4427 // Using array_merge to make the groups reindexed
4428 $all = array_merge( User::getAllGroups() );
4429 return array(
4430 'add' => $all,
4431 'remove' => $all,
4432 'add-self' => array(),
4433 'remove-self' => array()
4437 // Okay, it's not so simple, we will have to go through the arrays
4438 $groups = array(
4439 'add' => array(),
4440 'remove' => array(),
4441 'add-self' => array(),
4442 'remove-self' => array()
4444 $addergroups = $this->getEffectiveGroups();
4446 foreach ( $addergroups as $addergroup ) {
4447 $groups = array_merge_recursive(
4448 $groups, $this->changeableByGroup( $addergroup )
4450 $groups['add'] = array_unique( $groups['add'] );
4451 $groups['remove'] = array_unique( $groups['remove'] );
4452 $groups['add-self'] = array_unique( $groups['add-self'] );
4453 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4455 return $groups;
4459 * Increment the user's edit-count field.
4460 * Will have no effect for anonymous users.
4462 public function incEditCount() {
4463 if ( !$this->isAnon() ) {
4464 $dbw = wfGetDB( DB_MASTER );
4465 $dbw->update(
4466 'user',
4467 array( 'user_editcount=user_editcount+1' ),
4468 array( 'user_id' => $this->getId() ),
4469 __METHOD__
4472 // Lazy initialization check...
4473 if ( $dbw->affectedRows() == 0 ) {
4474 // Now here's a goddamn hack...
4475 $dbr = wfGetDB( DB_SLAVE );
4476 if ( $dbr !== $dbw ) {
4477 // If we actually have a slave server, the count is
4478 // at least one behind because the current transaction
4479 // has not been committed and replicated.
4480 $this->initEditCount( 1 );
4481 } else {
4482 // But if DB_SLAVE is selecting the master, then the
4483 // count we just read includes the revision that was
4484 // just added in the working transaction.
4485 $this->initEditCount();
4489 // edit count in user cache too
4490 $this->invalidateCache();
4494 * Initialize user_editcount from data out of the revision table
4496 * @param int $add Edits to add to the count from the revision table
4497 * @return int Number of edits
4499 protected function initEditCount( $add = 0 ) {
4500 // Pull from a slave to be less cruel to servers
4501 // Accuracy isn't the point anyway here
4502 $dbr = wfGetDB( DB_SLAVE );
4503 $count = (int)$dbr->selectField(
4504 'revision',
4505 'COUNT(rev_user)',
4506 array( 'rev_user' => $this->getId() ),
4507 __METHOD__
4509 $count = $count + $add;
4511 $dbw = wfGetDB( DB_MASTER );
4512 $dbw->update(
4513 'user',
4514 array( 'user_editcount' => $count ),
4515 array( 'user_id' => $this->getId() ),
4516 __METHOD__
4519 return $count;
4523 * Get the description of a given right
4525 * @param string $right Right to query
4526 * @return string Localized description of the right
4528 public static function getRightDescription( $right ) {
4529 $key = "right-$right";
4530 $msg = wfMessage( $key );
4531 return $msg->isBlank() ? $right : $msg->text();
4535 * Make an old-style password hash
4537 * @param string $password Plain-text password
4538 * @param string $userId User ID
4539 * @return string Password hash
4541 public static function oldCrypt( $password, $userId ) {
4542 global $wgPasswordSalt;
4543 if ( $wgPasswordSalt ) {
4544 return md5( $userId . '-' . md5( $password ) );
4545 } else {
4546 return md5( $password );
4551 * Make a new-style password hash
4553 * @param string $password Plain-text password
4554 * @param bool|string $salt Optional salt, may be random or the user ID.
4555 * If unspecified or false, will generate one automatically
4556 * @return string Password hash
4558 public static function crypt( $password, $salt = false ) {
4559 global $wgPasswordSalt;
4561 $hash = '';
4562 if ( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
4563 return $hash;
4566 if ( $wgPasswordSalt ) {
4567 if ( $salt === false ) {
4568 $salt = MWCryptRand::generateHex( 8 );
4570 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
4571 } else {
4572 return ':A:' . md5( $password );
4577 * Compare a password hash with a plain-text password. Requires the user
4578 * ID if there's a chance that the hash is an old-style hash.
4580 * @param string $hash Password hash
4581 * @param string $password Plain-text password to compare
4582 * @param string|bool $userId User ID for old-style password salt
4584 * @return bool
4586 public static function comparePasswords( $hash, $password, $userId = false ) {
4587 $type = substr( $hash, 0, 3 );
4589 $result = false;
4590 if ( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
4591 return $result;
4594 if ( $type == ':A:' ) {
4595 // Unsalted
4596 return md5( $password ) === substr( $hash, 3 );
4597 } elseif ( $type == ':B:' ) {
4598 // Salted
4599 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
4600 return md5( $salt . '-' . md5( $password ) ) === $realHash;
4601 } else {
4602 // Old-style
4603 return self::oldCrypt( $password, $userId ) === $hash;
4608 * Add a newuser log entry for this user.
4609 * Before 1.19 the return value was always true.
4611 * @param string|bool $action Account creation type.
4612 * - String, one of the following values:
4613 * - 'create' for an anonymous user creating an account for himself.
4614 * This will force the action's performer to be the created user itself,
4615 * no matter the value of $wgUser
4616 * - 'create2' for a logged in user creating an account for someone else
4617 * - 'byemail' when the created user will receive its password by e-mail
4618 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4619 * - Boolean means whether the account was created by e-mail (deprecated):
4620 * - true will be converted to 'byemail'
4621 * - false will be converted to 'create' if this object is the same as
4622 * $wgUser and to 'create2' otherwise
4624 * @param string $reason User supplied reason
4626 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4628 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4629 global $wgUser, $wgNewUserLog;
4630 if ( empty( $wgNewUserLog ) ) {
4631 return true; // disabled
4634 if ( $action === true ) {
4635 $action = 'byemail';
4636 } elseif ( $action === false ) {
4637 if ( $this->getName() == $wgUser->getName() ) {
4638 $action = 'create';
4639 } else {
4640 $action = 'create2';
4644 if ( $action === 'create' || $action === 'autocreate' ) {
4645 $performer = $this;
4646 } else {
4647 $performer = $wgUser;
4650 $logEntry = new ManualLogEntry( 'newusers', $action );
4651 $logEntry->setPerformer( $performer );
4652 $logEntry->setTarget( $this->getUserPage() );
4653 $logEntry->setComment( $reason );
4654 $logEntry->setParameters( array(
4655 '4::userid' => $this->getId(),
4656 ) );
4657 $logid = $logEntry->insert();
4659 if ( $action !== 'autocreate' ) {
4660 $logEntry->publish( $logid );
4663 return (int)$logid;
4667 * Add an autocreate newuser log entry for this user
4668 * Used by things like CentralAuth and perhaps other authplugins.
4669 * Consider calling addNewUserLogEntry() directly instead.
4671 * @return bool
4673 public function addNewUserLogEntryAutoCreate() {
4674 $this->addNewUserLogEntry( 'autocreate' );
4676 return true;
4680 * Load the user options either from cache, the database or an array
4682 * @param array $data Rows for the current user out of the user_properties table
4684 protected function loadOptions( $data = null ) {
4685 global $wgContLang;
4687 $this->load();
4689 if ( $this->mOptionsLoaded ) {
4690 return;
4693 $this->mOptions = self::getDefaultOptions();
4695 if ( !$this->getId() ) {
4696 // For unlogged-in users, load language/variant options from request.
4697 // There's no need to do it for logged-in users: they can set preferences,
4698 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4699 // so don't override user's choice (especially when the user chooses site default).
4700 $variant = $wgContLang->getDefaultVariant();
4701 $this->mOptions['variant'] = $variant;
4702 $this->mOptions['language'] = $variant;
4703 $this->mOptionsLoaded = true;
4704 return;
4707 // Maybe load from the object
4708 if ( !is_null( $this->mOptionOverrides ) ) {
4709 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4710 foreach ( $this->mOptionOverrides as $key => $value ) {
4711 $this->mOptions[$key] = $value;
4713 } else {
4714 if ( !is_array( $data ) ) {
4715 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4716 // Load from database
4717 $dbr = wfGetDB( DB_SLAVE );
4719 $res = $dbr->select(
4720 'user_properties',
4721 array( 'up_property', 'up_value' ),
4722 array( 'up_user' => $this->getId() ),
4723 __METHOD__
4726 $this->mOptionOverrides = array();
4727 $data = array();
4728 foreach ( $res as $row ) {
4729 $data[$row->up_property] = $row->up_value;
4732 foreach ( $data as $property => $value ) {
4733 $this->mOptionOverrides[$property] = $value;
4734 $this->mOptions[$property] = $value;
4738 $this->mOptionsLoaded = true;
4740 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
4744 * @todo document
4746 protected function saveOptions() {
4747 $this->loadOptions();
4749 // Not using getOptions(), to keep hidden preferences in database
4750 $saveOptions = $this->mOptions;
4752 // Allow hooks to abort, for instance to save to a global profile.
4753 // Reset options to default state before saving.
4754 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4755 return;
4758 $userId = $this->getId();
4759 $insert_rows = array();
4760 foreach ( $saveOptions as $key => $value ) {
4761 // Don't bother storing default values
4762 $defaultOption = self::getDefaultOption( $key );
4763 if ( ( is_null( $defaultOption ) &&
4764 !( $value === false || is_null( $value ) ) ) ||
4765 $value != $defaultOption
4767 $insert_rows[] = array(
4768 'up_user' => $userId,
4769 'up_property' => $key,
4770 'up_value' => $value,
4775 $dbw = wfGetDB( DB_MASTER );
4776 // Find and delete any prior preference rows...
4777 $res = $dbw->select( 'user_properties',
4778 array( 'up_property' ), array( 'up_user' => $userId ), __METHOD__ );
4779 $priorKeys = array();
4780 foreach ( $res as $row ) {
4781 $priorKeys[] = $row->up_property;
4783 if ( count( $priorKeys ) ) {
4784 // Do the DELETE by PRIMARY KEY for prior rows.
4785 // In the past a very large portion of calls to this function are for setting
4786 // 'rememberpassword' for new accounts (a preference that has since been removed).
4787 // Doing a blanket per-user DELETE for new accounts with no rows in the table
4788 // caused gap locks on [max user ID,+infinity) which caused high contention since
4789 // updates would pile up on each other as they are for higher (newer) user IDs.
4790 // It might not be necessary these days, but it shouldn't hurt either.
4791 $dbw->delete( 'user_properties',
4792 array( 'up_user' => $userId, 'up_property' => $priorKeys ), __METHOD__ );
4794 // Insert the new preference rows
4795 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, array( 'IGNORE' ) );
4799 * Provide an array of HTML5 attributes to put on an input element
4800 * intended for the user to enter a new password. This may include
4801 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4803 * Do *not* use this when asking the user to enter his current password!
4804 * Regardless of configuration, users may have invalid passwords for whatever
4805 * reason (e.g., they were set before requirements were tightened up).
4806 * Only use it when asking for a new password, like on account creation or
4807 * ResetPass.
4809 * Obviously, you still need to do server-side checking.
4811 * NOTE: A combination of bugs in various browsers means that this function
4812 * actually just returns array() unconditionally at the moment. May as
4813 * well keep it around for when the browser bugs get fixed, though.
4815 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4817 * @return array Array of HTML attributes suitable for feeding to
4818 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4819 * That will get confused by the boolean attribute syntax used.)
4821 public static function passwordChangeInputAttribs() {
4822 global $wgMinimalPasswordLength;
4824 if ( $wgMinimalPasswordLength == 0 ) {
4825 return array();
4828 # Note that the pattern requirement will always be satisfied if the
4829 # input is empty, so we need required in all cases.
4831 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4832 # if e-mail confirmation is being used. Since HTML5 input validation
4833 # is b0rked anyway in some browsers, just return nothing. When it's
4834 # re-enabled, fix this code to not output required for e-mail
4835 # registration.
4836 #$ret = array( 'required' );
4837 $ret = array();
4839 # We can't actually do this right now, because Opera 9.6 will print out
4840 # the entered password visibly in its error message! When other
4841 # browsers add support for this attribute, or Opera fixes its support,
4842 # we can add support with a version check to avoid doing this on Opera
4843 # versions where it will be a problem. Reported to Opera as
4844 # DSK-262266, but they don't have a public bug tracker for us to follow.
4846 if ( $wgMinimalPasswordLength > 1 ) {
4847 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4848 $ret['title'] = wfMessage( 'passwordtooshort' )
4849 ->numParams( $wgMinimalPasswordLength )->text();
4853 return $ret;
4857 * Return the list of user fields that should be selected to create
4858 * a new user object.
4859 * @return array
4861 public static function selectFields() {
4862 return array(
4863 'user_id',
4864 'user_name',
4865 'user_real_name',
4866 'user_password',
4867 'user_newpassword',
4868 'user_newpass_time',
4869 'user_email',
4870 'user_touched',
4871 'user_token',
4872 'user_email_authenticated',
4873 'user_email_token',
4874 'user_email_token_expires',
4875 'user_password_expires',
4876 'user_registration',
4877 'user_editcount',
4882 * Factory function for fatal permission-denied errors
4884 * @since 1.22
4885 * @param string $permission User right required
4886 * @return Status
4888 static function newFatalPermissionDeniedStatus( $permission ) {
4889 global $wgLang;
4891 $groups = array_map(
4892 array( 'User', 'makeGroupLinkWiki' ),
4893 User::getGroupsWithPermission( $permission )
4896 if ( $groups ) {
4897 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
4898 } else {
4899 return Status::newFatal( 'badaccess-group0' );