Merge "Add deprecation notices to recent s/var/public/ property changes."
[mediawiki.git] / includes / User.php
blob8228f1c207f41d088fc25bb4b0530503095b348f
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-categorypages',
147 'move-rootuserpages',
148 'move-subpages',
149 'nominornewtalk',
150 'noratelimit',
151 'override-export-depth',
152 'passwordreset',
153 'patrol',
154 'patrolmarks',
155 'protect',
156 'proxyunbannable',
157 'purge',
158 'read',
159 'reupload',
160 'reupload-own',
161 'reupload-shared',
162 'rollback',
163 'sendemail',
164 'siteadmin',
165 'suppressionlog',
166 'suppressredirect',
167 'suppressrevision',
168 'unblockself',
169 'undelete',
170 'unwatchedpages',
171 'upload',
172 'upload_by_url',
173 'userrights',
174 'userrights-interwiki',
175 'viewmyprivateinfo',
176 'viewmywatchlist',
177 'writeapi',
180 * String Cached results of getAllRights()
182 static $mAllRights = false;
184 /** @name Cache variables */
185 //@{
186 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
187 $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
188 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mEditCount,
189 $mGroups, $mOptionOverrides;
191 protected $mPasswordExpires;
192 //@}
195 * Bool Whether the cache variables have been loaded.
197 //@{
198 var $mOptionsLoaded;
201 * Array with already loaded items or true if all items have been loaded.
203 private $mLoadedItems = array();
204 //@}
207 * String Initialization data source if mLoadedItems!==true. May be one of:
208 * - 'defaults' anonymous user initialised from class defaults
209 * - 'name' initialise from mName
210 * - 'id' initialise from mId
211 * - 'session' log in from cookies or session if possible
213 * Use the User::newFrom*() family of functions to set this.
215 var $mFrom;
218 * Lazy-initialized variables, invalidated with clearInstanceCache
220 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mRights,
221 $mBlockreason, $mEffectiveGroups, $mImplicitGroups, $mFormerGroups, $mBlockedGlobally,
222 $mLocked, $mHideName, $mOptions;
225 * @var WebRequest
227 private $mRequest;
230 * @var Block
232 var $mBlock;
235 * @var bool
237 var $mAllowUsertalk;
240 * @var Block
242 private $mBlockedFromCreateAccount = false;
245 * @var array
247 private $mWatchedItems = array();
249 static $idCacheByName = array();
252 * Lightweight constructor for an anonymous user.
253 * Use the User::newFrom* factory functions for other kinds of users.
255 * @see newFromName()
256 * @see newFromId()
257 * @see newFromConfirmationCode()
258 * @see newFromSession()
259 * @see newFromRow()
261 public function __construct() {
262 $this->clearInstanceCache( 'defaults' );
266 * @return string
268 public function __toString() {
269 return $this->getName();
273 * Load the user table data for this object from the source given by mFrom.
275 public function load() {
276 if ( $this->mLoadedItems === true ) {
277 return;
279 wfProfileIn( __METHOD__ );
281 // Set it now to avoid infinite recursion in accessors
282 $this->mLoadedItems = true;
284 switch ( $this->mFrom ) {
285 case 'defaults':
286 $this->loadDefaults();
287 break;
288 case 'name':
289 $this->mId = self::idFromName( $this->mName );
290 if ( !$this->mId ) {
291 // Nonexistent user placeholder object
292 $this->loadDefaults( $this->mName );
293 } else {
294 $this->loadFromId();
296 break;
297 case 'id':
298 $this->loadFromId();
299 break;
300 case 'session':
301 if ( !$this->loadFromSession() ) {
302 // Loading from session failed. Load defaults.
303 $this->loadDefaults();
305 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
306 break;
307 default:
308 wfProfileOut( __METHOD__ );
309 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
311 wfProfileOut( __METHOD__ );
315 * Load user table data, given mId has already been set.
316 * @return bool false if the ID does not exist, true otherwise
318 public function loadFromId() {
319 global $wgMemc;
320 if ( $this->mId == 0 ) {
321 $this->loadDefaults();
322 return false;
325 // Try cache
326 $key = wfMemcKey( 'user', 'id', $this->mId );
327 $data = $wgMemc->get( $key );
328 if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
329 // Object is expired, load from DB
330 $data = false;
333 if ( !$data ) {
334 wfDebug( "User: cache miss for user {$this->mId}\n" );
335 // Load from DB
336 if ( !$this->loadFromDatabase() ) {
337 // Can't load from ID, user is anonymous
338 return false;
340 $this->saveToCache();
341 } else {
342 wfDebug( "User: got user {$this->mId} from cache\n" );
343 // Restore from cache
344 foreach ( self::$mCacheVars as $name ) {
345 $this->$name = $data[$name];
349 $this->mLoadedItems = true;
351 return true;
355 * Save user data to the shared cache
357 public function saveToCache() {
358 $this->load();
359 $this->loadGroups();
360 $this->loadOptions();
361 if ( $this->isAnon() ) {
362 // Anonymous users are uncached
363 return;
365 $data = array();
366 foreach ( self::$mCacheVars as $name ) {
367 $data[$name] = $this->$name;
369 $data['mVersion'] = MW_USER_VERSION;
370 $key = wfMemcKey( 'user', 'id', $this->mId );
371 global $wgMemc;
372 $wgMemc->set( $key, $data );
375 /** @name newFrom*() static factory methods */
376 //@{
379 * Static factory method for creation from username.
381 * This is slightly less efficient than newFromId(), so use newFromId() if
382 * you have both an ID and a name handy.
384 * @param string $name Username, validated by Title::newFromText()
385 * @param string|bool $validate Validate username. Takes the same parameters as
386 * User::getCanonicalName(), except that true is accepted as an alias
387 * for 'valid', for BC.
389 * @return User|bool User object, or false if the username is invalid
390 * (e.g. if it contains illegal characters or is an IP address). If the
391 * username is not present in the database, the result will be a user object
392 * with a name, zero user ID and default settings.
394 public static function newFromName( $name, $validate = 'valid' ) {
395 if ( $validate === true ) {
396 $validate = 'valid';
398 $name = self::getCanonicalName( $name, $validate );
399 if ( $name === false ) {
400 return false;
401 } else {
402 // Create unloaded user object
403 $u = new User;
404 $u->mName = $name;
405 $u->mFrom = 'name';
406 $u->setItemLoaded( 'name' );
407 return $u;
412 * Static factory method for creation from a given user ID.
414 * @param int $id Valid user ID
415 * @return User The corresponding User object
417 public static function newFromId( $id ) {
418 $u = new User;
419 $u->mId = $id;
420 $u->mFrom = 'id';
421 $u->setItemLoaded( 'id' );
422 return $u;
426 * Factory method to fetch whichever user has a given email confirmation code.
427 * This code is generated when an account is created or its e-mail address
428 * has changed.
430 * If the code is invalid or has expired, returns NULL.
432 * @param string $code Confirmation code
433 * @return User|null
435 public static function newFromConfirmationCode( $code ) {
436 $dbr = wfGetDB( DB_SLAVE );
437 $id = $dbr->selectField( 'user', 'user_id', array(
438 'user_email_token' => md5( $code ),
439 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
440 ) );
441 if ( $id !== false ) {
442 return User::newFromId( $id );
443 } else {
444 return null;
449 * Create a new user object using data from session or cookies. If the
450 * login credentials are invalid, the result is an anonymous user.
452 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
453 * @return User
455 public static function newFromSession( WebRequest $request = null ) {
456 $user = new User;
457 $user->mFrom = 'session';
458 $user->mRequest = $request;
459 return $user;
463 * Create a new user object from a user row.
464 * The row should have the following fields from the user table in it:
465 * - either user_name or user_id to load further data if needed (or both)
466 * - user_real_name
467 * - all other fields (email, password, etc.)
468 * It is useless to provide the remaining fields if either user_id,
469 * user_name and user_real_name are not provided because the whole row
470 * will be loaded once more from the database when accessing them.
472 * @param stdClass $row A row from the user table
473 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
474 * @return User
476 public static function newFromRow( $row, $data = null ) {
477 $user = new User;
478 $user->loadFromRow( $row, $data );
479 return $user;
482 //@}
485 * Get the username corresponding to a given user ID
486 * @param int $id User ID
487 * @return string|bool The corresponding username
489 public static function whoIs( $id ) {
490 return UserCache::singleton()->getProp( $id, 'name' );
494 * Get the real name of a user given their user ID
496 * @param int $id User ID
497 * @return string|bool The corresponding user's real name
499 public static function whoIsReal( $id ) {
500 return UserCache::singleton()->getProp( $id, 'real_name' );
504 * Get database id given a user name
505 * @param string $name Username
506 * @return int|null The corresponding user's ID, or null if user is nonexistent
508 public static function idFromName( $name ) {
509 $nt = Title::makeTitleSafe( NS_USER, $name );
510 if ( is_null( $nt ) ) {
511 // Illegal name
512 return null;
515 if ( isset( self::$idCacheByName[$name] ) ) {
516 return self::$idCacheByName[$name];
519 $dbr = wfGetDB( DB_SLAVE );
520 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
522 if ( $s === false ) {
523 $result = null;
524 } else {
525 $result = $s->user_id;
528 self::$idCacheByName[$name] = $result;
530 if ( count( self::$idCacheByName ) > 1000 ) {
531 self::$idCacheByName = array();
534 return $result;
538 * Reset the cache used in idFromName(). For use in tests.
540 public static function resetIdByNameCache() {
541 self::$idCacheByName = array();
545 * Does the string match an anonymous IPv4 address?
547 * This function exists for username validation, in order to reject
548 * usernames which are similar in form to IP addresses. Strings such
549 * as 300.300.300.300 will return true because it looks like an IP
550 * address, despite not being strictly valid.
552 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
553 * address because the usemod software would "cloak" anonymous IP
554 * addresses like this, if we allowed accounts like this to be created
555 * new users could get the old edits of these anonymous users.
557 * @param string $name Name to match
558 * @return bool
560 public static function isIP( $name ) {
561 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name ) || IP::isIPv6( $name );
565 * Is the input a valid username?
567 * Checks if the input is a valid username, we don't want an empty string,
568 * an IP address, anything that contains slashes (would mess up subpages),
569 * is longer than the maximum allowed username size or doesn't begin with
570 * a capital letter.
572 * @param string $name Name to match
573 * @return bool
575 public static function isValidUserName( $name ) {
576 global $wgContLang, $wgMaxNameChars;
578 if ( $name == ''
579 || User::isIP( $name )
580 || strpos( $name, '/' ) !== false
581 || strlen( $name ) > $wgMaxNameChars
582 || $name != $wgContLang->ucfirst( $name ) ) {
583 wfDebugLog( 'username', __METHOD__ .
584 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
585 return false;
588 // Ensure that the name can't be misresolved as a different title,
589 // such as with extra namespace keys at the start.
590 $parsed = Title::newFromText( $name );
591 if ( is_null( $parsed )
592 || $parsed->getNamespace()
593 || strcmp( $name, $parsed->getPrefixedText() ) ) {
594 wfDebugLog( 'username', __METHOD__ .
595 ": '$name' invalid due to ambiguous prefixes" );
596 return false;
599 // Check an additional blacklist of troublemaker characters.
600 // Should these be merged into the title char list?
601 $unicodeBlacklist = '/[' .
602 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
603 '\x{00a0}' . # non-breaking space
604 '\x{2000}-\x{200f}' . # various whitespace
605 '\x{2028}-\x{202f}' . # breaks and control chars
606 '\x{3000}' . # ideographic space
607 '\x{e000}-\x{f8ff}' . # private use
608 ']/u';
609 if ( preg_match( $unicodeBlacklist, $name ) ) {
610 wfDebugLog( 'username', __METHOD__ .
611 ": '$name' invalid due to blacklisted characters" );
612 return false;
615 return true;
619 * Usernames which fail to pass this function will be blocked
620 * from user login and new account registrations, but may be used
621 * internally by batch processes.
623 * If an account already exists in this form, login will be blocked
624 * by a failure to pass this function.
626 * @param string $name Name to match
627 * @return bool
629 public static function isUsableName( $name ) {
630 global $wgReservedUsernames;
631 // Must be a valid username, obviously ;)
632 if ( !self::isValidUserName( $name ) ) {
633 return false;
636 static $reservedUsernames = false;
637 if ( !$reservedUsernames ) {
638 $reservedUsernames = $wgReservedUsernames;
639 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
642 // Certain names may be reserved for batch processes.
643 foreach ( $reservedUsernames as $reserved ) {
644 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
645 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
647 if ( $reserved == $name ) {
648 return false;
651 return true;
655 * Usernames which fail to pass this function will be blocked
656 * from new account registrations, but may be used internally
657 * either by batch processes or by user accounts which have
658 * already been created.
660 * Additional blacklisting may be added here rather than in
661 * isValidUserName() to avoid disrupting existing accounts.
663 * @param string $name String to match
664 * @return bool
666 public static function isCreatableName( $name ) {
667 global $wgInvalidUsernameCharacters;
669 // Ensure that the username isn't longer than 235 bytes, so that
670 // (at least for the builtin skins) user javascript and css files
671 // will work. (bug 23080)
672 if ( strlen( $name ) > 235 ) {
673 wfDebugLog( 'username', __METHOD__ .
674 ": '$name' invalid due to length" );
675 return false;
678 // Preg yells if you try to give it an empty string
679 if ( $wgInvalidUsernameCharacters !== '' ) {
680 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
681 wfDebugLog( 'username', __METHOD__ .
682 ": '$name' invalid due to wgInvalidUsernameCharacters" );
683 return false;
687 return self::isUsableName( $name );
691 * Is the input a valid password for this user?
693 * @param string $password Desired password
694 * @return bool
696 public function isValidPassword( $password ) {
697 //simple boolean wrapper for getPasswordValidity
698 return $this->getPasswordValidity( $password ) === true;
703 * Given unvalidated password input, return error message on failure.
705 * @param string $password Desired password
706 * @return bool|string|array true on success, string or array of error message on failure
708 public function getPasswordValidity( $password ) {
709 $result = $this->checkPasswordValidity( $password );
710 if ( $result->isGood() ) {
711 return true;
712 } else {
713 $messages = array();
714 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
715 $messages[] = $error['message'];
717 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
718 $messages[] = $warning['message'];
720 if ( count( $messages ) === 1 ) {
721 return $messages[0];
723 return $messages;
728 * Check if this is a valid password for this user. Status will be good if
729 * the password is valid, or have an array of error messages if not.
731 * @param string $password Desired password
732 * @return Status
733 * @since 1.23
735 public function checkPasswordValidity( $password ) {
736 global $wgMinimalPasswordLength, $wgContLang;
738 static $blockedLogins = array(
739 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
740 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
743 $status = Status::newGood();
745 $result = false; //init $result to false for the internal checks
747 if ( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) ) {
748 $status->error( $result );
749 return $status;
752 if ( $result === false ) {
753 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
754 $status->error( 'passwordtooshort', $wgMinimalPasswordLength );
755 return $status;
756 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName ) ) {
757 $status->error( 'password-name-match' );
758 return $status;
759 } elseif ( isset( $blockedLogins[$this->getName()] ) && $password == $blockedLogins[$this->getName()] ) {
760 $status->error( 'password-login-forbidden' );
761 return $status;
762 } else {
763 //it seems weird returning a Good status here, but this is because of the
764 //initialization of $result to false above. If the hook is never run or it
765 //doesn't modify $result, then we will likely get down into this if with
766 //a valid password.
767 return $status;
769 } elseif ( $result === true ) {
770 return $status;
771 } else {
772 $status->error( $result );
773 return $status; //the isValidPassword hook set a string $result and returned true
778 * Expire a user's password
779 * @since 1.23
780 * @param int $ts Optional timestamp to convert, default 0 for the current time
782 public function expirePassword( $ts = 0 ) {
783 $this->load();
784 $timestamp = wfTimestamp( TS_MW, $ts );
785 $this->mPasswordExpires = $timestamp;
786 $this->saveSettings();
790 * Clear the password expiration for a user
791 * @since 1.23
792 * @param bool $load Ensure user object is loaded first
794 public function resetPasswordExpiration( $load = true ) {
795 global $wgPasswordExpirationDays;
796 if ( $load ) {
797 $this->load();
799 $newExpire = null;
800 if ( $wgPasswordExpirationDays ) {
801 $newExpire = wfTimestamp(
802 TS_MW,
803 time() + ( $wgPasswordExpirationDays * 24 * 3600 )
806 // Give extensions a chance to force an expiration
807 wfRunHooks( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
808 $this->mPasswordExpires = $newExpire;
812 * Check if the user's password is expired.
813 * TODO: Put this and password length into a PasswordPolicy object
814 * @since 1.23
815 * @return string|bool The expiration type, or false if not expired
816 * hard: A password change is required to login
817 * soft: Allow login, but encourage password change
818 * false: Password is not expired
820 public function getPasswordExpired() {
821 global $wgPasswordExpireGrace;
822 $expired = false;
823 $now = wfTimestamp();
824 $expiration = $this->getPasswordExpireDate();
825 $expUnix = wfTimestamp( TS_UNIX, $expiration );
826 if ( $expiration !== null && $expUnix < $now ) {
827 $expired = ( $expUnix + $wgPasswordExpireGrace < $now ) ? 'hard' : 'soft';
829 return $expired;
833 * Get this user's password expiration date. Since this may be using
834 * the cached User object, we assume that whatever mechanism is setting
835 * the expiration date is also expiring the User cache.
836 * @since 1.23
837 * @return string|bool The datestamp of the expiration, or null if not set
839 public function getPasswordExpireDate() {
840 $this->load();
841 return $this->mPasswordExpires;
845 * Does a string look like an e-mail address?
847 * This validates an email address using an HTML5 specification found at:
848 * http://www.whatwg.org/html/states-of-the-type-attribute.html#valid-e-mail-address
849 * Which as of 2011-01-24 says:
851 * A valid e-mail address is a string that matches the ABNF production
852 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
853 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
854 * 3.5.
856 * This function is an implementation of the specification as requested in
857 * bug 22449.
859 * Client-side forms will use the same standard validation rules via JS or
860 * HTML 5 validation; additional restrictions can be enforced server-side
861 * by extensions via the 'isValidEmailAddr' hook.
863 * Note that this validation doesn't 100% match RFC 2822, but is believed
864 * to be liberal enough for wide use. Some invalid addresses will still
865 * pass validation here.
867 * @param string $addr E-mail address
868 * @return bool
869 * @deprecated since 1.18 call Sanitizer::isValidEmail() directly
871 public static function isValidEmailAddr( $addr ) {
872 wfDeprecated( __METHOD__, '1.18' );
873 return Sanitizer::validateEmail( $addr );
877 * Given unvalidated user input, return a canonical username, or false if
878 * the username is invalid.
879 * @param string $name User input
880 * @param string|bool $validate Type of validation to use:
881 * - false No validation
882 * - 'valid' Valid for batch processes
883 * - 'usable' Valid for batch processes and login
884 * - 'creatable' Valid for batch processes, login and account creation
886 * @throws MWException
887 * @return bool|string
889 public static function getCanonicalName( $name, $validate = 'valid' ) {
890 // Force usernames to capital
891 global $wgContLang;
892 $name = $wgContLang->ucfirst( $name );
894 # Reject names containing '#'; these will be cleaned up
895 # with title normalisation, but then it's too late to
896 # check elsewhere
897 if ( strpos( $name, '#' ) !== false ) {
898 return false;
901 // Clean up name according to title rules
902 $t = ( $validate === 'valid' ) ?
903 Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
904 // Check for invalid titles
905 if ( is_null( $t ) ) {
906 return false;
909 // Reject various classes of invalid names
910 global $wgAuth;
911 $name = $wgAuth->getCanonicalName( $t->getText() );
913 switch ( $validate ) {
914 case false:
915 break;
916 case 'valid':
917 if ( !User::isValidUserName( $name ) ) {
918 $name = false;
920 break;
921 case 'usable':
922 if ( !User::isUsableName( $name ) ) {
923 $name = false;
925 break;
926 case 'creatable':
927 if ( !User::isCreatableName( $name ) ) {
928 $name = false;
930 break;
931 default:
932 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__ );
934 return $name;
938 * Count the number of edits of a user
940 * @param int $uid User ID to check
941 * @return int The user's edit count
943 * @deprecated since 1.21 in favour of User::getEditCount
945 public static function edits( $uid ) {
946 wfDeprecated( __METHOD__, '1.21' );
947 $user = self::newFromId( $uid );
948 return $user->getEditCount();
952 * Return a random password.
954 * @return string New random password
956 public static function randomPassword() {
957 global $wgMinimalPasswordLength;
958 // Decide the final password length based on our min password length, stopping at a minimum of 10 chars
959 $length = max( 10, $wgMinimalPasswordLength );
960 // Multiply by 1.25 to get the number of hex characters we need
961 $length = $length * 1.25;
962 // Generate random hex chars
963 $hex = MWCryptRand::generateHex( $length );
964 // Convert from base 16 to base 32 to get a proper password like string
965 return wfBaseConvert( $hex, 16, 32 );
969 * Set cached properties to default.
971 * @note This no longer clears uncached lazy-initialised properties;
972 * the constructor does that instead.
974 * @param string|bool $name
976 public function loadDefaults( $name = false ) {
977 wfProfileIn( __METHOD__ );
979 $this->mId = 0;
980 $this->mName = $name;
981 $this->mRealName = '';
982 $this->mPassword = $this->mNewpassword = '';
983 $this->mNewpassTime = null;
984 $this->mEmail = '';
985 $this->mOptionOverrides = null;
986 $this->mOptionsLoaded = false;
988 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
989 if ( $loggedOut !== null ) {
990 $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
991 } else {
992 $this->mTouched = '1'; # Allow any pages to be cached
995 $this->mToken = null; // Don't run cryptographic functions till we need a token
996 $this->mEmailAuthenticated = null;
997 $this->mEmailToken = '';
998 $this->mEmailTokenExpires = null;
999 $this->mPasswordExpires = null;
1000 $this->resetPasswordExpiration( false );
1001 $this->mRegistration = wfTimestamp( TS_MW );
1002 $this->mGroups = array();
1004 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
1006 wfProfileOut( __METHOD__ );
1010 * Return whether an item has been loaded.
1012 * @param string $item Item to check. Current possibilities:
1013 * - id
1014 * - name
1015 * - realname
1016 * @param string $all 'all' to check if the whole object has been loaded
1017 * or any other string to check if only the item is available (e.g.
1018 * for optimisation)
1019 * @return bool
1021 public function isItemLoaded( $item, $all = 'all' ) {
1022 return ( $this->mLoadedItems === true && $all === 'all' ) ||
1023 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
1027 * Set that an item has been loaded
1029 * @param string $item
1031 protected function setItemLoaded( $item ) {
1032 if ( is_array( $this->mLoadedItems ) ) {
1033 $this->mLoadedItems[$item] = true;
1038 * Load user data from the session or login cookie.
1039 * @return bool True if the user is logged in, false otherwise.
1041 private function loadFromSession() {
1042 $result = null;
1043 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
1044 if ( $result !== null ) {
1045 return $result;
1048 $request = $this->getRequest();
1050 $cookieId = $request->getCookie( 'UserID' );
1051 $sessId = $request->getSessionData( 'wsUserID' );
1053 if ( $cookieId !== null ) {
1054 $sId = intval( $cookieId );
1055 if ( $sessId !== null && $cookieId != $sessId ) {
1056 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1057 cookie user ID ($sId) don't match!" );
1058 return false;
1060 $request->setSessionData( 'wsUserID', $sId );
1061 } elseif ( $sessId !== null && $sessId != 0 ) {
1062 $sId = $sessId;
1063 } else {
1064 return false;
1067 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1068 $sName = $request->getSessionData( 'wsUserName' );
1069 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1070 $sName = $request->getCookie( 'UserName' );
1071 $request->setSessionData( 'wsUserName', $sName );
1072 } else {
1073 return false;
1076 $proposedUser = User::newFromId( $sId );
1077 if ( !$proposedUser->isLoggedIn() ) {
1078 // Not a valid ID
1079 return false;
1082 global $wgBlockDisablesLogin;
1083 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1084 // User blocked and we've disabled blocked user logins
1085 return false;
1088 if ( $request->getSessionData( 'wsToken' ) ) {
1089 $passwordCorrect = ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1090 $from = 'session';
1091 } elseif ( $request->getCookie( 'Token' ) ) {
1092 # Get the token from DB/cache and clean it up to remove garbage padding.
1093 # This deals with historical problems with bugs and the default column value.
1094 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1095 // Make comparison in constant time (bug 61346)
1096 $passwordCorrect = strlen( $token ) && $this->compareSecrets( $token, $request->getCookie( 'Token' ) );
1097 $from = 'cookie';
1098 } else {
1099 // No session or persistent login cookie
1100 return false;
1103 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1104 $this->loadFromUserObject( $proposedUser );
1105 $request->setSessionData( 'wsToken', $this->mToken );
1106 wfDebug( "User: logged in from $from\n" );
1107 return true;
1108 } else {
1109 // Invalid credentials
1110 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1111 return false;
1116 * A comparison of two strings, not vulnerable to timing attacks
1117 * @param string $answer The secret string that you are comparing against.
1118 * @param string $test Compare this string to the $answer.
1119 * @return bool True if the strings are the same, false otherwise
1121 protected function compareSecrets( $answer, $test ) {
1122 if ( strlen( $answer ) !== strlen( $test ) ) {
1123 $passwordCorrect = false;
1124 } else {
1125 $result = 0;
1126 for ( $i = 0; $i < strlen( $answer ); $i++ ) {
1127 $result |= ord( $answer[$i] ) ^ ord( $test[$i] );
1129 $passwordCorrect = ( $result == 0 );
1131 return $passwordCorrect;
1135 * Load user and user_group data from the database.
1136 * $this->mId must be set, this is how the user is identified.
1138 * @return bool True if the user exists, false if the user is anonymous
1140 public function loadFromDatabase() {
1141 // Paranoia
1142 $this->mId = intval( $this->mId );
1144 // Anonymous user
1145 if ( !$this->mId ) {
1146 $this->loadDefaults();
1147 return false;
1150 $dbr = wfGetDB( DB_MASTER );
1151 $s = $dbr->selectRow( 'user', self::selectFields(), array( 'user_id' => $this->mId ), __METHOD__ );
1153 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1155 if ( $s !== false ) {
1156 // Initialise user table data
1157 $this->loadFromRow( $s );
1158 $this->mGroups = null; // deferred
1159 $this->getEditCount(); // revalidation for nulls
1160 return true;
1161 } else {
1162 // Invalid user_id
1163 $this->mId = 0;
1164 $this->loadDefaults();
1165 return false;
1170 * Initialize this object from a row from the user table.
1172 * @param stdClass $row Row from the user table to load.
1173 * @param array $data Further user data to load into the object
1175 * user_groups Array with groups out of the user_groups table
1176 * user_properties Array with properties out of the user_properties table
1178 public function loadFromRow( $row, $data = null ) {
1179 $all = true;
1181 $this->mGroups = null; // deferred
1183 if ( isset( $row->user_name ) ) {
1184 $this->mName = $row->user_name;
1185 $this->mFrom = 'name';
1186 $this->setItemLoaded( 'name' );
1187 } else {
1188 $all = false;
1191 if ( isset( $row->user_real_name ) ) {
1192 $this->mRealName = $row->user_real_name;
1193 $this->setItemLoaded( 'realname' );
1194 } else {
1195 $all = false;
1198 if ( isset( $row->user_id ) ) {
1199 $this->mId = intval( $row->user_id );
1200 $this->mFrom = 'id';
1201 $this->setItemLoaded( 'id' );
1202 } else {
1203 $all = false;
1206 if ( isset( $row->user_editcount ) ) {
1207 $this->mEditCount = $row->user_editcount;
1208 } else {
1209 $all = false;
1212 if ( isset( $row->user_password ) ) {
1213 $this->mPassword = $row->user_password;
1214 $this->mNewpassword = $row->user_newpassword;
1215 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
1216 $this->mEmail = $row->user_email;
1217 if ( isset( $row->user_options ) ) {
1218 $this->decodeOptions( $row->user_options );
1220 $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1221 $this->mToken = $row->user_token;
1222 if ( $this->mToken == '' ) {
1223 $this->mToken = null;
1225 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1226 $this->mEmailToken = $row->user_email_token;
1227 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1228 $this->mPasswordExpires = wfTimestampOrNull( TS_MW, $row->user_password_expires );
1229 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1230 } else {
1231 $all = false;
1234 if ( $all ) {
1235 $this->mLoadedItems = true;
1238 if ( is_array( $data ) ) {
1239 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1240 $this->mGroups = $data['user_groups'];
1242 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1243 $this->loadOptions( $data['user_properties'] );
1249 * Load the data for this user object from another user object.
1251 * @param User $user
1253 protected function loadFromUserObject( $user ) {
1254 $user->load();
1255 $user->loadGroups();
1256 $user->loadOptions();
1257 foreach ( self::$mCacheVars as $var ) {
1258 $this->$var = $user->$var;
1263 * Load the groups from the database if they aren't already loaded.
1265 private function loadGroups() {
1266 if ( is_null( $this->mGroups ) ) {
1267 $dbr = wfGetDB( DB_MASTER );
1268 $res = $dbr->select( 'user_groups',
1269 array( 'ug_group' ),
1270 array( 'ug_user' => $this->mId ),
1271 __METHOD__ );
1272 $this->mGroups = array();
1273 foreach ( $res as $row ) {
1274 $this->mGroups[] = $row->ug_group;
1280 * Add the user to the group if he/she meets given criteria.
1282 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1283 * possible to remove manually via Special:UserRights. In such case it
1284 * will not be re-added automatically. The user will also not lose the
1285 * group if they no longer meet the criteria.
1287 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1289 * @return array Array of groups the user has been promoted to.
1291 * @see $wgAutopromoteOnce
1293 public function addAutopromoteOnceGroups( $event ) {
1294 global $wgAutopromoteOnceLogInRC, $wgAuth;
1296 $toPromote = array();
1297 if ( $this->getId() ) {
1298 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1299 if ( count( $toPromote ) ) {
1300 $oldGroups = $this->getGroups(); // previous groups
1302 foreach ( $toPromote as $group ) {
1303 $this->addGroup( $group );
1305 // update groups in external authentication database
1306 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1308 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1310 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1311 $logEntry->setPerformer( $this );
1312 $logEntry->setTarget( $this->getUserPage() );
1313 $logEntry->setParameters( array(
1314 '4::oldgroups' => $oldGroups,
1315 '5::newgroups' => $newGroups,
1316 ) );
1317 $logid = $logEntry->insert();
1318 if ( $wgAutopromoteOnceLogInRC ) {
1319 $logEntry->publish( $logid );
1323 return $toPromote;
1327 * Clear various cached data stored in this object. The cache of the user table
1328 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1330 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1331 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1333 public function clearInstanceCache( $reloadFrom = false ) {
1334 $this->mNewtalk = -1;
1335 $this->mDatePreference = null;
1336 $this->mBlockedby = -1; # Unset
1337 $this->mHash = false;
1338 $this->mRights = null;
1339 $this->mEffectiveGroups = null;
1340 $this->mImplicitGroups = null;
1341 $this->mGroups = null;
1342 $this->mOptions = null;
1343 $this->mOptionsLoaded = false;
1344 $this->mEditCount = null;
1346 if ( $reloadFrom ) {
1347 $this->mLoadedItems = array();
1348 $this->mFrom = $reloadFrom;
1353 * Combine the language default options with any site-specific options
1354 * and add the default language variants.
1356 * @return array Array of String options
1358 public static function getDefaultOptions() {
1359 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1361 static $defOpt = null;
1362 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1363 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1364 // mid-request and see that change reflected in the return value of this function.
1365 // Which is insane and would never happen during normal MW operation
1366 return $defOpt;
1369 $defOpt = $wgDefaultUserOptions;
1370 // Default language setting
1371 $defOpt['language'] = $wgContLang->getCode();
1372 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
1373 $defOpt[$langCode == $wgContLang->getCode() ? 'variant' : "variant-$langCode"] = $langCode;
1375 foreach ( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1376 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1378 $defOpt['skin'] = $wgDefaultSkin;
1380 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1382 return $defOpt;
1386 * Get a given default option value.
1388 * @param string $opt Name of option to retrieve
1389 * @return string Default option value
1391 public static function getDefaultOption( $opt ) {
1392 $defOpts = self::getDefaultOptions();
1393 if ( isset( $defOpts[$opt] ) ) {
1394 return $defOpts[$opt];
1395 } else {
1396 return null;
1401 * Get blocking information
1402 * @param bool $bFromSlave Whether to check the slave database first.
1403 * To improve performance, non-critical checks are done against slaves.
1404 * Check when actually saving should be done against master.
1406 private function getBlockedStatus( $bFromSlave = true ) {
1407 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1409 if ( -1 != $this->mBlockedby ) {
1410 return;
1413 wfProfileIn( __METHOD__ );
1414 wfDebug( __METHOD__ . ": checking...\n" );
1416 // Initialize data...
1417 // Otherwise something ends up stomping on $this->mBlockedby when
1418 // things get lazy-loaded later, causing false positive block hits
1419 // due to -1 !== 0. Probably session-related... Nothing should be
1420 // overwriting mBlockedby, surely?
1421 $this->load();
1423 # We only need to worry about passing the IP address to the Block generator if the
1424 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1425 # know which IP address they're actually coming from
1426 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1427 $ip = $this->getRequest()->getIP();
1428 } else {
1429 $ip = null;
1432 // User/IP blocking
1433 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1435 // Proxy blocking
1436 if ( !$block instanceof Block && $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1437 && !in_array( $ip, $wgProxyWhitelist )
1439 // Local list
1440 if ( self::isLocallyBlockedProxy( $ip ) ) {
1441 $block = new Block;
1442 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1443 $block->mReason = wfMessage( 'proxyblockreason' )->text();
1444 $block->setTarget( $ip );
1445 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1446 $block = new Block;
1447 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1448 $block->mReason = wfMessage( 'sorbsreason' )->text();
1449 $block->setTarget( $ip );
1453 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1454 if ( !$block instanceof Block
1455 && $wgApplyIpBlocksToXff
1456 && $ip !== null
1457 && !$this->isAllowed( 'proxyunbannable' )
1458 && !in_array( $ip, $wgProxyWhitelist )
1460 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1461 $xff = array_map( 'trim', explode( ',', $xff ) );
1462 $xff = array_diff( $xff, array( $ip ) );
1463 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1464 $block = Block::chooseBlock( $xffblocks, $xff );
1465 if ( $block instanceof Block ) {
1466 # Mangle the reason to alert the user that the block
1467 # originated from matching the X-Forwarded-For header.
1468 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->text();
1472 if ( $block instanceof Block ) {
1473 wfDebug( __METHOD__ . ": Found block.\n" );
1474 $this->mBlock = $block;
1475 $this->mBlockedby = $block->getByName();
1476 $this->mBlockreason = $block->mReason;
1477 $this->mHideName = $block->mHideName;
1478 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1479 } else {
1480 $this->mBlockedby = '';
1481 $this->mHideName = 0;
1482 $this->mAllowUsertalk = false;
1485 // Extensions
1486 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1488 wfProfileOut( __METHOD__ );
1492 * Whether the given IP is in a DNS blacklist.
1494 * @param string $ip IP to check
1495 * @param bool $checkWhitelist Whether to check the whitelist first
1496 * @return bool True if blacklisted.
1498 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1499 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1500 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1502 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs ) {
1503 return false;
1506 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1507 return false;
1510 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1511 return $this->inDnsBlacklist( $ip, $urls );
1515 * Whether the given IP is in a given DNS blacklist.
1517 * @param string $ip IP to check
1518 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1519 * @return bool True if blacklisted.
1521 public function inDnsBlacklist( $ip, $bases ) {
1522 wfProfileIn( __METHOD__ );
1524 $found = false;
1525 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1526 if ( IP::isIPv4( $ip ) ) {
1527 // Reverse IP, bug 21255
1528 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1530 foreach ( (array)$bases as $base ) {
1531 // Make hostname
1532 // If we have an access key, use that too (ProjectHoneypot, etc.)
1533 if ( is_array( $base ) ) {
1534 if ( count( $base ) >= 2 ) {
1535 // Access key is 1, base URL is 0
1536 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1537 } else {
1538 $host = "$ipReversed.{$base[0]}";
1540 } else {
1541 $host = "$ipReversed.$base";
1544 // Send query
1545 $ipList = gethostbynamel( $host );
1547 if ( $ipList ) {
1548 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1549 $found = true;
1550 break;
1551 } else {
1552 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1557 wfProfileOut( __METHOD__ );
1558 return $found;
1562 * Check if an IP address is in the local proxy list
1564 * @param string $ip
1566 * @return bool
1568 public static function isLocallyBlockedProxy( $ip ) {
1569 global $wgProxyList;
1571 if ( !$wgProxyList ) {
1572 return false;
1574 wfProfileIn( __METHOD__ );
1576 if ( !is_array( $wgProxyList ) ) {
1577 // Load from the specified file
1578 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1581 if ( !is_array( $wgProxyList ) ) {
1582 $ret = false;
1583 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1584 $ret = true;
1585 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1586 // Old-style flipped proxy list
1587 $ret = true;
1588 } else {
1589 $ret = false;
1591 wfProfileOut( __METHOD__ );
1592 return $ret;
1596 * Is this user subject to rate limiting?
1598 * @return bool True if rate limited
1600 public function isPingLimitable() {
1601 global $wgRateLimitsExcludedIPs;
1602 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1603 // No other good way currently to disable rate limits
1604 // for specific IPs. :P
1605 // But this is a crappy hack and should die.
1606 return false;
1608 return !$this->isAllowed( 'noratelimit' );
1612 * Primitive rate limits: enforce maximum actions per time period
1613 * to put a brake on flooding.
1615 * @note When using a shared cache like memcached, IP-address
1616 * last-hit counters will be shared across wikis.
1618 * @param string $action Action to enforce; 'edit' if unspecified
1619 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1620 * @return bool True if a rate limiter was tripped
1622 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1623 // Call the 'PingLimiter' hook
1624 $result = false;
1625 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1626 return $result;
1629 global $wgRateLimits;
1630 if ( !isset( $wgRateLimits[$action] ) ) {
1631 return false;
1634 // Some groups shouldn't trigger the ping limiter, ever
1635 if ( !$this->isPingLimitable() ) {
1636 return false;
1639 global $wgMemc;
1640 wfProfileIn( __METHOD__ );
1642 $limits = $wgRateLimits[$action];
1643 $keys = array();
1644 $id = $this->getId();
1645 $userLimit = false;
1647 if ( isset( $limits['anon'] ) && $id == 0 ) {
1648 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1651 if ( isset( $limits['user'] ) && $id != 0 ) {
1652 $userLimit = $limits['user'];
1654 if ( $this->isNewbie() ) {
1655 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1656 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1658 if ( isset( $limits['ip'] ) ) {
1659 $ip = $this->getRequest()->getIP();
1660 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1662 if ( isset( $limits['subnet'] ) ) {
1663 $ip = $this->getRequest()->getIP();
1664 $matches = array();
1665 $subnet = false;
1666 if ( IP::isIPv6( $ip ) ) {
1667 $parts = IP::parseRange( "$ip/64" );
1668 $subnet = $parts[0];
1669 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1670 // IPv4
1671 $subnet = $matches[1];
1673 if ( $subnet !== false ) {
1674 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1678 // Check for group-specific permissions
1679 // If more than one group applies, use the group with the highest limit
1680 foreach ( $this->getGroups() as $group ) {
1681 if ( isset( $limits[$group] ) ) {
1682 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1683 $userLimit = $limits[$group];
1687 // Set the user limit key
1688 if ( $userLimit !== false ) {
1689 list( $max, $period ) = $userLimit;
1690 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
1691 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1694 $triggered = false;
1695 foreach ( $keys as $key => $limit ) {
1696 list( $max, $period ) = $limit;
1697 $summary = "(limit $max in {$period}s)";
1698 $count = $wgMemc->get( $key );
1699 // Already pinged?
1700 if ( $count ) {
1701 if ( $count >= $max ) {
1702 wfDebugLog( 'ratelimit', $this->getName() . " tripped! $key at $count $summary" );
1703 $triggered = true;
1704 } else {
1705 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1707 } else {
1708 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1709 if ( $incrBy > 0 ) {
1710 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1713 if ( $incrBy > 0 ) {
1714 $wgMemc->incr( $key, $incrBy );
1718 wfProfileOut( __METHOD__ );
1719 return $triggered;
1723 * Check if user is blocked
1725 * @param bool $bFromSlave Whether to check the slave database instead of the master
1726 * @return bool True if blocked, false otherwise
1728 public function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1729 return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
1733 * Get the block affecting the user, or null if the user is not blocked
1735 * @param bool $bFromSlave Whether to check the slave database instead of the master
1736 * @return Block|null
1738 public function getBlock( $bFromSlave = true ) {
1739 $this->getBlockedStatus( $bFromSlave );
1740 return $this->mBlock instanceof Block ? $this->mBlock : null;
1744 * Check if user is blocked from editing a particular article
1746 * @param Title $title Title to check
1747 * @param bool $bFromSlave Whether to check the slave database instead of the master
1748 * @return bool
1750 public function isBlockedFrom( $title, $bFromSlave = false ) {
1751 global $wgBlockAllowsUTEdit;
1752 wfProfileIn( __METHOD__ );
1754 $blocked = $this->isBlocked( $bFromSlave );
1755 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1756 // If a user's name is suppressed, they cannot make edits anywhere
1757 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName()
1758 && $title->getNamespace() == NS_USER_TALK ) {
1759 $blocked = false;
1760 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1763 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1765 wfProfileOut( __METHOD__ );
1766 return $blocked;
1770 * If user is blocked, return the name of the user who placed the block
1771 * @return string Name of blocker
1773 public function blockedBy() {
1774 $this->getBlockedStatus();
1775 return $this->mBlockedby;
1779 * If user is blocked, return the specified reason for the block
1780 * @return string Blocking reason
1782 public function blockedFor() {
1783 $this->getBlockedStatus();
1784 return $this->mBlockreason;
1788 * If user is blocked, return the ID for the block
1789 * @return int Block ID
1791 public function getBlockId() {
1792 $this->getBlockedStatus();
1793 return ( $this->mBlock ? $this->mBlock->getId() : false );
1797 * Check if user is blocked on all wikis.
1798 * Do not use for actual edit permission checks!
1799 * This is intended for quick UI checks.
1801 * @param string $ip IP address, uses current client if none given
1802 * @return bool True if blocked, false otherwise
1804 public function isBlockedGlobally( $ip = '' ) {
1805 if ( $this->mBlockedGlobally !== null ) {
1806 return $this->mBlockedGlobally;
1808 // User is already an IP?
1809 if ( IP::isIPAddress( $this->getName() ) ) {
1810 $ip = $this->getName();
1811 } elseif ( !$ip ) {
1812 $ip = $this->getRequest()->getIP();
1814 $blocked = false;
1815 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1816 $this->mBlockedGlobally = (bool)$blocked;
1817 return $this->mBlockedGlobally;
1821 * Check if user account is locked
1823 * @return bool True if locked, false otherwise
1825 public function isLocked() {
1826 if ( $this->mLocked !== null ) {
1827 return $this->mLocked;
1829 global $wgAuth;
1830 StubObject::unstub( $wgAuth );
1831 $authUser = $wgAuth->getUserInstance( $this );
1832 $this->mLocked = (bool)$authUser->isLocked();
1833 return $this->mLocked;
1837 * Check if user account is hidden
1839 * @return bool True if hidden, false otherwise
1841 public function isHidden() {
1842 if ( $this->mHideName !== null ) {
1843 return $this->mHideName;
1845 $this->getBlockedStatus();
1846 if ( !$this->mHideName ) {
1847 global $wgAuth;
1848 StubObject::unstub( $wgAuth );
1849 $authUser = $wgAuth->getUserInstance( $this );
1850 $this->mHideName = (bool)$authUser->isHidden();
1852 return $this->mHideName;
1856 * Get the user's ID.
1857 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1859 public function getId() {
1860 if ( $this->mId === null && $this->mName !== null && User::isIP( $this->mName ) ) {
1861 // Special case, we know the user is anonymous
1862 return 0;
1863 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1864 // Don't load if this was initialized from an ID
1865 $this->load();
1867 return $this->mId;
1871 * Set the user and reload all fields according to a given ID
1872 * @param int $v User ID to reload
1874 public function setId( $v ) {
1875 $this->mId = $v;
1876 $this->clearInstanceCache( 'id' );
1880 * Get the user name, or the IP of an anonymous user
1881 * @return string User's name or IP address
1883 public function getName() {
1884 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1885 // Special case optimisation
1886 return $this->mName;
1887 } else {
1888 $this->load();
1889 if ( $this->mName === false ) {
1890 // Clean up IPs
1891 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
1893 return $this->mName;
1898 * Set the user name.
1900 * This does not reload fields from the database according to the given
1901 * name. Rather, it is used to create a temporary "nonexistent user" for
1902 * later addition to the database. It can also be used to set the IP
1903 * address for an anonymous user to something other than the current
1904 * remote IP.
1906 * @note User::newFromName() has roughly the same function, when the named user
1907 * does not exist.
1908 * @param string $str New user name to set
1910 public function setName( $str ) {
1911 $this->load();
1912 $this->mName = $str;
1916 * Get the user's name escaped by underscores.
1917 * @return string Username escaped by underscores.
1919 public function getTitleKey() {
1920 return str_replace( ' ', '_', $this->getName() );
1924 * Check if the user has new messages.
1925 * @return bool True if the user has new messages
1927 public function getNewtalk() {
1928 $this->load();
1930 // Load the newtalk status if it is unloaded (mNewtalk=-1)
1931 if ( $this->mNewtalk === -1 ) {
1932 $this->mNewtalk = false; # reset talk page status
1934 // Check memcached separately for anons, who have no
1935 // entire User object stored in there.
1936 if ( !$this->mId ) {
1937 global $wgDisableAnonTalk;
1938 if ( $wgDisableAnonTalk ) {
1939 // Anon newtalk disabled by configuration.
1940 $this->mNewtalk = false;
1941 } else {
1942 global $wgMemc;
1943 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1944 $newtalk = $wgMemc->get( $key );
1945 if ( strval( $newtalk ) !== '' ) {
1946 $this->mNewtalk = (bool)$newtalk;
1947 } else {
1948 // Since we are caching this, make sure it is up to date by getting it
1949 // from the master
1950 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1951 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1954 } else {
1955 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1959 return (bool)$this->mNewtalk;
1963 * Return the data needed to construct links for new talk page message
1964 * alerts. If there are new messages, this will return an associative array
1965 * with the following data:
1966 * wiki: The database name of the wiki
1967 * link: Root-relative link to the user's talk page
1968 * rev: The last talk page revision that the user has seen or null. This
1969 * is useful for building diff links.
1970 * If there are no new messages, it returns an empty array.
1971 * @note This function was designed to accomodate multiple talk pages, but
1972 * currently only returns a single link and revision.
1973 * @return array
1975 public function getNewMessageLinks() {
1976 $talks = array();
1977 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
1978 return $talks;
1979 } elseif ( !$this->getNewtalk() ) {
1980 return array();
1982 $utp = $this->getTalkPage();
1983 $dbr = wfGetDB( DB_SLAVE );
1984 // Get the "last viewed rev" timestamp from the oldest message notification
1985 $timestamp = $dbr->selectField( 'user_newtalk',
1986 'MIN(user_last_timestamp)',
1987 $this->isAnon() ? array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
1988 __METHOD__ );
1989 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
1990 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
1994 * Get the revision ID for the last talk page revision viewed by the talk
1995 * page owner.
1996 * @return int|null Revision ID or null
1998 public function getNewMessageRevisionId() {
1999 $newMessageRevisionId = null;
2000 $newMessageLinks = $this->getNewMessageLinks();
2001 if ( $newMessageLinks ) {
2002 // Note: getNewMessageLinks() never returns more than a single link
2003 // and it is always for the same wiki, but we double-check here in
2004 // case that changes some time in the future.
2005 if ( count( $newMessageLinks ) === 1
2006 && $newMessageLinks[0]['wiki'] === wfWikiID()
2007 && $newMessageLinks[0]['rev']
2009 $newMessageRevision = $newMessageLinks[0]['rev'];
2010 $newMessageRevisionId = $newMessageRevision->getId();
2013 return $newMessageRevisionId;
2017 * Internal uncached check for new messages
2019 * @see getNewtalk()
2020 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2021 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2022 * @param bool $fromMaster true to fetch from the master, false for a slave
2023 * @return bool True if the user has new messages
2025 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
2026 if ( $fromMaster ) {
2027 $db = wfGetDB( DB_MASTER );
2028 } else {
2029 $db = wfGetDB( DB_SLAVE );
2031 $ok = $db->selectField( 'user_newtalk', $field,
2032 array( $field => $id ), __METHOD__ );
2033 return $ok !== false;
2037 * Add or update the new messages flag
2038 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2039 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2040 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2041 * @return bool True if successful, false otherwise
2043 protected function updateNewtalk( $field, $id, $curRev = null ) {
2044 // Get timestamp of the talk page revision prior to the current one
2045 $prevRev = $curRev ? $curRev->getPrevious() : false;
2046 $ts = $prevRev ? $prevRev->getTimestamp() : null;
2047 // Mark the user as having new messages since this revision
2048 $dbw = wfGetDB( DB_MASTER );
2049 $dbw->insert( 'user_newtalk',
2050 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2051 __METHOD__,
2052 'IGNORE' );
2053 if ( $dbw->affectedRows() ) {
2054 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
2055 return true;
2056 } else {
2057 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
2058 return false;
2063 * Clear the new messages flag for the given user
2064 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2065 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2066 * @return bool True if successful, false otherwise
2068 protected function deleteNewtalk( $field, $id ) {
2069 $dbw = wfGetDB( DB_MASTER );
2070 $dbw->delete( 'user_newtalk',
2071 array( $field => $id ),
2072 __METHOD__ );
2073 if ( $dbw->affectedRows() ) {
2074 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
2075 return true;
2076 } else {
2077 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
2078 return false;
2083 * Update the 'You have new messages!' status.
2084 * @param bool $val Whether the user has new messages
2085 * @param Revision $curRev New, as yet unseen revision of the user talk page. Ignored if null or !$val.
2087 public function setNewtalk( $val, $curRev = null ) {
2088 if ( wfReadOnly() ) {
2089 return;
2092 $this->load();
2093 $this->mNewtalk = $val;
2095 if ( $this->isAnon() ) {
2096 $field = 'user_ip';
2097 $id = $this->getName();
2098 } else {
2099 $field = 'user_id';
2100 $id = $this->getId();
2102 global $wgMemc;
2104 if ( $val ) {
2105 $changed = $this->updateNewtalk( $field, $id, $curRev );
2106 } else {
2107 $changed = $this->deleteNewtalk( $field, $id );
2110 if ( $this->isAnon() ) {
2111 // Anons have a separate memcached space, since
2112 // user records aren't kept for them.
2113 $key = wfMemcKey( 'newtalk', 'ip', $id );
2114 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
2116 if ( $changed ) {
2117 $this->invalidateCache();
2122 * Generate a current or new-future timestamp to be stored in the
2123 * user_touched field when we update things.
2124 * @return string Timestamp in TS_MW format
2126 private static function newTouchedTimestamp() {
2127 global $wgClockSkewFudge;
2128 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
2132 * Clear user data from memcached.
2133 * Use after applying fun updates to the database; caller's
2134 * responsibility to update user_touched if appropriate.
2136 * Called implicitly from invalidateCache() and saveSettings().
2138 private function clearSharedCache() {
2139 $this->load();
2140 if ( $this->mId ) {
2141 global $wgMemc;
2142 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
2147 * Immediately touch the user data cache for this account.
2148 * Updates user_touched field, and removes account data from memcached
2149 * for reload on the next hit.
2151 public function invalidateCache() {
2152 if ( wfReadOnly() ) {
2153 return;
2155 $this->load();
2156 if ( $this->mId ) {
2157 $this->mTouched = self::newTouchedTimestamp();
2159 $dbw = wfGetDB( DB_MASTER );
2160 $userid = $this->mId;
2161 $touched = $this->mTouched;
2162 $method = __METHOD__;
2163 $dbw->onTransactionIdle( function() use ( $dbw, $userid, $touched, $method ) {
2164 // Prevent contention slams by checking user_touched first
2165 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2166 $needsPurge = $dbw->selectField( 'user', '1',
2167 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2168 if ( $needsPurge ) {
2169 $dbw->update( 'user',
2170 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2171 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2172 $method
2175 } );
2176 $this->clearSharedCache();
2181 * Validate the cache for this account.
2182 * @param string $timestamp A timestamp in TS_MW format
2183 * @return bool
2185 public function validateCache( $timestamp ) {
2186 $this->load();
2187 return ( $timestamp >= $this->mTouched );
2191 * Get the user touched timestamp
2192 * @return string Timestamp
2194 public function getTouched() {
2195 $this->load();
2196 return $this->mTouched;
2200 * Set the password and reset the random token.
2201 * Calls through to authentication plugin if necessary;
2202 * will have no effect if the auth plugin refuses to
2203 * pass the change through or if the legal password
2204 * checks fail.
2206 * As a special case, setting the password to null
2207 * wipes it, so the account cannot be logged in until
2208 * a new password is set, for instance via e-mail.
2210 * @param string $str New password to set
2211 * @throws PasswordError on failure
2213 * @return bool
2215 public function setPassword( $str ) {
2216 global $wgAuth;
2218 if ( $str !== null ) {
2219 if ( !$wgAuth->allowPasswordChange() ) {
2220 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2223 if ( !$this->isValidPassword( $str ) ) {
2224 global $wgMinimalPasswordLength;
2225 $valid = $this->getPasswordValidity( $str );
2226 if ( is_array( $valid ) ) {
2227 $message = array_shift( $valid );
2228 $params = $valid;
2229 } else {
2230 $message = $valid;
2231 $params = array( $wgMinimalPasswordLength );
2233 throw new PasswordError( wfMessage( $message, $params )->text() );
2237 if ( !$wgAuth->setPassword( $this, $str ) ) {
2238 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2241 $this->setInternalPassword( $str );
2243 return true;
2247 * Set the password and reset the random token unconditionally.
2249 * @param string|null $str New password to set or null to set an invalid
2250 * password hash meaning that the user will not be able to log in
2251 * through the web interface.
2253 public function setInternalPassword( $str ) {
2254 $this->load();
2255 $this->setToken();
2257 if ( $str === null ) {
2258 // Save an invalid hash...
2259 $this->mPassword = '';
2260 } else {
2261 $this->mPassword = self::crypt( $str );
2263 $this->mNewpassword = '';
2264 $this->mNewpassTime = null;
2268 * Get the user's current token.
2269 * @param bool $forceCreation Force the generation of a new token if the user doesn't have one (default=true for backwards compatibility)
2270 * @return string Token
2272 public function getToken( $forceCreation = true ) {
2273 $this->load();
2274 if ( !$this->mToken && $forceCreation ) {
2275 $this->setToken();
2277 return $this->mToken;
2281 * Set the random token (used for persistent authentication)
2282 * Called from loadDefaults() among other places.
2284 * @param string|bool $token If specified, set the token to this value
2286 public function setToken( $token = false ) {
2287 $this->load();
2288 if ( !$token ) {
2289 $this->mToken = MWCryptRand::generateHex( USER_TOKEN_LENGTH );
2290 } else {
2291 $this->mToken = $token;
2296 * Set the password for a password reminder or new account email
2298 * @param string $str New password to set or null to set an invalid
2299 * password hash meaning that the user will not be able to use it
2300 * @param bool $throttle If true, reset the throttle timestamp to the present
2302 public function setNewpassword( $str, $throttle = true ) {
2303 $this->load();
2305 if ( $str === null ) {
2306 $this->mNewpassword = '';
2307 $this->mNewpassTime = null;
2308 } else {
2309 $this->mNewpassword = self::crypt( $str );
2310 if ( $throttle ) {
2311 $this->mNewpassTime = wfTimestampNow();
2317 * Has password reminder email been sent within the last
2318 * $wgPasswordReminderResendTime hours?
2319 * @return bool
2321 public function isPasswordReminderThrottled() {
2322 global $wgPasswordReminderResendTime;
2323 $this->load();
2324 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
2325 return false;
2327 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
2328 return time() < $expiry;
2332 * Get the user's e-mail address
2333 * @return string User's email address
2335 public function getEmail() {
2336 $this->load();
2337 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
2338 return $this->mEmail;
2342 * Get the timestamp of the user's e-mail authentication
2343 * @return string TS_MW timestamp
2345 public function getEmailAuthenticationTimestamp() {
2346 $this->load();
2347 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2348 return $this->mEmailAuthenticated;
2352 * Set the user's e-mail address
2353 * @param string $str New e-mail address
2355 public function setEmail( $str ) {
2356 $this->load();
2357 if ( $str == $this->mEmail ) {
2358 return;
2360 $this->mEmail = $str;
2361 $this->invalidateEmail();
2362 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
2366 * Set the user's e-mail address and a confirmation mail if needed.
2368 * @since 1.20
2369 * @param string $str New e-mail address
2370 * @return Status
2372 public function setEmailWithConfirmation( $str ) {
2373 global $wgEnableEmail, $wgEmailAuthentication;
2375 if ( !$wgEnableEmail ) {
2376 return Status::newFatal( 'emaildisabled' );
2379 $oldaddr = $this->getEmail();
2380 if ( $str === $oldaddr ) {
2381 return Status::newGood( true );
2384 $this->setEmail( $str );
2386 if ( $str !== '' && $wgEmailAuthentication ) {
2387 // Send a confirmation request to the new address if needed
2388 $type = $oldaddr != '' ? 'changed' : 'set';
2389 $result = $this->sendConfirmationMail( $type );
2390 if ( $result->isGood() ) {
2391 // Say the the caller that a confirmation mail has been sent
2392 $result->value = 'eauth';
2394 } else {
2395 $result = Status::newGood( true );
2398 return $result;
2402 * Get the user's real name
2403 * @return string User's real name
2405 public function getRealName() {
2406 if ( !$this->isItemLoaded( 'realname' ) ) {
2407 $this->load();
2410 return $this->mRealName;
2414 * Set the user's real name
2415 * @param string $str New real name
2417 public function setRealName( $str ) {
2418 $this->load();
2419 $this->mRealName = $str;
2423 * Get the user's current setting for a given option.
2425 * @param string $oname The option to check
2426 * @param string $defaultOverride A default value returned if the option does not exist
2427 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2428 * @return string User's current value for the option
2429 * @see getBoolOption()
2430 * @see getIntOption()
2432 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2433 global $wgHiddenPrefs;
2434 $this->loadOptions();
2436 # We want 'disabled' preferences to always behave as the default value for
2437 # users, even if they have set the option explicitly in their settings (ie they
2438 # set it, and then it was disabled removing their ability to change it). But
2439 # we don't want to erase the preferences in the database in case the preference
2440 # is re-enabled again. So don't touch $mOptions, just override the returned value
2441 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2442 return self::getDefaultOption( $oname );
2445 if ( array_key_exists( $oname, $this->mOptions ) ) {
2446 return $this->mOptions[$oname];
2447 } else {
2448 return $defaultOverride;
2453 * Get all user's options
2455 * @return array
2457 public function getOptions() {
2458 global $wgHiddenPrefs;
2459 $this->loadOptions();
2460 $options = $this->mOptions;
2462 # We want 'disabled' preferences to always behave as the default value for
2463 # users, even if they have set the option explicitly in their settings (ie they
2464 # set it, and then it was disabled removing their ability to change it). But
2465 # we don't want to erase the preferences in the database in case the preference
2466 # is re-enabled again. So don't touch $mOptions, just override the returned value
2467 foreach ( $wgHiddenPrefs as $pref ) {
2468 $default = self::getDefaultOption( $pref );
2469 if ( $default !== null ) {
2470 $options[$pref] = $default;
2474 return $options;
2478 * Get the user's current setting for a given option, as a boolean value.
2480 * @param string $oname The option to check
2481 * @return bool User's current value for the option
2482 * @see getOption()
2484 public function getBoolOption( $oname ) {
2485 return (bool)$this->getOption( $oname );
2489 * Get the user's current setting for a given option, as an integer value.
2491 * @param string $oname The option to check
2492 * @param int $defaultOverride A default value returned if the option does not exist
2493 * @return int User's current value for the option
2494 * @see getOption()
2496 public function getIntOption( $oname, $defaultOverride = 0 ) {
2497 $val = $this->getOption( $oname );
2498 if ( $val == '' ) {
2499 $val = $defaultOverride;
2501 return intval( $val );
2505 * Set the given option for a user.
2507 * @param string $oname The option to set
2508 * @param mixed $val New value to set
2510 public function setOption( $oname, $val ) {
2511 $this->loadOptions();
2513 // Explicitly NULL values should refer to defaults
2514 if ( is_null( $val ) ) {
2515 $val = self::getDefaultOption( $oname );
2518 $this->mOptions[$oname] = $val;
2522 * Get a token stored in the preferences (like the watchlist one),
2523 * resetting it if it's empty (and saving changes).
2525 * @param string $oname The option name to retrieve the token from
2526 * @return string|bool User's current value for the option, or false if this option is disabled.
2527 * @see resetTokenFromOption()
2528 * @see getOption()
2530 public function getTokenFromOption( $oname ) {
2531 global $wgHiddenPrefs;
2532 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2533 return false;
2536 $token = $this->getOption( $oname );
2537 if ( !$token ) {
2538 $token = $this->resetTokenFromOption( $oname );
2539 $this->saveSettings();
2541 return $token;
2545 * Reset a token stored in the preferences (like the watchlist one).
2546 * *Does not* save user's preferences (similarly to setOption()).
2548 * @param string $oname The option name to reset the token in
2549 * @return string|bool New token value, or false if this option is disabled.
2550 * @see getTokenFromOption()
2551 * @see setOption()
2553 public function resetTokenFromOption( $oname ) {
2554 global $wgHiddenPrefs;
2555 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2556 return false;
2559 $token = MWCryptRand::generateHex( 40 );
2560 $this->setOption( $oname, $token );
2561 return $token;
2565 * Return a list of the types of user options currently returned by
2566 * User::getOptionKinds().
2568 * Currently, the option kinds are:
2569 * - 'registered' - preferences which are registered in core MediaWiki or
2570 * by extensions using the UserGetDefaultOptions hook.
2571 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2572 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2573 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2574 * be used by user scripts.
2575 * - 'special' - "preferences" that are not accessible via User::getOptions
2576 * or User::setOptions.
2577 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2578 * These are usually legacy options, removed in newer versions.
2580 * The API (and possibly others) use this function to determine the possible
2581 * option types for validation purposes, so make sure to update this when a
2582 * new option kind is added.
2584 * @see User::getOptionKinds
2585 * @return array Option kinds
2587 public static function listOptionKinds() {
2588 return array(
2589 'registered',
2590 'registered-multiselect',
2591 'registered-checkmatrix',
2592 'userjs',
2593 'special',
2594 'unused'
2599 * Return an associative array mapping preferences keys to the kind of a preference they're
2600 * used for. Different kinds are handled differently when setting or reading preferences.
2602 * See User::listOptionKinds for the list of valid option types that can be provided.
2604 * @see User::listOptionKinds
2605 * @param IContextSource $context
2606 * @param array $options Assoc. array with options keys to check as keys. Defaults to $this->mOptions.
2607 * @return array the key => kind mapping data
2609 public function getOptionKinds( IContextSource $context, $options = null ) {
2610 $this->loadOptions();
2611 if ( $options === null ) {
2612 $options = $this->mOptions;
2615 $prefs = Preferences::getPreferences( $this, $context );
2616 $mapping = array();
2618 // Pull out the "special" options, so they don't get converted as
2619 // multiselect or checkmatrix.
2620 $specialOptions = array_fill_keys( Preferences::getSaveBlacklist(), true );
2621 foreach ( $specialOptions as $name => $value ) {
2622 unset( $prefs[$name] );
2625 // Multiselect and checkmatrix options are stored in the database with
2626 // one key per option, each having a boolean value. Extract those keys.
2627 $multiselectOptions = array();
2628 foreach ( $prefs as $name => $info ) {
2629 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2630 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2631 $opts = HTMLFormField::flattenOptions( $info['options'] );
2632 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2634 foreach ( $opts as $value ) {
2635 $multiselectOptions["$prefix$value"] = true;
2638 unset( $prefs[$name] );
2641 $checkmatrixOptions = array();
2642 foreach ( $prefs as $name => $info ) {
2643 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2644 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2645 $columns = HTMLFormField::flattenOptions( $info['columns'] );
2646 $rows = HTMLFormField::flattenOptions( $info['rows'] );
2647 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2649 foreach ( $columns as $column ) {
2650 foreach ( $rows as $row ) {
2651 $checkmatrixOptions["$prefix-$column-$row"] = true;
2655 unset( $prefs[$name] );
2659 // $value is ignored
2660 foreach ( $options as $key => $value ) {
2661 if ( isset( $prefs[$key] ) ) {
2662 $mapping[$key] = 'registered';
2663 } elseif ( isset( $multiselectOptions[$key] ) ) {
2664 $mapping[$key] = 'registered-multiselect';
2665 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2666 $mapping[$key] = 'registered-checkmatrix';
2667 } elseif ( isset( $specialOptions[$key] ) ) {
2668 $mapping[$key] = 'special';
2669 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2670 $mapping[$key] = 'userjs';
2671 } else {
2672 $mapping[$key] = 'unused';
2676 return $mapping;
2680 * Reset certain (or all) options to the site defaults
2682 * The optional parameter determines which kinds of preferences will be reset.
2683 * Supported values are everything that can be reported by getOptionKinds()
2684 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2686 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2687 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2688 * for backwards-compatibility.
2689 * @param IContextSource|null $context Context source used when $resetKinds
2690 * does not contain 'all', passed to getOptionKinds().
2691 * Defaults to RequestContext::getMain() when null.
2693 public function resetOptions(
2694 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2695 IContextSource $context = null
2697 $this->load();
2698 $defaultOptions = self::getDefaultOptions();
2700 if ( !is_array( $resetKinds ) ) {
2701 $resetKinds = array( $resetKinds );
2704 if ( in_array( 'all', $resetKinds ) ) {
2705 $newOptions = $defaultOptions;
2706 } else {
2707 if ( $context === null ) {
2708 $context = RequestContext::getMain();
2711 $optionKinds = $this->getOptionKinds( $context );
2712 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
2713 $newOptions = array();
2715 // Use default values for the options that should be deleted, and
2716 // copy old values for the ones that shouldn't.
2717 foreach ( $this->mOptions as $key => $value ) {
2718 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2719 if ( array_key_exists( $key, $defaultOptions ) ) {
2720 $newOptions[$key] = $defaultOptions[$key];
2722 } else {
2723 $newOptions[$key] = $value;
2728 $this->mOptions = $newOptions;
2729 $this->mOptionsLoaded = true;
2733 * Get the user's preferred date format.
2734 * @return string User's preferred date format
2736 public function getDatePreference() {
2737 // Important migration for old data rows
2738 if ( is_null( $this->mDatePreference ) ) {
2739 global $wgLang;
2740 $value = $this->getOption( 'date' );
2741 $map = $wgLang->getDatePreferenceMigrationMap();
2742 if ( isset( $map[$value] ) ) {
2743 $value = $map[$value];
2745 $this->mDatePreference = $value;
2747 return $this->mDatePreference;
2751 * Determine based on the wiki configuration and the user's options,
2752 * whether this user must be over HTTPS no matter what.
2754 * @return bool
2756 public function requiresHTTPS() {
2757 global $wgSecureLogin;
2758 if ( !$wgSecureLogin ) {
2759 return false;
2760 } else {
2761 $https = $this->getBoolOption( 'prefershttps' );
2762 wfRunHooks( 'UserRequiresHTTPS', array( $this, &$https ) );
2763 if ( $https ) {
2764 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2766 return $https;
2771 * Get the user preferred stub threshold
2773 * @return int
2775 public function getStubThreshold() {
2776 global $wgMaxArticleSize; # Maximum article size, in Kb
2777 $threshold = $this->getIntOption( 'stubthreshold' );
2778 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2779 // If they have set an impossible value, disable the preference
2780 // so we can use the parser cache again.
2781 $threshold = 0;
2783 return $threshold;
2787 * Get the permissions this user has.
2788 * @return array Array of String permission names
2790 public function getRights() {
2791 if ( is_null( $this->mRights ) ) {
2792 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2793 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
2794 // Force reindexation of rights when a hook has unset one of them
2795 $this->mRights = array_values( array_unique( $this->mRights ) );
2797 return $this->mRights;
2801 * Get the list of explicit group memberships this user has.
2802 * The implicit * and user groups are not included.
2803 * @return array Array of String internal group names
2805 public function getGroups() {
2806 $this->load();
2807 $this->loadGroups();
2808 return $this->mGroups;
2812 * Get the list of implicit group memberships this user has.
2813 * This includes all explicit groups, plus 'user' if logged in,
2814 * '*' for all accounts, and autopromoted groups
2815 * @param bool $recache Whether to avoid the cache
2816 * @return array Array of String internal group names
2818 public function getEffectiveGroups( $recache = false ) {
2819 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
2820 wfProfileIn( __METHOD__ );
2821 $this->mEffectiveGroups = array_unique( array_merge(
2822 $this->getGroups(), // explicit groups
2823 $this->getAutomaticGroups( $recache ) // implicit groups
2824 ) );
2825 // Hook for additional groups
2826 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
2827 // Force reindexation of groups when a hook has unset one of them
2828 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
2829 wfProfileOut( __METHOD__ );
2831 return $this->mEffectiveGroups;
2835 * Get the list of implicit group memberships this user has.
2836 * This includes 'user' if logged in, '*' for all accounts,
2837 * and autopromoted groups
2838 * @param bool $recache Whether to avoid the cache
2839 * @return array Array of String internal group names
2841 public function getAutomaticGroups( $recache = false ) {
2842 if ( $recache || is_null( $this->mImplicitGroups ) ) {
2843 wfProfileIn( __METHOD__ );
2844 $this->mImplicitGroups = array( '*' );
2845 if ( $this->getId() ) {
2846 $this->mImplicitGroups[] = 'user';
2848 $this->mImplicitGroups = array_unique( array_merge(
2849 $this->mImplicitGroups,
2850 Autopromote::getAutopromoteGroups( $this )
2851 ) );
2853 if ( $recache ) {
2854 // Assure data consistency with rights/groups,
2855 // as getEffectiveGroups() depends on this function
2856 $this->mEffectiveGroups = null;
2858 wfProfileOut( __METHOD__ );
2860 return $this->mImplicitGroups;
2864 * Returns the groups the user has belonged to.
2866 * The user may still belong to the returned groups. Compare with getGroups().
2868 * The function will not return groups the user had belonged to before MW 1.17
2870 * @return array Names of the groups the user has belonged to.
2872 public function getFormerGroups() {
2873 if ( is_null( $this->mFormerGroups ) ) {
2874 $dbr = wfGetDB( DB_MASTER );
2875 $res = $dbr->select( 'user_former_groups',
2876 array( 'ufg_group' ),
2877 array( 'ufg_user' => $this->mId ),
2878 __METHOD__ );
2879 $this->mFormerGroups = array();
2880 foreach ( $res as $row ) {
2881 $this->mFormerGroups[] = $row->ufg_group;
2884 return $this->mFormerGroups;
2888 * Get the user's edit count.
2889 * @return int|null null for anonymous users
2891 public function getEditCount() {
2892 if ( !$this->getId() ) {
2893 return null;
2896 if ( !isset( $this->mEditCount ) ) {
2897 /* Populate the count, if it has not been populated yet */
2898 wfProfileIn( __METHOD__ );
2899 $dbr = wfGetDB( DB_SLAVE );
2900 // check if the user_editcount field has been initialized
2901 $count = $dbr->selectField(
2902 'user', 'user_editcount',
2903 array( 'user_id' => $this->mId ),
2904 __METHOD__
2907 if ( $count === null ) {
2908 // it has not been initialized. do so.
2909 $count = $this->initEditCount();
2911 $this->mEditCount = $count;
2912 wfProfileOut( __METHOD__ );
2914 return (int)$this->mEditCount;
2918 * Add the user to the given group.
2919 * This takes immediate effect.
2920 * @param string $group Name of the group to add
2922 public function addGroup( $group ) {
2923 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2924 $dbw = wfGetDB( DB_MASTER );
2925 if ( $this->getId() ) {
2926 $dbw->insert( 'user_groups',
2927 array(
2928 'ug_user' => $this->getID(),
2929 'ug_group' => $group,
2931 __METHOD__,
2932 array( 'IGNORE' ) );
2935 $this->loadGroups();
2936 $this->mGroups[] = $group;
2937 // In case loadGroups was not called before, we now have the right twice.
2938 // Get rid of the duplicate.
2939 $this->mGroups = array_unique( $this->mGroups );
2941 // Refresh the groups caches, and clear the rights cache so it will be
2942 // refreshed on the next call to $this->getRights().
2943 $this->getEffectiveGroups( true );
2944 $this->mRights = null;
2946 $this->invalidateCache();
2950 * Remove the user from the given group.
2951 * This takes immediate effect.
2952 * @param string $group Name of the group to remove
2954 public function removeGroup( $group ) {
2955 $this->load();
2956 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
2957 $dbw = wfGetDB( DB_MASTER );
2958 $dbw->delete( 'user_groups',
2959 array(
2960 'ug_user' => $this->getID(),
2961 'ug_group' => $group,
2962 ), __METHOD__ );
2963 // Remember that the user was in this group
2964 $dbw->insert( 'user_former_groups',
2965 array(
2966 'ufg_user' => $this->getID(),
2967 'ufg_group' => $group,
2969 __METHOD__,
2970 array( 'IGNORE' ) );
2972 $this->loadGroups();
2973 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
2975 // Refresh the groups caches, and clear the rights cache so it will be
2976 // refreshed on the next call to $this->getRights().
2977 $this->getEffectiveGroups( true );
2978 $this->mRights = null;
2980 $this->invalidateCache();
2984 * Get whether the user is logged in
2985 * @return bool
2987 public function isLoggedIn() {
2988 return $this->getID() != 0;
2992 * Get whether the user is anonymous
2993 * @return bool
2995 public function isAnon() {
2996 return !$this->isLoggedIn();
3000 * Check if user is allowed to access a feature / make an action
3002 * @internal param \String $varargs permissions to test
3003 * @return bool True if user is allowed to perform *any* of the given actions
3005 * @return bool
3007 public function isAllowedAny( /*...*/ ) {
3008 $permissions = func_get_args();
3009 foreach ( $permissions as $permission ) {
3010 if ( $this->isAllowed( $permission ) ) {
3011 return true;
3014 return false;
3019 * @internal param $varargs string
3020 * @return bool True if the user is allowed to perform *all* of the given actions
3022 public function isAllowedAll( /*...*/ ) {
3023 $permissions = func_get_args();
3024 foreach ( $permissions as $permission ) {
3025 if ( !$this->isAllowed( $permission ) ) {
3026 return false;
3029 return true;
3033 * Internal mechanics of testing a permission
3034 * @param string $action
3035 * @return bool
3037 public function isAllowed( $action = '' ) {
3038 if ( $action === '' ) {
3039 return true; // In the spirit of DWIM
3041 // Patrolling may not be enabled
3042 if ( $action === 'patrol' || $action === 'autopatrol' ) {
3043 global $wgUseRCPatrol, $wgUseNPPatrol;
3044 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3045 return false;
3048 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3049 // by misconfiguration: 0 == 'foo'
3050 return in_array( $action, $this->getRights(), true );
3054 * Check whether to enable recent changes patrol features for this user
3055 * @return bool True or false
3057 public function useRCPatrol() {
3058 global $wgUseRCPatrol;
3059 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3063 * Check whether to enable new pages patrol features for this user
3064 * @return bool True or false
3066 public function useNPPatrol() {
3067 global $wgUseRCPatrol, $wgUseNPPatrol;
3068 return (
3069 ( $wgUseRCPatrol || $wgUseNPPatrol )
3070 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3075 * Get the WebRequest object to use with this object
3077 * @return WebRequest
3079 public function getRequest() {
3080 if ( $this->mRequest ) {
3081 return $this->mRequest;
3082 } else {
3083 global $wgRequest;
3084 return $wgRequest;
3089 * Get the current skin, loading it if required
3090 * @return Skin The current skin
3091 * @todo FIXME: Need to check the old failback system [AV]
3092 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3094 public function getSkin() {
3095 wfDeprecated( __METHOD__, '1.18' );
3096 return RequestContext::getMain()->getSkin();
3100 * Get a WatchedItem for this user and $title.
3102 * @since 1.22 $checkRights parameter added
3103 * @param Title $title
3104 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3105 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3106 * @return WatchedItem
3108 public function getWatchedItem( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3109 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3111 if ( isset( $this->mWatchedItems[$key] ) ) {
3112 return $this->mWatchedItems[$key];
3115 if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
3116 $this->mWatchedItems = array();
3119 $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title, $checkRights );
3120 return $this->mWatchedItems[$key];
3124 * Check the watched status of an article.
3125 * @since 1.22 $checkRights parameter added
3126 * @param Title $title Title of the article to look at
3127 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3128 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3129 * @return bool
3131 public function isWatched( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3132 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3136 * Watch an article.
3137 * @since 1.22 $checkRights parameter added
3138 * @param Title $title Title of the article to look at
3139 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3140 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3142 public function addWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3143 $this->getWatchedItem( $title, $checkRights )->addWatch();
3144 $this->invalidateCache();
3148 * Stop watching an article.
3149 * @since 1.22 $checkRights parameter added
3150 * @param Title $title Title of the article to look at
3151 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3152 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3154 public function removeWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3155 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3156 $this->invalidateCache();
3160 * Clear the user's notification timestamp for the given title.
3161 * If e-notif e-mails are on, they will receive notification mails on
3162 * the next change of the page if it's watched etc.
3163 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3164 * @param Title $title Title of the article to look at
3165 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3167 public function clearNotification( &$title, $oldid = 0 ) {
3168 global $wgUseEnotif, $wgShowUpdatedMarker;
3170 // Do nothing if the database is locked to writes
3171 if ( wfReadOnly() ) {
3172 return;
3175 // Do nothing if not allowed to edit the watchlist
3176 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3177 return;
3180 // If we're working on user's talk page, we should update the talk page message indicator
3181 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3182 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3183 return;
3186 $nextid = $oldid ? $title->getNextRevisionID( $oldid ) : null;
3188 if ( !$oldid || !$nextid ) {
3189 // If we're looking at the latest revision, we should definitely clear it
3190 $this->setNewtalk( false );
3191 } else {
3192 // Otherwise we should update its revision, if it's present
3193 if ( $this->getNewtalk() ) {
3194 // Naturally the other one won't clear by itself
3195 $this->setNewtalk( false );
3196 $this->setNewtalk( true, Revision::newFromId( $nextid ) );
3201 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3202 return;
3205 if ( $this->isAnon() ) {
3206 // Nothing else to do...
3207 return;
3210 // Only update the timestamp if the page is being watched.
3211 // The query to find out if it is watched is cached both in memcached and per-invocation,
3212 // and when it does have to be executed, it can be on a slave
3213 // If this is the user's newtalk page, we always update the timestamp
3214 $force = '';
3215 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3216 $force = 'force';
3219 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3223 * Resets all of the given user's page-change notification timestamps.
3224 * If e-notif e-mails are on, they will receive notification mails on
3225 * the next change of any watched page.
3226 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3228 public function clearAllNotifications() {
3229 if ( wfReadOnly() ) {
3230 return;
3233 // Do nothing if not allowed to edit the watchlist
3234 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3235 return;
3238 global $wgUseEnotif, $wgShowUpdatedMarker;
3239 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3240 $this->setNewtalk( false );
3241 return;
3243 $id = $this->getId();
3244 if ( $id != 0 ) {
3245 $dbw = wfGetDB( DB_MASTER );
3246 $dbw->update( 'watchlist',
3247 array( /* SET */ 'wl_notificationtimestamp' => null ),
3248 array( /* WHERE */ 'wl_user' => $id ),
3249 __METHOD__
3251 // We also need to clear here the "you have new message" notification for the own user_talk page;
3252 // it's cleared one page view later in WikiPage::doViewUpdates().
3257 * Set this user's options from an encoded string
3258 * @param string $str Encoded options to import
3260 * @deprecated since 1.19 due to removal of user_options from the user table
3262 private function decodeOptions( $str ) {
3263 wfDeprecated( __METHOD__, '1.19' );
3264 if ( !$str ) {
3265 return;
3268 $this->mOptionsLoaded = true;
3269 $this->mOptionOverrides = array();
3271 // If an option is not set in $str, use the default value
3272 $this->mOptions = self::getDefaultOptions();
3274 $a = explode( "\n", $str );
3275 foreach ( $a as $s ) {
3276 $m = array();
3277 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
3278 $this->mOptions[$m[1]] = $m[2];
3279 $this->mOptionOverrides[$m[1]] = $m[2];
3285 * Set a cookie on the user's client. Wrapper for
3286 * WebResponse::setCookie
3287 * @param string $name Name of the cookie to set
3288 * @param string $value Value to set
3289 * @param int $exp Expiration time, as a UNIX time value;
3290 * if 0 or not specified, use the default $wgCookieExpiration
3291 * @param bool $secure
3292 * true: Force setting the secure attribute when setting the cookie
3293 * false: Force NOT setting the secure attribute when setting the cookie
3294 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3295 * @param array $params Array of options sent passed to WebResponse::setcookie()
3297 protected function setCookie( $name, $value, $exp = 0, $secure = null, $params = array() ) {
3298 $params['secure'] = $secure;
3299 $this->getRequest()->response()->setcookie( $name, $value, $exp, $params );
3303 * Clear a cookie on the user's client
3304 * @param string $name Name of the cookie to clear
3305 * @param bool $secure
3306 * true: Force setting the secure attribute when setting the cookie
3307 * false: Force NOT setting the secure attribute when setting the cookie
3308 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3309 * @param array $params Array of options sent passed to WebResponse::setcookie()
3311 protected function clearCookie( $name, $secure = null, $params = array() ) {
3312 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3316 * Set the default cookies for this session on the user's client.
3318 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3319 * is passed.
3320 * @param bool $secure Whether to force secure/insecure cookies or use default
3321 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3323 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3324 if ( $request === null ) {
3325 $request = $this->getRequest();
3328 $this->load();
3329 if ( 0 == $this->mId ) {
3330 return;
3332 if ( !$this->mToken ) {
3333 // When token is empty or NULL generate a new one and then save it to the database
3334 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3335 // Simply by setting every cell in the user_token column to NULL and letting them be
3336 // regenerated as users log back into the wiki.
3337 $this->setToken();
3338 $this->saveSettings();
3340 $session = array(
3341 'wsUserID' => $this->mId,
3342 'wsToken' => $this->mToken,
3343 'wsUserName' => $this->getName()
3345 $cookies = array(
3346 'UserID' => $this->mId,
3347 'UserName' => $this->getName(),
3349 if ( $rememberMe ) {
3350 $cookies['Token'] = $this->mToken;
3351 } else {
3352 $cookies['Token'] = false;
3355 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3357 foreach ( $session as $name => $value ) {
3358 $request->setSessionData( $name, $value );
3360 foreach ( $cookies as $name => $value ) {
3361 if ( $value === false ) {
3362 $this->clearCookie( $name );
3363 } else {
3364 $this->setCookie( $name, $value, 0, $secure );
3369 * If wpStickHTTPS was selected, also set an insecure cookie that
3370 * will cause the site to redirect the user to HTTPS, if they access
3371 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3372 * as the one set by centralauth (bug 53538). Also set it to session, or
3373 * standard time setting, based on if rememberme was set.
3375 if ( $request->getCheck( 'wpStickHTTPS' ) || $this->requiresHTTPS() ) {
3376 $this->setCookie(
3377 'forceHTTPS',
3378 'true',
3379 $rememberMe ? 0 : null,
3380 false,
3381 array( 'prefix' => '' ) // no prefix
3387 * Log this user out.
3389 public function logout() {
3390 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3391 $this->doLogout();
3396 * Clear the user's cookies and session, and reset the instance cache.
3397 * @see logout()
3399 public function doLogout() {
3400 $this->clearInstanceCache( 'defaults' );
3402 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3404 $this->clearCookie( 'UserID' );
3405 $this->clearCookie( 'Token' );
3406 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3408 // Remember when user logged out, to prevent seeing cached pages
3409 $this->setCookie( 'LoggedOut', time(), time() + 86400 );
3413 * Save this user's settings into the database.
3414 * @todo Only rarely do all these fields need to be set!
3416 public function saveSettings() {
3417 global $wgAuth;
3419 $this->load();
3420 if ( wfReadOnly() ) {
3421 return;
3423 if ( 0 == $this->mId ) {
3424 return;
3427 $this->mTouched = self::newTouchedTimestamp();
3428 if ( !$wgAuth->allowSetLocalPassword() ) {
3429 $this->mPassword = '';
3432 $dbw = wfGetDB( DB_MASTER );
3433 $dbw->update( 'user',
3434 array( /* SET */
3435 'user_name' => $this->mName,
3436 'user_password' => $this->mPassword,
3437 'user_newpassword' => $this->mNewpassword,
3438 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3439 'user_real_name' => $this->mRealName,
3440 'user_email' => $this->mEmail,
3441 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3442 'user_touched' => $dbw->timestamp( $this->mTouched ),
3443 'user_token' => strval( $this->mToken ),
3444 'user_email_token' => $this->mEmailToken,
3445 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3446 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires ),
3447 ), array( /* WHERE */
3448 'user_id' => $this->mId
3449 ), __METHOD__
3452 $this->saveOptions();
3454 wfRunHooks( 'UserSaveSettings', array( $this ) );
3455 $this->clearSharedCache();
3456 $this->getUserPage()->invalidateCache();
3460 * If only this user's username is known, and it exists, return the user ID.
3461 * @return int
3463 public function idForName() {
3464 $s = trim( $this->getName() );
3465 if ( $s === '' ) {
3466 return 0;
3469 $dbr = wfGetDB( DB_SLAVE );
3470 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
3471 if ( $id === false ) {
3472 $id = 0;
3474 return $id;
3478 * Add a user to the database, return the user object
3480 * @param string $name Username to add
3481 * @param array $params Array of Strings Non-default parameters to save to the database as user_* fields:
3482 * - password The user's password hash. Password logins will be disabled if this is omitted.
3483 * - newpassword Hash for a temporary password that has been mailed to the user
3484 * - email The user's email address
3485 * - email_authenticated The email authentication timestamp
3486 * - real_name The user's real name
3487 * - options An associative array of non-default options
3488 * - token Random authentication token. Do not set.
3489 * - registration Registration timestamp. Do not set.
3491 * @return User|null User object, or null if the username already exists
3493 public static function createNew( $name, $params = array() ) {
3494 $user = new User;
3495 $user->load();
3496 $user->setToken(); // init token
3497 if ( isset( $params['options'] ) ) {
3498 $user->mOptions = $params['options'] + (array)$user->mOptions;
3499 unset( $params['options'] );
3501 $dbw = wfGetDB( DB_MASTER );
3502 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3504 $fields = array(
3505 'user_id' => $seqVal,
3506 'user_name' => $name,
3507 'user_password' => $user->mPassword,
3508 'user_newpassword' => $user->mNewpassword,
3509 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
3510 'user_email' => $user->mEmail,
3511 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3512 'user_real_name' => $user->mRealName,
3513 'user_token' => strval( $user->mToken ),
3514 'user_registration' => $dbw->timestamp( $user->mRegistration ),
3515 'user_editcount' => 0,
3516 'user_touched' => $dbw->timestamp( self::newTouchedTimestamp() ),
3518 foreach ( $params as $name => $value ) {
3519 $fields["user_$name"] = $value;
3521 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
3522 if ( $dbw->affectedRows() ) {
3523 $newUser = User::newFromId( $dbw->insertId() );
3524 } else {
3525 $newUser = null;
3527 return $newUser;
3531 * Add this existing user object to the database. If the user already
3532 * exists, a fatal status object is returned, and the user object is
3533 * initialised with the data from the database.
3535 * Previously, this function generated a DB error due to a key conflict
3536 * if the user already existed. Many extension callers use this function
3537 * in code along the lines of:
3539 * $user = User::newFromName( $name );
3540 * if ( !$user->isLoggedIn() ) {
3541 * $user->addToDatabase();
3543 * // do something with $user...
3545 * However, this was vulnerable to a race condition (bug 16020). By
3546 * initialising the user object if the user exists, we aim to support this
3547 * calling sequence as far as possible.
3549 * Note that if the user exists, this function will acquire a write lock,
3550 * so it is still advisable to make the call conditional on isLoggedIn(),
3551 * and to commit the transaction after calling.
3553 * @throws MWException
3554 * @return Status
3556 public function addToDatabase() {
3557 $this->load();
3558 if ( !$this->mToken ) {
3559 $this->setToken(); // init token
3562 $this->mTouched = self::newTouchedTimestamp();
3564 $dbw = wfGetDB( DB_MASTER );
3565 $inWrite = $dbw->writesOrCallbacksPending();
3566 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3567 $dbw->insert( 'user',
3568 array(
3569 'user_id' => $seqVal,
3570 'user_name' => $this->mName,
3571 'user_password' => $this->mPassword,
3572 'user_newpassword' => $this->mNewpassword,
3573 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3574 'user_email' => $this->mEmail,
3575 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3576 'user_real_name' => $this->mRealName,
3577 'user_token' => strval( $this->mToken ),
3578 'user_registration' => $dbw->timestamp( $this->mRegistration ),
3579 'user_editcount' => 0,
3580 'user_touched' => $dbw->timestamp( $this->mTouched ),
3581 ), __METHOD__,
3582 array( 'IGNORE' )
3584 if ( !$dbw->affectedRows() ) {
3585 if ( !$inWrite ) {
3586 // XXX: Get out of REPEATABLE-READ so the SELECT below works.
3587 // Often this case happens early in views before any writes.
3588 // This shows up at least with CentralAuth.
3589 $dbw->commit( __METHOD__, 'flush' );
3591 $this->mId = $dbw->selectField( 'user', 'user_id',
3592 array( 'user_name' => $this->mName ), __METHOD__ );
3593 $loaded = false;
3594 if ( $this->mId ) {
3595 if ( $this->loadFromDatabase() ) {
3596 $loaded = true;
3599 if ( !$loaded ) {
3600 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
3601 "to insert user '{$this->mName}' row, but it was not present in select!" );
3603 return Status::newFatal( 'userexists' );
3605 $this->mId = $dbw->insertId();
3607 // Clear instance cache other than user table data, which is already accurate
3608 $this->clearInstanceCache();
3610 $this->saveOptions();
3611 return Status::newGood();
3615 * If this user is logged-in and blocked,
3616 * block any IP address they've successfully logged in from.
3617 * @return bool A block was spread
3619 public function spreadAnyEditBlock() {
3620 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3621 return $this->spreadBlock();
3623 return false;
3627 * If this (non-anonymous) user is blocked,
3628 * block the IP address they've successfully logged in from.
3629 * @return bool A block was spread
3631 protected function spreadBlock() {
3632 wfDebug( __METHOD__ . "()\n" );
3633 $this->load();
3634 if ( $this->mId == 0 ) {
3635 return false;
3638 $userblock = Block::newFromTarget( $this->getName() );
3639 if ( !$userblock ) {
3640 return false;
3643 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3647 * Get whether the user is explicitly blocked from account creation.
3648 * @return bool|Block
3650 public function isBlockedFromCreateAccount() {
3651 $this->getBlockedStatus();
3652 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
3653 return $this->mBlock;
3656 # bug 13611: if the IP address the user is trying to create an account from is
3657 # blocked with createaccount disabled, prevent new account creation there even
3658 # when the user is logged in
3659 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3660 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
3662 return $this->mBlockedFromCreateAccount instanceof Block && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
3663 ? $this->mBlockedFromCreateAccount
3664 : false;
3668 * Get whether the user is blocked from using Special:Emailuser.
3669 * @return bool
3671 public function isBlockedFromEmailuser() {
3672 $this->getBlockedStatus();
3673 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
3677 * Get whether the user is allowed to create an account.
3678 * @return bool
3680 public function isAllowedToCreateAccount() {
3681 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3685 * Get this user's personal page title.
3687 * @return Title User's personal page title
3689 public function getUserPage() {
3690 return Title::makeTitle( NS_USER, $this->getName() );
3694 * Get this user's talk page title.
3696 * @return Title User's talk page title
3698 public function getTalkPage() {
3699 $title = $this->getUserPage();
3700 return $title->getTalkPage();
3704 * Determine whether the user is a newbie. Newbies are either
3705 * anonymous IPs, or the most recently created accounts.
3706 * @return bool
3708 public function isNewbie() {
3709 return !$this->isAllowed( 'autoconfirmed' );
3713 * Check to see if the given clear-text password is one of the accepted passwords
3714 * @param string $password user password.
3715 * @return bool True if the given password is correct, otherwise False.
3717 public function checkPassword( $password ) {
3718 global $wgAuth, $wgLegacyEncoding;
3719 $this->load();
3721 // Certain authentication plugins do NOT want to save
3722 // domain passwords in a mysql database, so we should
3723 // check this (in case $wgAuth->strict() is false).
3725 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3726 return true;
3727 } elseif ( $wgAuth->strict() ) {
3728 // Auth plugin doesn't allow local authentication
3729 return false;
3730 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3731 // Auth plugin doesn't allow local authentication for this user name
3732 return false;
3734 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
3735 return true;
3736 } elseif ( $wgLegacyEncoding ) {
3737 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3738 // Check for this with iconv
3739 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3740 if ( $cp1252Password != $password
3741 && self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId )
3743 return true;
3746 return false;
3750 * Check if the given clear-text password matches the temporary password
3751 * sent by e-mail for password reset operations.
3753 * @param string $plaintext
3755 * @return bool True if matches, false otherwise
3757 public function checkTemporaryPassword( $plaintext ) {
3758 global $wgNewPasswordExpiry;
3760 $this->load();
3761 if ( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) {
3762 if ( is_null( $this->mNewpassTime ) ) {
3763 return true;
3765 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
3766 return ( time() < $expiry );
3767 } else {
3768 return false;
3773 * Alias for getEditToken.
3774 * @deprecated since 1.19, use getEditToken instead.
3776 * @param string|array $salt of Strings Optional function-specific data for hashing
3777 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3778 * @return string The new edit token
3780 public function editToken( $salt = '', $request = null ) {
3781 wfDeprecated( __METHOD__, '1.19' );
3782 return $this->getEditToken( $salt, $request );
3786 * Initialize (if necessary) and return a session token value
3787 * which can be used in edit forms to show that the user's
3788 * login credentials aren't being hijacked with a foreign form
3789 * submission.
3791 * @since 1.19
3793 * @param string|array $salt of Strings Optional function-specific data for hashing
3794 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3795 * @return string The new edit token
3797 public function getEditToken( $salt = '', $request = null ) {
3798 if ( $request == null ) {
3799 $request = $this->getRequest();
3802 if ( $this->isAnon() ) {
3803 return EDIT_TOKEN_SUFFIX;
3804 } else {
3805 $token = $request->getSessionData( 'wsEditToken' );
3806 if ( $token === null ) {
3807 $token = MWCryptRand::generateHex( 32 );
3808 $request->setSessionData( 'wsEditToken', $token );
3810 if ( is_array( $salt ) ) {
3811 $salt = implode( '|', $salt );
3813 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
3818 * Generate a looking random token for various uses.
3820 * @return string The new random token
3821 * @deprecated since 1.20: Use MWCryptRand for secure purposes or wfRandomString for pseudo-randomness
3823 public static function generateToken() {
3824 return MWCryptRand::generateHex( 32 );
3828 * Check given value against the token value stored in the session.
3829 * A match should confirm that the form was submitted from the
3830 * user's own login session, not a form submission from a third-party
3831 * site.
3833 * @param string $val Input value to compare
3834 * @param string $salt Optional function-specific data for hashing
3835 * @param WebRequest|null $request Object to use or null to use $wgRequest
3836 * @return bool Whether the token matches
3838 public function matchEditToken( $val, $salt = '', $request = null ) {
3839 $sessionToken = $this->getEditToken( $salt, $request );
3840 if ( $val != $sessionToken ) {
3841 wfDebug( "User::matchEditToken: broken session data\n" );
3843 return $val == $sessionToken;
3847 * Check given value against the token value stored in the session,
3848 * ignoring the suffix.
3850 * @param string $val Input value to compare
3851 * @param string $salt Optional function-specific data for hashing
3852 * @param WebRequest|null $request object to use or null to use $wgRequest
3853 * @return bool Whether the token matches
3855 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3856 $sessionToken = $this->getEditToken( $salt, $request );
3857 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3861 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3862 * mail to the user's given address.
3864 * @param string $type Message to send, either "created", "changed" or "set"
3865 * @return Status
3867 public function sendConfirmationMail( $type = 'created' ) {
3868 global $wgLang;
3869 $expiration = null; // gets passed-by-ref and defined in next line.
3870 $token = $this->confirmationToken( $expiration );
3871 $url = $this->confirmationTokenUrl( $token );
3872 $invalidateURL = $this->invalidationTokenUrl( $token );
3873 $this->saveSettings();
3875 if ( $type == 'created' || $type === false ) {
3876 $message = 'confirmemail_body';
3877 } elseif ( $type === true ) {
3878 $message = 'confirmemail_body_changed';
3879 } else {
3880 // Messages: confirmemail_body_changed, confirmemail_body_set
3881 $message = 'confirmemail_body_' . $type;
3884 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3885 wfMessage( $message,
3886 $this->getRequest()->getIP(),
3887 $this->getName(),
3888 $url,
3889 $wgLang->timeanddate( $expiration, false ),
3890 $invalidateURL,
3891 $wgLang->date( $expiration, false ),
3892 $wgLang->time( $expiration, false ) )->text() );
3896 * Send an e-mail to this user's account. Does not check for
3897 * confirmed status or validity.
3899 * @param string $subject Message subject
3900 * @param string $body Message body
3901 * @param string $from Optional From address; if unspecified, default $wgPasswordSender will be used
3902 * @param string $replyto Reply-To address
3903 * @return Status
3905 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3906 if ( is_null( $from ) ) {
3907 global $wgPasswordSender;
3908 $sender = new MailAddress( $wgPasswordSender,
3909 wfMessage( 'emailsender' )->inContentLanguage()->text() );
3910 } else {
3911 $sender = new MailAddress( $from );
3914 $to = new MailAddress( $this );
3915 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
3919 * Generate, store, and return a new e-mail confirmation code.
3920 * A hash (unsalted, since it's used as a key) is stored.
3922 * @note Call saveSettings() after calling this function to commit
3923 * this change to the database.
3925 * @param string &$expiration Accepts the expiration time
3926 * @return string New token
3928 protected function confirmationToken( &$expiration ) {
3929 global $wgUserEmailConfirmationTokenExpiry;
3930 $now = time();
3931 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
3932 $expiration = wfTimestamp( TS_MW, $expires );
3933 $this->load();
3934 $token = MWCryptRand::generateHex( 32 );
3935 $hash = md5( $token );
3936 $this->mEmailToken = $hash;
3937 $this->mEmailTokenExpires = $expiration;
3938 return $token;
3942 * Return a URL the user can use to confirm their email address.
3943 * @param string $token Accepts the email confirmation token
3944 * @return string New token URL
3946 protected function confirmationTokenUrl( $token ) {
3947 return $this->getTokenUrl( 'ConfirmEmail', $token );
3951 * Return a URL the user can use to invalidate their email address.
3952 * @param string $token Accepts the email confirmation token
3953 * @return string New token URL
3955 protected function invalidationTokenUrl( $token ) {
3956 return $this->getTokenUrl( 'InvalidateEmail', $token );
3960 * Internal function to format the e-mail validation/invalidation URLs.
3961 * This uses a quickie hack to use the
3962 * hardcoded English names of the Special: pages, for ASCII safety.
3964 * @note Since these URLs get dropped directly into emails, using the
3965 * short English names avoids insanely long URL-encoded links, which
3966 * also sometimes can get corrupted in some browsers/mailers
3967 * (bug 6957 with Gmail and Internet Explorer).
3969 * @param string $page Special page
3970 * @param string $token Token
3971 * @return string Formatted URL
3973 protected function getTokenUrl( $page, $token ) {
3974 // Hack to bypass localization of 'Special:'
3975 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
3976 return $title->getCanonicalURL();
3980 * Mark the e-mail address confirmed.
3982 * @note Call saveSettings() after calling this function to commit the change.
3984 * @return bool
3986 public function confirmEmail() {
3987 // Check if it's already confirmed, so we don't touch the database
3988 // and fire the ConfirmEmailComplete hook on redundant confirmations.
3989 if ( !$this->isEmailConfirmed() ) {
3990 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3991 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3993 return true;
3997 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3998 * address if it was already confirmed.
4000 * @note Call saveSettings() after calling this function to commit the change.
4001 * @return bool Returns true
4003 public function invalidateEmail() {
4004 $this->load();
4005 $this->mEmailToken = null;
4006 $this->mEmailTokenExpires = null;
4007 $this->setEmailAuthenticationTimestamp( null );
4008 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
4009 return true;
4013 * Set the e-mail authentication timestamp.
4014 * @param string $timestamp TS_MW timestamp
4016 public function setEmailAuthenticationTimestamp( $timestamp ) {
4017 $this->load();
4018 $this->mEmailAuthenticated = $timestamp;
4019 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
4023 * Is this user allowed to send e-mails within limits of current
4024 * site configuration?
4025 * @return bool
4027 public function canSendEmail() {
4028 global $wgEnableEmail, $wgEnableUserEmail;
4029 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4030 return false;
4032 $canSend = $this->isEmailConfirmed();
4033 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
4034 return $canSend;
4038 * Is this user allowed to receive e-mails within limits of current
4039 * site configuration?
4040 * @return bool
4042 public function canReceiveEmail() {
4043 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4047 * Is this user's e-mail address valid-looking and confirmed within
4048 * limits of the current site configuration?
4050 * @note If $wgEmailAuthentication is on, this may require the user to have
4051 * confirmed their address by returning a code or using a password
4052 * sent to the address from the wiki.
4054 * @return bool
4056 public function isEmailConfirmed() {
4057 global $wgEmailAuthentication;
4058 $this->load();
4059 $confirmed = true;
4060 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4061 if ( $this->isAnon() ) {
4062 return false;
4064 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4065 return false;
4067 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4068 return false;
4070 return true;
4071 } else {
4072 return $confirmed;
4077 * Check whether there is an outstanding request for e-mail confirmation.
4078 * @return bool
4080 public function isEmailConfirmationPending() {
4081 global $wgEmailAuthentication;
4082 return $wgEmailAuthentication &&
4083 !$this->isEmailConfirmed() &&
4084 $this->mEmailToken &&
4085 $this->mEmailTokenExpires > wfTimestamp();
4089 * Get the timestamp of account creation.
4091 * @return string|bool|null Timestamp of account creation, false for
4092 * non-existent/anonymous user accounts, or null if existing account
4093 * but information is not in database.
4095 public function getRegistration() {
4096 if ( $this->isAnon() ) {
4097 return false;
4099 $this->load();
4100 return $this->mRegistration;
4104 * Get the timestamp of the first edit
4106 * @return string|bool Timestamp of first edit, or false for
4107 * non-existent/anonymous user accounts.
4109 public function getFirstEditTimestamp() {
4110 if ( $this->getId() == 0 ) {
4111 return false; // anons
4113 $dbr = wfGetDB( DB_SLAVE );
4114 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4115 array( 'rev_user' => $this->getId() ),
4116 __METHOD__,
4117 array( 'ORDER BY' => 'rev_timestamp ASC' )
4119 if ( !$time ) {
4120 return false; // no edits
4122 return wfTimestamp( TS_MW, $time );
4126 * Get the permissions associated with a given list of groups
4128 * @param array $groups Array of Strings List of internal group names
4129 * @return array Array of Strings List of permission key names for given groups combined
4131 public static function getGroupPermissions( $groups ) {
4132 global $wgGroupPermissions, $wgRevokePermissions;
4133 $rights = array();
4134 // grant every granted permission first
4135 foreach ( $groups as $group ) {
4136 if ( isset( $wgGroupPermissions[$group] ) ) {
4137 $rights = array_merge( $rights,
4138 // array_filter removes empty items
4139 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4142 // now revoke the revoked permissions
4143 foreach ( $groups as $group ) {
4144 if ( isset( $wgRevokePermissions[$group] ) ) {
4145 $rights = array_diff( $rights,
4146 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4149 return array_unique( $rights );
4153 * Get all the groups who have a given permission
4155 * @param string $role Role to check
4156 * @return array Array of Strings List of internal group names with the given permission
4158 public static function getGroupsWithPermission( $role ) {
4159 global $wgGroupPermissions;
4160 $allowedGroups = array();
4161 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4162 if ( self::groupHasPermission( $group, $role ) ) {
4163 $allowedGroups[] = $group;
4166 return $allowedGroups;
4170 * Check, if the given group has the given permission
4172 * If you're wanting to check whether all users have a permission, use
4173 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4174 * from anyone.
4176 * @since 1.21
4177 * @param string $group Group to check
4178 * @param string $role Role to check
4179 * @return bool
4181 public static function groupHasPermission( $group, $role ) {
4182 global $wgGroupPermissions, $wgRevokePermissions;
4183 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4184 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4188 * Check if all users have the given permission
4190 * @since 1.22
4191 * @param string $right Right to check
4192 * @return bool
4194 public static function isEveryoneAllowed( $right ) {
4195 global $wgGroupPermissions, $wgRevokePermissions;
4196 static $cache = array();
4198 // Use the cached results, except in unit tests which rely on
4199 // being able change the permission mid-request
4200 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4201 return $cache[$right];
4204 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
4205 $cache[$right] = false;
4206 return false;
4209 // If it's revoked anywhere, then everyone doesn't have it
4210 foreach ( $wgRevokePermissions as $rights ) {
4211 if ( isset( $rights[$right] ) && $rights[$right] ) {
4212 $cache[$right] = false;
4213 return false;
4217 // Allow extensions (e.g. OAuth) to say false
4218 if ( !wfRunHooks( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4219 $cache[$right] = false;
4220 return false;
4223 $cache[$right] = true;
4224 return true;
4228 * Get the localized descriptive name for a group, if it exists
4230 * @param string $group Internal group name
4231 * @return string Localized descriptive group name
4233 public static function getGroupName( $group ) {
4234 $msg = wfMessage( "group-$group" );
4235 return $msg->isBlank() ? $group : $msg->text();
4239 * Get the localized descriptive name for a member of a group, if it exists
4241 * @param string $group Internal group name
4242 * @param string $username Username for gender (since 1.19)
4243 * @return string Localized name for group member
4245 public static function getGroupMember( $group, $username = '#' ) {
4246 $msg = wfMessage( "group-$group-member", $username );
4247 return $msg->isBlank() ? $group : $msg->text();
4251 * Return the set of defined explicit groups.
4252 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4253 * are not included, as they are defined automatically, not in the database.
4254 * @return array Array of internal group names
4256 public static function getAllGroups() {
4257 global $wgGroupPermissions, $wgRevokePermissions;
4258 return array_diff(
4259 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4260 self::getImplicitGroups()
4265 * Get a list of all available permissions.
4266 * @return array Array of permission names
4268 public static function getAllRights() {
4269 if ( self::$mAllRights === false ) {
4270 global $wgAvailableRights;
4271 if ( count( $wgAvailableRights ) ) {
4272 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
4273 } else {
4274 self::$mAllRights = self::$mCoreRights;
4276 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
4278 return self::$mAllRights;
4282 * Get a list of implicit groups
4283 * @return array Array of Strings Array of internal group names
4285 public static function getImplicitGroups() {
4286 global $wgImplicitGroups;
4287 $groups = $wgImplicitGroups;
4288 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
4289 return $groups;
4293 * Get the title of a page describing a particular group
4295 * @param string $group Internal group name
4296 * @return Title|bool Title of the page if it exists, false otherwise
4298 public static function getGroupPage( $group ) {
4299 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4300 if ( $msg->exists() ) {
4301 $title = Title::newFromText( $msg->text() );
4302 if ( is_object( $title ) ) {
4303 return $title;
4306 return false;
4310 * Create a link to the group in HTML, if available;
4311 * else return the group name.
4313 * @param string $group Internal name of the group
4314 * @param string $text The text of the link
4315 * @return string HTML link to the group
4317 public static function makeGroupLinkHTML( $group, $text = '' ) {
4318 if ( $text == '' ) {
4319 $text = self::getGroupName( $group );
4321 $title = self::getGroupPage( $group );
4322 if ( $title ) {
4323 return Linker::link( $title, htmlspecialchars( $text ) );
4324 } else {
4325 return $text;
4330 * Create a link to the group in Wikitext, if available;
4331 * else return the group name.
4333 * @param string $group Internal name of the group
4334 * @param string $text The text of the link
4335 * @return string Wikilink to the group
4337 public static function makeGroupLinkWiki( $group, $text = '' ) {
4338 if ( $text == '' ) {
4339 $text = self::getGroupName( $group );
4341 $title = self::getGroupPage( $group );
4342 if ( $title ) {
4343 $page = $title->getPrefixedText();
4344 return "[[$page|$text]]";
4345 } else {
4346 return $text;
4351 * Returns an array of the groups that a particular group can add/remove.
4353 * @param string $group The group to check for whether it can add/remove
4354 * @return array array( 'add' => array( addablegroups ),
4355 * 'remove' => array( removablegroups ),
4356 * 'add-self' => array( addablegroups to self),
4357 * 'remove-self' => array( removable groups from self) )
4359 public static function changeableByGroup( $group ) {
4360 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4362 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
4363 if ( empty( $wgAddGroups[$group] ) ) {
4364 // Don't add anything to $groups
4365 } elseif ( $wgAddGroups[$group] === true ) {
4366 // You get everything
4367 $groups['add'] = self::getAllGroups();
4368 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4369 $groups['add'] = $wgAddGroups[$group];
4372 // Same thing for remove
4373 if ( empty( $wgRemoveGroups[$group] ) ) {
4374 } elseif ( $wgRemoveGroups[$group] === true ) {
4375 $groups['remove'] = self::getAllGroups();
4376 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4377 $groups['remove'] = $wgRemoveGroups[$group];
4380 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4381 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4382 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4383 if ( is_int( $key ) ) {
4384 $wgGroupsAddToSelf['user'][] = $value;
4389 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4390 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4391 if ( is_int( $key ) ) {
4392 $wgGroupsRemoveFromSelf['user'][] = $value;
4397 // Now figure out what groups the user can add to him/herself
4398 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4399 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4400 // No idea WHY this would be used, but it's there
4401 $groups['add-self'] = User::getAllGroups();
4402 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4403 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4406 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4407 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4408 $groups['remove-self'] = User::getAllGroups();
4409 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4410 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4413 return $groups;
4417 * Returns an array of groups that this user can add and remove
4418 * @return array array( 'add' => array( addablegroups ),
4419 * 'remove' => array( removablegroups ),
4420 * 'add-self' => array( addablegroups to self),
4421 * 'remove-self' => array( removable groups from self) )
4423 public function changeableGroups() {
4424 if ( $this->isAllowed( 'userrights' ) ) {
4425 // This group gives the right to modify everything (reverse-
4426 // compatibility with old "userrights lets you change
4427 // everything")
4428 // Using array_merge to make the groups reindexed
4429 $all = array_merge( User::getAllGroups() );
4430 return array(
4431 'add' => $all,
4432 'remove' => $all,
4433 'add-self' => array(),
4434 'remove-self' => array()
4438 // Okay, it's not so simple, we will have to go through the arrays
4439 $groups = array(
4440 'add' => array(),
4441 'remove' => array(),
4442 'add-self' => array(),
4443 'remove-self' => array()
4445 $addergroups = $this->getEffectiveGroups();
4447 foreach ( $addergroups as $addergroup ) {
4448 $groups = array_merge_recursive(
4449 $groups, $this->changeableByGroup( $addergroup )
4451 $groups['add'] = array_unique( $groups['add'] );
4452 $groups['remove'] = array_unique( $groups['remove'] );
4453 $groups['add-self'] = array_unique( $groups['add-self'] );
4454 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4456 return $groups;
4460 * Increment the user's edit-count field.
4461 * Will have no effect for anonymous users.
4463 public function incEditCount() {
4464 if ( !$this->isAnon() ) {
4465 $dbw = wfGetDB( DB_MASTER );
4466 $dbw->update(
4467 'user',
4468 array( 'user_editcount=user_editcount+1' ),
4469 array( 'user_id' => $this->getId() ),
4470 __METHOD__
4473 // Lazy initialization check...
4474 if ( $dbw->affectedRows() == 0 ) {
4475 // Now here's a goddamn hack...
4476 $dbr = wfGetDB( DB_SLAVE );
4477 if ( $dbr !== $dbw ) {
4478 // If we actually have a slave server, the count is
4479 // at least one behind because the current transaction
4480 // has not been committed and replicated.
4481 $this->initEditCount( 1 );
4482 } else {
4483 // But if DB_SLAVE is selecting the master, then the
4484 // count we just read includes the revision that was
4485 // just added in the working transaction.
4486 $this->initEditCount();
4490 // edit count in user cache too
4491 $this->invalidateCache();
4495 * Initialize user_editcount from data out of the revision table
4497 * @param int $add Edits to add to the count from the revision table
4498 * @return int Number of edits
4500 protected function initEditCount( $add = 0 ) {
4501 // Pull from a slave to be less cruel to servers
4502 // Accuracy isn't the point anyway here
4503 $dbr = wfGetDB( DB_SLAVE );
4504 $count = (int)$dbr->selectField(
4505 'revision',
4506 'COUNT(rev_user)',
4507 array( 'rev_user' => $this->getId() ),
4508 __METHOD__
4510 $count = $count + $add;
4512 $dbw = wfGetDB( DB_MASTER );
4513 $dbw->update(
4514 'user',
4515 array( 'user_editcount' => $count ),
4516 array( 'user_id' => $this->getId() ),
4517 __METHOD__
4520 return $count;
4524 * Get the description of a given right
4526 * @param string $right Right to query
4527 * @return string Localized description of the right
4529 public static function getRightDescription( $right ) {
4530 $key = "right-$right";
4531 $msg = wfMessage( $key );
4532 return $msg->isBlank() ? $right : $msg->text();
4536 * Make an old-style password hash
4538 * @param string $password Plain-text password
4539 * @param string $userId User ID
4540 * @return string Password hash
4542 public static function oldCrypt( $password, $userId ) {
4543 global $wgPasswordSalt;
4544 if ( $wgPasswordSalt ) {
4545 return md5( $userId . '-' . md5( $password ) );
4546 } else {
4547 return md5( $password );
4552 * Make a new-style password hash
4554 * @param string $password Plain-text password
4555 * @param bool|string $salt Optional salt, may be random or the user ID.
4556 * If unspecified or false, will generate one automatically
4557 * @return string Password hash
4559 public static function crypt( $password, $salt = false ) {
4560 global $wgPasswordSalt;
4562 $hash = '';
4563 if ( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
4564 return $hash;
4567 if ( $wgPasswordSalt ) {
4568 if ( $salt === false ) {
4569 $salt = MWCryptRand::generateHex( 8 );
4571 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
4572 } else {
4573 return ':A:' . md5( $password );
4578 * Compare a password hash with a plain-text password. Requires the user
4579 * ID if there's a chance that the hash is an old-style hash.
4581 * @param string $hash Password hash
4582 * @param string $password Plain-text password to compare
4583 * @param string|bool $userId User ID for old-style password salt
4585 * @return bool
4587 public static function comparePasswords( $hash, $password, $userId = false ) {
4588 $type = substr( $hash, 0, 3 );
4590 $result = false;
4591 if ( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
4592 return $result;
4595 if ( $type == ':A:' ) {
4596 // Unsalted
4597 return md5( $password ) === substr( $hash, 3 );
4598 } elseif ( $type == ':B:' ) {
4599 // Salted
4600 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
4601 return md5( $salt . '-' . md5( $password ) ) === $realHash;
4602 } else {
4603 // Old-style
4604 return self::oldCrypt( $password, $userId ) === $hash;
4609 * Add a newuser log entry for this user.
4610 * Before 1.19 the return value was always true.
4612 * @param string|bool $action Account creation type.
4613 * - String, one of the following values:
4614 * - 'create' for an anonymous user creating an account for himself.
4615 * This will force the action's performer to be the created user itself,
4616 * no matter the value of $wgUser
4617 * - 'create2' for a logged in user creating an account for someone else
4618 * - 'byemail' when the created user will receive its password by e-mail
4619 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4620 * - Boolean means whether the account was created by e-mail (deprecated):
4621 * - true will be converted to 'byemail'
4622 * - false will be converted to 'create' if this object is the same as
4623 * $wgUser and to 'create2' otherwise
4625 * @param string $reason User supplied reason
4627 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4629 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4630 global $wgUser, $wgNewUserLog;
4631 if ( empty( $wgNewUserLog ) ) {
4632 return true; // disabled
4635 if ( $action === true ) {
4636 $action = 'byemail';
4637 } elseif ( $action === false ) {
4638 if ( $this->getName() == $wgUser->getName() ) {
4639 $action = 'create';
4640 } else {
4641 $action = 'create2';
4645 if ( $action === 'create' || $action === 'autocreate' ) {
4646 $performer = $this;
4647 } else {
4648 $performer = $wgUser;
4651 $logEntry = new ManualLogEntry( 'newusers', $action );
4652 $logEntry->setPerformer( $performer );
4653 $logEntry->setTarget( $this->getUserPage() );
4654 $logEntry->setComment( $reason );
4655 $logEntry->setParameters( array(
4656 '4::userid' => $this->getId(),
4657 ) );
4658 $logid = $logEntry->insert();
4660 if ( $action !== 'autocreate' ) {
4661 $logEntry->publish( $logid );
4664 return (int)$logid;
4668 * Add an autocreate newuser log entry for this user
4669 * Used by things like CentralAuth and perhaps other authplugins.
4670 * Consider calling addNewUserLogEntry() directly instead.
4672 * @return bool
4674 public function addNewUserLogEntryAutoCreate() {
4675 $this->addNewUserLogEntry( 'autocreate' );
4677 return true;
4681 * Load the user options either from cache, the database or an array
4683 * @param array $data Rows for the current user out of the user_properties table
4685 protected function loadOptions( $data = null ) {
4686 global $wgContLang;
4688 $this->load();
4690 if ( $this->mOptionsLoaded ) {
4691 return;
4694 $this->mOptions = self::getDefaultOptions();
4696 if ( !$this->getId() ) {
4697 // For unlogged-in users, load language/variant options from request.
4698 // There's no need to do it for logged-in users: they can set preferences,
4699 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4700 // so don't override user's choice (especially when the user chooses site default).
4701 $variant = $wgContLang->getDefaultVariant();
4702 $this->mOptions['variant'] = $variant;
4703 $this->mOptions['language'] = $variant;
4704 $this->mOptionsLoaded = true;
4705 return;
4708 // Maybe load from the object
4709 if ( !is_null( $this->mOptionOverrides ) ) {
4710 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4711 foreach ( $this->mOptionOverrides as $key => $value ) {
4712 $this->mOptions[$key] = $value;
4714 } else {
4715 if ( !is_array( $data ) ) {
4716 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4717 // Load from database
4718 $dbr = wfGetDB( DB_SLAVE );
4720 $res = $dbr->select(
4721 'user_properties',
4722 array( 'up_property', 'up_value' ),
4723 array( 'up_user' => $this->getId() ),
4724 __METHOD__
4727 $this->mOptionOverrides = array();
4728 $data = array();
4729 foreach ( $res as $row ) {
4730 $data[$row->up_property] = $row->up_value;
4733 foreach ( $data as $property => $value ) {
4734 $this->mOptionOverrides[$property] = $value;
4735 $this->mOptions[$property] = $value;
4739 $this->mOptionsLoaded = true;
4741 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
4745 * @todo document
4747 protected function saveOptions() {
4748 $this->loadOptions();
4750 // Not using getOptions(), to keep hidden preferences in database
4751 $saveOptions = $this->mOptions;
4753 // Allow hooks to abort, for instance to save to a global profile.
4754 // Reset options to default state before saving.
4755 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4756 return;
4759 $userId = $this->getId();
4760 $insert_rows = array();
4761 foreach ( $saveOptions as $key => $value ) {
4762 // Don't bother storing default values
4763 $defaultOption = self::getDefaultOption( $key );
4764 if ( ( is_null( $defaultOption ) &&
4765 !( $value === false || is_null( $value ) ) ) ||
4766 $value != $defaultOption
4768 $insert_rows[] = array(
4769 'up_user' => $userId,
4770 'up_property' => $key,
4771 'up_value' => $value,
4776 $dbw = wfGetDB( DB_MASTER );
4777 // Find and delete any prior preference rows...
4778 $res = $dbw->select( 'user_properties',
4779 array( 'up_property' ), array( 'up_user' => $userId ), __METHOD__ );
4780 $priorKeys = array();
4781 foreach ( $res as $row ) {
4782 $priorKeys[] = $row->up_property;
4784 if ( count( $priorKeys ) ) {
4785 // Do the DELETE by PRIMARY KEY for prior rows.
4786 // In the past a very large portion of calls to this function are for setting
4787 // 'rememberpassword' for new accounts (a preference that has since been removed).
4788 // Doing a blanket per-user DELETE for new accounts with no rows in the table
4789 // caused gap locks on [max user ID,+infinity) which caused high contention since
4790 // updates would pile up on each other as they are for higher (newer) user IDs.
4791 // It might not be necessary these days, but it shouldn't hurt either.
4792 $dbw->delete( 'user_properties',
4793 array( 'up_user' => $userId, 'up_property' => $priorKeys ), __METHOD__ );
4795 // Insert the new preference rows
4796 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, array( 'IGNORE' ) );
4800 * Provide an array of HTML5 attributes to put on an input element
4801 * intended for the user to enter a new password. This may include
4802 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4804 * Do *not* use this when asking the user to enter his current password!
4805 * Regardless of configuration, users may have invalid passwords for whatever
4806 * reason (e.g., they were set before requirements were tightened up).
4807 * Only use it when asking for a new password, like on account creation or
4808 * ResetPass.
4810 * Obviously, you still need to do server-side checking.
4812 * NOTE: A combination of bugs in various browsers means that this function
4813 * actually just returns array() unconditionally at the moment. May as
4814 * well keep it around for when the browser bugs get fixed, though.
4816 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4818 * @return array Array of HTML attributes suitable for feeding to
4819 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4820 * That will get confused by the boolean attribute syntax used.)
4822 public static function passwordChangeInputAttribs() {
4823 global $wgMinimalPasswordLength;
4825 if ( $wgMinimalPasswordLength == 0 ) {
4826 return array();
4829 # Note that the pattern requirement will always be satisfied if the
4830 # input is empty, so we need required in all cases.
4832 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4833 # if e-mail confirmation is being used. Since HTML5 input validation
4834 # is b0rked anyway in some browsers, just return nothing. When it's
4835 # re-enabled, fix this code to not output required for e-mail
4836 # registration.
4837 #$ret = array( 'required' );
4838 $ret = array();
4840 # We can't actually do this right now, because Opera 9.6 will print out
4841 # the entered password visibly in its error message! When other
4842 # browsers add support for this attribute, or Opera fixes its support,
4843 # we can add support with a version check to avoid doing this on Opera
4844 # versions where it will be a problem. Reported to Opera as
4845 # DSK-262266, but they don't have a public bug tracker for us to follow.
4847 if ( $wgMinimalPasswordLength > 1 ) {
4848 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4849 $ret['title'] = wfMessage( 'passwordtooshort' )
4850 ->numParams( $wgMinimalPasswordLength )->text();
4854 return $ret;
4858 * Return the list of user fields that should be selected to create
4859 * a new user object.
4860 * @return array
4862 public static function selectFields() {
4863 return array(
4864 'user_id',
4865 'user_name',
4866 'user_real_name',
4867 'user_password',
4868 'user_newpassword',
4869 'user_newpass_time',
4870 'user_email',
4871 'user_touched',
4872 'user_token',
4873 'user_email_authenticated',
4874 'user_email_token',
4875 'user_email_token_expires',
4876 'user_password_expires',
4877 'user_registration',
4878 'user_editcount',
4883 * Factory function for fatal permission-denied errors
4885 * @since 1.22
4886 * @param string $permission User right required
4887 * @return Status
4889 static function newFatalPermissionDeniedStatus( $permission ) {
4890 global $wgLang;
4892 $groups = array_map(
4893 array( 'User', 'makeGroupLinkWiki' ),
4894 User::getGroupsWithPermission( $permission )
4897 if ( $groups ) {
4898 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
4899 } else {
4900 return Status::newFatal( 'badaccess-group0' );