mediawiki.api: Emit warning when deprecated callback parameters are used
[mediawiki.git] / includes / User.php
blob0b28f664ade18d8853b4d3c1de326767b24f37be
1 <?php
2 /**
3 * Implements the User class for the %MediaWiki software.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
23 /**
24 * Int Number of characters in user_token field.
25 * @ingroup Constants
27 define( 'USER_TOKEN_LENGTH', 32 );
29 /**
30 * Int Serialized record version.
31 * @ingroup Constants
33 define( 'MW_USER_VERSION', 9 );
35 /**
36 * String Some punctuation to prevent editing from broken text-mangling proxies.
37 * @ingroup Constants
39 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
41 /**
42 * Thrown by User::setPassword() on error.
43 * @ingroup Exception
45 class PasswordError extends MWException {
46 // NOP
49 /**
50 * The User object encapsulates all of the user-specific settings (user_id,
51 * name, rights, password, email address, options, last login time). Client
52 * classes use the getXXX() functions to access these fields. These functions
53 * do all the work of determining whether the user is logged in,
54 * whether the requested option can be satisfied from cookies or
55 * whether a database query is needed. Most of the settings needed
56 * for rendering normal pages are set in the cookie to minimize use
57 * of the database.
59 class User {
60 /**
61 * Global constants made accessible as class constants so that autoloader
62 * magic can be used.
64 const USER_TOKEN_LENGTH = USER_TOKEN_LENGTH;
65 const MW_USER_VERSION = MW_USER_VERSION;
66 const EDIT_TOKEN_SUFFIX = EDIT_TOKEN_SUFFIX;
68 /**
69 * Maximum items in $mWatchedItems
71 const MAX_WATCHED_ITEMS_CACHE = 100;
73 /**
74 * Array of Strings List of member variables which are saved to the
75 * shared cache (memcached). Any operation which changes the
76 * corresponding database fields must call a cache-clearing function.
77 * @showinitializer
79 static $mCacheVars = array(
80 // user table
81 'mId',
82 'mName',
83 'mRealName',
84 'mPassword',
85 'mNewpassword',
86 'mNewpassTime',
87 'mEmail',
88 'mTouched',
89 'mToken',
90 'mEmailAuthenticated',
91 'mEmailToken',
92 'mEmailTokenExpires',
93 'mPasswordExpires',
94 'mRegistration',
95 'mEditCount',
96 // user_groups table
97 'mGroups',
98 // user_properties table
99 'mOptionOverrides',
103 * Array of Strings Core rights.
104 * Each of these should have a corresponding message of the form
105 * "right-$right".
106 * @showinitializer
108 static $mCoreRights = array(
109 'apihighlimits',
110 'autoconfirmed',
111 'autopatrol',
112 'bigdelete',
113 'block',
114 'blockemail',
115 'bot',
116 'browsearchive',
117 'createaccount',
118 'createpage',
119 'createtalk',
120 'delete',
121 'deletedhistory',
122 'deletedtext',
123 'deletelogentry',
124 'deleterevision',
125 'edit',
126 'editinterface',
127 'editprotected',
128 'editmyoptions',
129 'editmyprivateinfo',
130 'editmyusercss',
131 'editmyuserjs',
132 'editmywatchlist',
133 'editsemiprotected',
134 'editusercssjs', #deprecated
135 'editusercss',
136 'edituserjs',
137 'hideuser',
138 'import',
139 'importupload',
140 'ipblock-exempt',
141 'markbotedits',
142 'mergehistory',
143 'minoredit',
144 'move',
145 'movefile',
146 'move-rootuserpages',
147 'move-subpages',
148 'nominornewtalk',
149 'noratelimit',
150 'override-export-depth',
151 'passwordreset',
152 'patrol',
153 'patrolmarks',
154 'protect',
155 'proxyunbannable',
156 'purge',
157 'read',
158 'reupload',
159 'reupload-own',
160 'reupload-shared',
161 'rollback',
162 'sendemail',
163 'siteadmin',
164 'suppressionlog',
165 'suppressredirect',
166 'suppressrevision',
167 'unblockself',
168 'undelete',
169 'unwatchedpages',
170 'upload',
171 'upload_by_url',
172 'userrights',
173 'userrights-interwiki',
174 'viewmyprivateinfo',
175 'viewmywatchlist',
176 'writeapi',
179 * String Cached results of getAllRights()
181 static $mAllRights = false;
183 /** @name Cache variables */
184 //@{
185 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
186 $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
187 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mEditCount,
188 $mGroups, $mOptionOverrides;
190 protected $mPasswordExpires;
191 //@}
194 * Bool Whether the cache variables have been loaded.
196 //@{
197 var $mOptionsLoaded;
200 * Array with already loaded items or true if all items have been loaded.
202 private $mLoadedItems = array();
203 //@}
206 * String Initialization data source if mLoadedItems!==true. May be one of:
207 * - 'defaults' anonymous user initialised from class defaults
208 * - 'name' initialise from mName
209 * - 'id' initialise from mId
210 * - 'session' log in from cookies or session if possible
212 * Use the User::newFrom*() family of functions to set this.
214 var $mFrom;
217 * Lazy-initialized variables, invalidated with clearInstanceCache
219 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mRights,
220 $mBlockreason, $mEffectiveGroups, $mImplicitGroups, $mFormerGroups, $mBlockedGlobally,
221 $mLocked, $mHideName, $mOptions;
224 * @var WebRequest
226 private $mRequest;
229 * @var Block
231 var $mBlock;
234 * @var bool
236 var $mAllowUsertalk;
239 * @var Block
241 private $mBlockedFromCreateAccount = false;
244 * @var Array
246 private $mWatchedItems = array();
248 static $idCacheByName = array();
251 * Lightweight constructor for an anonymous user.
252 * Use the User::newFrom* factory functions for other kinds of users.
254 * @see newFromName()
255 * @see newFromId()
256 * @see newFromConfirmationCode()
257 * @see newFromSession()
258 * @see newFromRow()
260 public function __construct() {
261 $this->clearInstanceCache( 'defaults' );
265 * @return string
267 public function __toString() {
268 return $this->getName();
272 * Load the user table data for this object from the source given by mFrom.
274 public function load() {
275 if ( $this->mLoadedItems === true ) {
276 return;
278 wfProfileIn( __METHOD__ );
280 // Set it now to avoid infinite recursion in accessors
281 $this->mLoadedItems = true;
283 switch ( $this->mFrom ) {
284 case 'defaults':
285 $this->loadDefaults();
286 break;
287 case 'name':
288 $this->mId = self::idFromName( $this->mName );
289 if ( !$this->mId ) {
290 // Nonexistent user placeholder object
291 $this->loadDefaults( $this->mName );
292 } else {
293 $this->loadFromId();
295 break;
296 case 'id':
297 $this->loadFromId();
298 break;
299 case 'session':
300 if ( !$this->loadFromSession() ) {
301 // Loading from session failed. Load defaults.
302 $this->loadDefaults();
304 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
305 break;
306 default:
307 wfProfileOut( __METHOD__ );
308 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
310 wfProfileOut( __METHOD__ );
314 * Load user table data, given mId has already been set.
315 * @return bool false if the ID does not exist, true otherwise
317 public function loadFromId() {
318 global $wgMemc;
319 if ( $this->mId == 0 ) {
320 $this->loadDefaults();
321 return false;
324 // Try cache
325 $key = wfMemcKey( 'user', 'id', $this->mId );
326 $data = $wgMemc->get( $key );
327 if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
328 // Object is expired, load from DB
329 $data = false;
332 if ( !$data ) {
333 wfDebug( "User: cache miss for user {$this->mId}\n" );
334 // Load from DB
335 if ( !$this->loadFromDatabase() ) {
336 // Can't load from ID, user is anonymous
337 return false;
339 $this->saveToCache();
340 } else {
341 wfDebug( "User: got user {$this->mId} from cache\n" );
342 // Restore from cache
343 foreach ( self::$mCacheVars as $name ) {
344 $this->$name = $data[$name];
348 $this->mLoadedItems = true;
350 return true;
354 * Save user data to the shared cache
356 public function saveToCache() {
357 $this->load();
358 $this->loadGroups();
359 $this->loadOptions();
360 if ( $this->isAnon() ) {
361 // Anonymous users are uncached
362 return;
364 $data = array();
365 foreach ( self::$mCacheVars as $name ) {
366 $data[$name] = $this->$name;
368 $data['mVersion'] = MW_USER_VERSION;
369 $key = wfMemcKey( 'user', 'id', $this->mId );
370 global $wgMemc;
371 $wgMemc->set( $key, $data );
374 /** @name newFrom*() static factory methods */
375 //@{
378 * Static factory method for creation from username.
380 * This is slightly less efficient than newFromId(), so use newFromId() if
381 * you have both an ID and a name handy.
383 * @param string $name Username, validated by Title::newFromText()
384 * @param string|bool $validate Validate username. Takes the same parameters as
385 * User::getCanonicalName(), except that true is accepted as an alias
386 * for 'valid', for BC.
388 * @return User|bool User object, or false if the username is invalid
389 * (e.g. if it contains illegal characters or is an IP address). If the
390 * username is not present in the database, the result will be a user object
391 * with a name, zero user ID and default settings.
393 public static function newFromName( $name, $validate = 'valid' ) {
394 if ( $validate === true ) {
395 $validate = 'valid';
397 $name = self::getCanonicalName( $name, $validate );
398 if ( $name === false ) {
399 return false;
400 } else {
401 // Create unloaded user object
402 $u = new User;
403 $u->mName = $name;
404 $u->mFrom = 'name';
405 $u->setItemLoaded( 'name' );
406 return $u;
411 * Static factory method for creation from a given user ID.
413 * @param int $id Valid user ID
414 * @return User The corresponding User object
416 public static function newFromId( $id ) {
417 $u = new User;
418 $u->mId = $id;
419 $u->mFrom = 'id';
420 $u->setItemLoaded( 'id' );
421 return $u;
425 * Factory method to fetch whichever user has a given email confirmation code.
426 * This code is generated when an account is created or its e-mail address
427 * has changed.
429 * If the code is invalid or has expired, returns NULL.
431 * @param string $code Confirmation code
432 * @return User|null
434 public static function newFromConfirmationCode( $code ) {
435 $dbr = wfGetDB( DB_SLAVE );
436 $id = $dbr->selectField( 'user', 'user_id', array(
437 'user_email_token' => md5( $code ),
438 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
439 ) );
440 if ( $id !== false ) {
441 return User::newFromId( $id );
442 } else {
443 return null;
448 * Create a new user object using data from session or cookies. If the
449 * login credentials are invalid, the result is an anonymous user.
451 * @param WebRequest $request Object to use; $wgRequest will be used if omitted.
452 * @return User object
454 public static function newFromSession( WebRequest $request = null ) {
455 $user = new User;
456 $user->mFrom = 'session';
457 $user->mRequest = $request;
458 return $user;
462 * Create a new user object from a user row.
463 * The row should have the following fields from the user table in it:
464 * - either user_name or user_id to load further data if needed (or both)
465 * - user_real_name
466 * - all other fields (email, password, etc.)
467 * It is useless to provide the remaining fields if either user_id,
468 * user_name and user_real_name are not provided because the whole row
469 * will be loaded once more from the database when accessing them.
471 * @param stdClass $row A row from the user table
472 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
473 * @return User
475 public static function newFromRow( $row, $data = null ) {
476 $user = new User;
477 $user->loadFromRow( $row, $data );
478 return $user;
481 //@}
484 * Get the username corresponding to a given user ID
485 * @param int $id User ID
486 * @return string|bool The corresponding username
488 public static function whoIs( $id ) {
489 return UserCache::singleton()->getProp( $id, 'name' );
493 * Get the real name of a user given their user ID
495 * @param int $id User ID
496 * @return string|bool The corresponding user's real name
498 public static function whoIsReal( $id ) {
499 return UserCache::singleton()->getProp( $id, 'real_name' );
503 * Get database id given a user name
504 * @param string $name Username
505 * @return int|null The corresponding user's ID, or null if user is nonexistent
507 public static function idFromName( $name ) {
508 $nt = Title::makeTitleSafe( NS_USER, $name );
509 if ( is_null( $nt ) ) {
510 // Illegal name
511 return null;
514 if ( isset( self::$idCacheByName[$name] ) ) {
515 return self::$idCacheByName[$name];
518 $dbr = wfGetDB( DB_SLAVE );
519 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
521 if ( $s === false ) {
522 $result = null;
523 } else {
524 $result = $s->user_id;
527 self::$idCacheByName[$name] = $result;
529 if ( count( self::$idCacheByName ) > 1000 ) {
530 self::$idCacheByName = array();
533 return $result;
537 * Reset the cache used in idFromName(). For use in tests.
539 public static function resetIdByNameCache() {
540 self::$idCacheByName = array();
544 * Does the string match an anonymous IPv4 address?
546 * This function exists for username validation, in order to reject
547 * usernames which are similar in form to IP addresses. Strings such
548 * as 300.300.300.300 will return true because it looks like an IP
549 * address, despite not being strictly valid.
551 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
552 * address because the usemod software would "cloak" anonymous IP
553 * addresses like this, if we allowed accounts like this to be created
554 * new users could get the old edits of these anonymous users.
556 * @param string $name Name to match
557 * @return bool
559 public static function isIP( $name ) {
560 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name ) || IP::isIPv6( $name );
564 * Is the input a valid username?
566 * Checks if the input is a valid username, we don't want an empty string,
567 * an IP address, anything that contains slashes (would mess up subpages),
568 * is longer than the maximum allowed username size or doesn't begin with
569 * a capital letter.
571 * @param string $name Name to match
572 * @return bool
574 public static function isValidUserName( $name ) {
575 global $wgContLang, $wgMaxNameChars;
577 if ( $name == ''
578 || User::isIP( $name )
579 || strpos( $name, '/' ) !== false
580 || strlen( $name ) > $wgMaxNameChars
581 || $name != $wgContLang->ucfirst( $name ) ) {
582 wfDebugLog( 'username', __METHOD__ .
583 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
584 return false;
587 // Ensure that the name can't be misresolved as a different title,
588 // such as with extra namespace keys at the start.
589 $parsed = Title::newFromText( $name );
590 if ( is_null( $parsed )
591 || $parsed->getNamespace()
592 || strcmp( $name, $parsed->getPrefixedText() ) ) {
593 wfDebugLog( 'username', __METHOD__ .
594 ": '$name' invalid due to ambiguous prefixes" );
595 return false;
598 // Check an additional blacklist of troublemaker characters.
599 // Should these be merged into the title char list?
600 $unicodeBlacklist = '/[' .
601 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
602 '\x{00a0}' . # non-breaking space
603 '\x{2000}-\x{200f}' . # various whitespace
604 '\x{2028}-\x{202f}' . # breaks and control chars
605 '\x{3000}' . # ideographic space
606 '\x{e000}-\x{f8ff}' . # private use
607 ']/u';
608 if ( preg_match( $unicodeBlacklist, $name ) ) {
609 wfDebugLog( 'username', __METHOD__ .
610 ": '$name' invalid due to blacklisted characters" );
611 return false;
614 return true;
618 * Usernames which fail to pass this function will be blocked
619 * from user login and new account registrations, but may be used
620 * internally by batch processes.
622 * If an account already exists in this form, login will be blocked
623 * by a failure to pass this function.
625 * @param string $name Name to match
626 * @return bool
628 public static function isUsableName( $name ) {
629 global $wgReservedUsernames;
630 // Must be a valid username, obviously ;)
631 if ( !self::isValidUserName( $name ) ) {
632 return false;
635 static $reservedUsernames = false;
636 if ( !$reservedUsernames ) {
637 $reservedUsernames = $wgReservedUsernames;
638 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
641 // Certain names may be reserved for batch processes.
642 foreach ( $reservedUsernames as $reserved ) {
643 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
644 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
646 if ( $reserved == $name ) {
647 return false;
650 return true;
654 * Usernames which fail to pass this function will be blocked
655 * from new account registrations, but may be used internally
656 * either by batch processes or by user accounts which have
657 * already been created.
659 * Additional blacklisting may be added here rather than in
660 * isValidUserName() to avoid disrupting existing accounts.
662 * @param string $name to match
663 * @return bool
665 public static function isCreatableName( $name ) {
666 global $wgInvalidUsernameCharacters;
668 // Ensure that the username isn't longer than 235 bytes, so that
669 // (at least for the builtin skins) user javascript and css files
670 // will work. (bug 23080)
671 if ( strlen( $name ) > 235 ) {
672 wfDebugLog( 'username', __METHOD__ .
673 ": '$name' invalid due to length" );
674 return false;
677 // Preg yells if you try to give it an empty string
678 if ( $wgInvalidUsernameCharacters !== '' ) {
679 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
680 wfDebugLog( 'username', __METHOD__ .
681 ": '$name' invalid due to wgInvalidUsernameCharacters" );
682 return false;
686 return self::isUsableName( $name );
690 * Is the input a valid password for this user?
692 * @param string $password Desired password
693 * @return bool
695 public function isValidPassword( $password ) {
696 //simple boolean wrapper for getPasswordValidity
697 return $this->getPasswordValidity( $password ) === true;
701 * Given unvalidated password input, return error message on failure.
703 * @param string $password Desired password
704 * @return mixed: true on success, string or array of error message on failure
706 public function getPasswordValidity( $password ) {
707 global $wgMinimalPasswordLength, $wgContLang;
709 static $blockedLogins = array(
710 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
711 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
714 $result = false; //init $result to false for the internal checks
716 if ( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) ) {
717 return $result;
720 if ( $result === false ) {
721 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
722 return 'passwordtooshort';
723 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName ) ) {
724 return 'password-name-match';
725 } elseif ( isset( $blockedLogins[$this->getName()] ) && $password == $blockedLogins[$this->getName()] ) {
726 return 'password-login-forbidden';
727 } else {
728 //it seems weird returning true here, but this is because of the
729 //initialization of $result to false above. If the hook is never run or it
730 //doesn't modify $result, then we will likely get down into this if with
731 //a valid password.
732 return true;
734 } elseif ( $result === true ) {
735 return true;
736 } else {
737 return $result; //the isValidPassword hook set a string $result and returned true
742 * Expire a user's password
743 * @since 1.23
744 * @param $ts Mixed: optional timestamp to convert, default 0 for the current time
746 public function expirePassword( $ts = 0 ) {
747 $this->load();
748 $timestamp = wfTimestamp( TS_MW, $ts );
749 $this->mPasswordExpires = $timestamp;
750 $this->saveSettings();
754 * Clear the password expiration for a user
755 * @since 1.23
756 * @param bool $load ensure user object is loaded first
758 public function resetPasswordExpiration( $load = true ) {
759 global $wgPasswordExpirationDays;
760 if ( $load ) {
761 $this->load();
763 $newExpire = null;
764 if ( $wgPasswordExpirationDays ) {
765 $newExpire = wfTimestamp(
766 TS_MW,
767 time() + ( $wgPasswordExpirationDays * 24 * 3600 )
770 // Give extensions a chance to force an expiration
771 wfRunHooks( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
772 $this->mPasswordExpires = $newExpire;
776 * Check if the user's password is expired.
777 * TODO: Put this and password length into a PasswordPolicy object
778 * @since 1.23
779 * @return string|bool The expiration type, or false if not expired
780 * hard: A password change is required to login
781 * soft: Allow login, but encourage password change
782 * false: Password is not expired
784 public function getPasswordExpired() {
785 global $wgPasswordExpireGrace;
786 $expired = false;
787 $now = wfTimestamp();
788 $expiration = $this->getPasswordExpireDate();
789 $expUnix = wfTimestamp( TS_UNIX, $expiration );
790 if ( $expiration !== null && $expUnix < $now ) {
791 $expired = ( $expUnix + $wgPasswordExpireGrace < $now ) ? 'hard' : 'soft';
793 return $expired;
797 * Get this user's password expiration date. Since this may be using
798 * the cached User object, we assume that whatever mechanism is setting
799 * the expiration date is also expiring the User cache.
800 * @since 1.23
801 * @return string|false the datestamp of the expiration, or null if not set
803 public function getPasswordExpireDate() {
804 $this->load();
805 return $this->mPasswordExpires;
809 * Does a string look like an e-mail address?
811 * This validates an email address using an HTML5 specification found at:
812 * http://www.whatwg.org/html/states-of-the-type-attribute.html#valid-e-mail-address
813 * Which as of 2011-01-24 says:
815 * A valid e-mail address is a string that matches the ABNF production
816 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
817 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
818 * 3.5.
820 * This function is an implementation of the specification as requested in
821 * bug 22449.
823 * Client-side forms will use the same standard validation rules via JS or
824 * HTML 5 validation; additional restrictions can be enforced server-side
825 * by extensions via the 'isValidEmailAddr' hook.
827 * Note that this validation doesn't 100% match RFC 2822, but is believed
828 * to be liberal enough for wide use. Some invalid addresses will still
829 * pass validation here.
831 * @param string $addr E-mail address
832 * @return bool
833 * @deprecated since 1.18 call Sanitizer::isValidEmail() directly
835 public static function isValidEmailAddr( $addr ) {
836 wfDeprecated( __METHOD__, '1.18' );
837 return Sanitizer::validateEmail( $addr );
841 * Given unvalidated user input, return a canonical username, or false if
842 * the username is invalid.
843 * @param string $name User input
844 * @param string|bool $validate type of validation to use:
845 * - false No validation
846 * - 'valid' Valid for batch processes
847 * - 'usable' Valid for batch processes and login
848 * - 'creatable' Valid for batch processes, login and account creation
850 * @throws MWException
851 * @return bool|string
853 public static function getCanonicalName( $name, $validate = 'valid' ) {
854 // Force usernames to capital
855 global $wgContLang;
856 $name = $wgContLang->ucfirst( $name );
858 # Reject names containing '#'; these will be cleaned up
859 # with title normalisation, but then it's too late to
860 # check elsewhere
861 if ( strpos( $name, '#' ) !== false ) {
862 return false;
865 // Clean up name according to title rules
866 $t = ( $validate === 'valid' ) ?
867 Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
868 // Check for invalid titles
869 if ( is_null( $t ) ) {
870 return false;
873 // Reject various classes of invalid names
874 global $wgAuth;
875 $name = $wgAuth->getCanonicalName( $t->getText() );
877 switch ( $validate ) {
878 case false:
879 break;
880 case 'valid':
881 if ( !User::isValidUserName( $name ) ) {
882 $name = false;
884 break;
885 case 'usable':
886 if ( !User::isUsableName( $name ) ) {
887 $name = false;
889 break;
890 case 'creatable':
891 if ( !User::isCreatableName( $name ) ) {
892 $name = false;
894 break;
895 default:
896 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__ );
898 return $name;
902 * Count the number of edits of a user
904 * @param int $uid User ID to check
905 * @return int The user's edit count
907 * @deprecated since 1.21 in favour of User::getEditCount
909 public static function edits( $uid ) {
910 wfDeprecated( __METHOD__, '1.21' );
911 $user = self::newFromId( $uid );
912 return $user->getEditCount();
916 * Return a random password.
918 * @return string New random password
920 public static function randomPassword() {
921 global $wgMinimalPasswordLength;
922 // Decide the final password length based on our min password length, stopping at a minimum of 10 chars
923 $length = max( 10, $wgMinimalPasswordLength );
924 // Multiply by 1.25 to get the number of hex characters we need
925 $length = $length * 1.25;
926 // Generate random hex chars
927 $hex = MWCryptRand::generateHex( $length );
928 // Convert from base 16 to base 32 to get a proper password like string
929 return wfBaseConvert( $hex, 16, 32 );
933 * Set cached properties to default.
935 * @note This no longer clears uncached lazy-initialised properties;
936 * the constructor does that instead.
938 * @param $name string|bool
940 public function loadDefaults( $name = false ) {
941 wfProfileIn( __METHOD__ );
943 $this->mId = 0;
944 $this->mName = $name;
945 $this->mRealName = '';
946 $this->mPassword = $this->mNewpassword = '';
947 $this->mNewpassTime = null;
948 $this->mEmail = '';
949 $this->mOptionOverrides = null;
950 $this->mOptionsLoaded = false;
952 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
953 if ( $loggedOut !== null ) {
954 $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
955 } else {
956 $this->mTouched = '1'; # Allow any pages to be cached
959 $this->mToken = null; // Don't run cryptographic functions till we need a token
960 $this->mEmailAuthenticated = null;
961 $this->mEmailToken = '';
962 $this->mEmailTokenExpires = null;
963 $this->mPasswordExpires = null;
964 $this->resetPasswordExpiration( false );
965 $this->mRegistration = wfTimestamp( TS_MW );
966 $this->mGroups = array();
968 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
970 wfProfileOut( __METHOD__ );
974 * Return whether an item has been loaded.
976 * @param string $item item to check. Current possibilities:
977 * - id
978 * - name
979 * - realname
980 * @param string $all 'all' to check if the whole object has been loaded
981 * or any other string to check if only the item is available (e.g.
982 * for optimisation)
983 * @return boolean
985 public function isItemLoaded( $item, $all = 'all' ) {
986 return ( $this->mLoadedItems === true && $all === 'all' ) ||
987 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
991 * Set that an item has been loaded
993 * @param string $item
995 protected function setItemLoaded( $item ) {
996 if ( is_array( $this->mLoadedItems ) ) {
997 $this->mLoadedItems[$item] = true;
1002 * Load user data from the session or login cookie.
1003 * @return bool True if the user is logged in, false otherwise.
1005 private function loadFromSession() {
1006 $result = null;
1007 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
1008 if ( $result !== null ) {
1009 return $result;
1012 $request = $this->getRequest();
1014 $cookieId = $request->getCookie( 'UserID' );
1015 $sessId = $request->getSessionData( 'wsUserID' );
1017 if ( $cookieId !== null ) {
1018 $sId = intval( $cookieId );
1019 if ( $sessId !== null && $cookieId != $sessId ) {
1020 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1021 cookie user ID ($sId) don't match!" );
1022 return false;
1024 $request->setSessionData( 'wsUserID', $sId );
1025 } elseif ( $sessId !== null && $sessId != 0 ) {
1026 $sId = $sessId;
1027 } else {
1028 return false;
1031 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1032 $sName = $request->getSessionData( 'wsUserName' );
1033 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1034 $sName = $request->getCookie( 'UserName' );
1035 $request->setSessionData( 'wsUserName', $sName );
1036 } else {
1037 return false;
1040 $proposedUser = User::newFromId( $sId );
1041 if ( !$proposedUser->isLoggedIn() ) {
1042 // Not a valid ID
1043 return false;
1046 global $wgBlockDisablesLogin;
1047 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1048 // User blocked and we've disabled blocked user logins
1049 return false;
1052 if ( $request->getSessionData( 'wsToken' ) ) {
1053 $passwordCorrect = ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1054 $from = 'session';
1055 } elseif ( $request->getCookie( 'Token' ) ) {
1056 # Get the token from DB/cache and clean it up to remove garbage padding.
1057 # This deals with historical problems with bugs and the default column value.
1058 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1059 // Make comparison in constant time (bug 61346)
1060 $passwordCorrect = strlen( $token ) && $this->compareSecrets( $token, $request->getCookie( 'Token' ) );
1061 $from = 'cookie';
1062 } else {
1063 // No session or persistent login cookie
1064 return false;
1067 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1068 $this->loadFromUserObject( $proposedUser );
1069 $request->setSessionData( 'wsToken', $this->mToken );
1070 wfDebug( "User: logged in from $from\n" );
1071 return true;
1072 } else {
1073 // Invalid credentials
1074 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1075 return false;
1080 * A comparison of two strings, not vulnerable to timing attacks
1081 * @param string $answer the secret string that you are comparing against.
1082 * @param string $test compare this string to the $answer.
1083 * @return bool True if the strings are the same, false otherwise
1085 protected function compareSecrets( $answer, $test ) {
1086 if ( strlen( $answer ) !== strlen( $test ) ) {
1087 $passwordCorrect = false;
1088 } else {
1089 $result = 0;
1090 for ( $i = 0; $i < strlen( $answer ); $i++ ) {
1091 $result |= ord( $answer{$i} ) ^ ord( $test{$i} );
1093 $passwordCorrect = ( $result == 0 );
1095 return $passwordCorrect;
1099 * Load user and user_group data from the database.
1100 * $this->mId must be set, this is how the user is identified.
1102 * @return bool True if the user exists, false if the user is anonymous
1104 public function loadFromDatabase() {
1105 // Paranoia
1106 $this->mId = intval( $this->mId );
1108 // Anonymous user
1109 if ( !$this->mId ) {
1110 $this->loadDefaults();
1111 return false;
1114 $dbr = wfGetDB( DB_MASTER );
1115 $s = $dbr->selectRow( 'user', self::selectFields(), array( 'user_id' => $this->mId ), __METHOD__ );
1117 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1119 if ( $s !== false ) {
1120 // Initialise user table data
1121 $this->loadFromRow( $s );
1122 $this->mGroups = null; // deferred
1123 $this->getEditCount(); // revalidation for nulls
1124 return true;
1125 } else {
1126 // Invalid user_id
1127 $this->mId = 0;
1128 $this->loadDefaults();
1129 return false;
1134 * Initialize this object from a row from the user table.
1136 * @param stdClass $row Row from the user table to load.
1137 * @param array $data Further user data to load into the object
1139 * user_groups Array with groups out of the user_groups table
1140 * user_properties Array with properties out of the user_properties table
1142 public function loadFromRow( $row, $data = null ) {
1143 $all = true;
1145 $this->mGroups = null; // deferred
1147 if ( isset( $row->user_name ) ) {
1148 $this->mName = $row->user_name;
1149 $this->mFrom = 'name';
1150 $this->setItemLoaded( 'name' );
1151 } else {
1152 $all = false;
1155 if ( isset( $row->user_real_name ) ) {
1156 $this->mRealName = $row->user_real_name;
1157 $this->setItemLoaded( 'realname' );
1158 } else {
1159 $all = false;
1162 if ( isset( $row->user_id ) ) {
1163 $this->mId = intval( $row->user_id );
1164 $this->mFrom = 'id';
1165 $this->setItemLoaded( 'id' );
1166 } else {
1167 $all = false;
1170 if ( isset( $row->user_editcount ) ) {
1171 $this->mEditCount = $row->user_editcount;
1172 } else {
1173 $all = false;
1176 if ( isset( $row->user_password ) ) {
1177 $this->mPassword = $row->user_password;
1178 $this->mNewpassword = $row->user_newpassword;
1179 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
1180 $this->mEmail = $row->user_email;
1181 if ( isset( $row->user_options ) ) {
1182 $this->decodeOptions( $row->user_options );
1184 $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1185 $this->mToken = $row->user_token;
1186 if ( $this->mToken == '' ) {
1187 $this->mToken = null;
1189 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1190 $this->mEmailToken = $row->user_email_token;
1191 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1192 $this->mPasswordExpires = wfTimestampOrNull( TS_MW, $row->user_password_expires );
1193 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1194 } else {
1195 $all = false;
1198 if ( $all ) {
1199 $this->mLoadedItems = true;
1202 if ( is_array( $data ) ) {
1203 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1204 $this->mGroups = $data['user_groups'];
1206 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1207 $this->loadOptions( $data['user_properties'] );
1213 * Load the data for this user object from another user object.
1215 * @param $user User
1217 protected function loadFromUserObject( $user ) {
1218 $user->load();
1219 $user->loadGroups();
1220 $user->loadOptions();
1221 foreach ( self::$mCacheVars as $var ) {
1222 $this->$var = $user->$var;
1227 * Load the groups from the database if they aren't already loaded.
1229 private function loadGroups() {
1230 if ( is_null( $this->mGroups ) ) {
1231 $dbr = wfGetDB( DB_MASTER );
1232 $res = $dbr->select( 'user_groups',
1233 array( 'ug_group' ),
1234 array( 'ug_user' => $this->mId ),
1235 __METHOD__ );
1236 $this->mGroups = array();
1237 foreach ( $res as $row ) {
1238 $this->mGroups[] = $row->ug_group;
1244 * Add the user to the group if he/she meets given criteria.
1246 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1247 * possible to remove manually via Special:UserRights. In such case it
1248 * will not be re-added automatically. The user will also not lose the
1249 * group if they no longer meet the criteria.
1251 * @param string $event key in $wgAutopromoteOnce (each one has groups/criteria)
1253 * @return array Array of groups the user has been promoted to.
1255 * @see $wgAutopromoteOnce
1257 public function addAutopromoteOnceGroups( $event ) {
1258 global $wgAutopromoteOnceLogInRC, $wgAuth;
1260 $toPromote = array();
1261 if ( $this->getId() ) {
1262 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1263 if ( count( $toPromote ) ) {
1264 $oldGroups = $this->getGroups(); // previous groups
1266 foreach ( $toPromote as $group ) {
1267 $this->addGroup( $group );
1269 // update groups in external authentication database
1270 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1272 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1274 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1275 $logEntry->setPerformer( $this );
1276 $logEntry->setTarget( $this->getUserPage() );
1277 $logEntry->setParameters( array(
1278 '4::oldgroups' => $oldGroups,
1279 '5::newgroups' => $newGroups,
1280 ) );
1281 $logid = $logEntry->insert();
1282 if ( $wgAutopromoteOnceLogInRC ) {
1283 $logEntry->publish( $logid );
1287 return $toPromote;
1291 * Clear various cached data stored in this object. The cache of the user table
1292 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1294 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1295 * given source. May be "name", "id", "defaults", "session", or false for
1296 * no reload.
1298 public function clearInstanceCache( $reloadFrom = false ) {
1299 $this->mNewtalk = -1;
1300 $this->mDatePreference = null;
1301 $this->mBlockedby = -1; # Unset
1302 $this->mHash = false;
1303 $this->mRights = null;
1304 $this->mEffectiveGroups = null;
1305 $this->mImplicitGroups = null;
1306 $this->mGroups = null;
1307 $this->mOptions = null;
1308 $this->mOptionsLoaded = false;
1309 $this->mEditCount = null;
1311 if ( $reloadFrom ) {
1312 $this->mLoadedItems = array();
1313 $this->mFrom = $reloadFrom;
1318 * Combine the language default options with any site-specific options
1319 * and add the default language variants.
1321 * @return Array of String options
1323 public static function getDefaultOptions() {
1324 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1326 static $defOpt = null;
1327 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1328 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1329 // mid-request and see that change reflected in the return value of this function.
1330 // Which is insane and would never happen during normal MW operation
1331 return $defOpt;
1334 $defOpt = $wgDefaultUserOptions;
1335 // Default language setting
1336 $defOpt['language'] = $wgContLang->getCode();
1337 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
1338 $defOpt[$langCode == $wgContLang->getCode() ? 'variant' : "variant-$langCode"] = $langCode;
1340 foreach ( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1341 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1343 $defOpt['skin'] = $wgDefaultSkin;
1345 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1347 return $defOpt;
1351 * Get a given default option value.
1353 * @param string $opt Name of option to retrieve
1354 * @return string Default option value
1356 public static function getDefaultOption( $opt ) {
1357 $defOpts = self::getDefaultOptions();
1358 if ( isset( $defOpts[$opt] ) ) {
1359 return $defOpts[$opt];
1360 } else {
1361 return null;
1366 * Get blocking information
1367 * @param bool $bFromSlave Whether to check the slave database first. To
1368 * improve performance, non-critical checks are done
1369 * against slaves. Check when actually saving should be
1370 * done against master.
1372 private function getBlockedStatus( $bFromSlave = true ) {
1373 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1375 if ( -1 != $this->mBlockedby ) {
1376 return;
1379 wfProfileIn( __METHOD__ );
1380 wfDebug( __METHOD__ . ": checking...\n" );
1382 // Initialize data...
1383 // Otherwise something ends up stomping on $this->mBlockedby when
1384 // things get lazy-loaded later, causing false positive block hits
1385 // due to -1 !== 0. Probably session-related... Nothing should be
1386 // overwriting mBlockedby, surely?
1387 $this->load();
1389 # We only need to worry about passing the IP address to the Block generator if the
1390 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1391 # know which IP address they're actually coming from
1392 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1393 $ip = $this->getRequest()->getIP();
1394 } else {
1395 $ip = null;
1398 // User/IP blocking
1399 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1401 // Proxy blocking
1402 if ( !$block instanceof Block && $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1403 && !in_array( $ip, $wgProxyWhitelist )
1405 // Local list
1406 if ( self::isLocallyBlockedProxy( $ip ) ) {
1407 $block = new Block;
1408 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1409 $block->mReason = wfMessage( 'proxyblockreason' )->text();
1410 $block->setTarget( $ip );
1411 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1412 $block = new Block;
1413 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1414 $block->mReason = wfMessage( 'sorbsreason' )->text();
1415 $block->setTarget( $ip );
1419 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1420 if ( !$block instanceof Block
1421 && $wgApplyIpBlocksToXff
1422 && $ip !== null
1423 && !$this->isAllowed( 'proxyunbannable' )
1424 && !in_array( $ip, $wgProxyWhitelist )
1426 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1427 $xff = array_map( 'trim', explode( ',', $xff ) );
1428 $xff = array_diff( $xff, array( $ip ) );
1429 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1430 $block = Block::chooseBlock( $xffblocks, $xff );
1431 if ( $block instanceof Block ) {
1432 # Mangle the reason to alert the user that the block
1433 # originated from matching the X-Forwarded-For header.
1434 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->text();
1438 if ( $block instanceof Block ) {
1439 wfDebug( __METHOD__ . ": Found block.\n" );
1440 $this->mBlock = $block;
1441 $this->mBlockedby = $block->getByName();
1442 $this->mBlockreason = $block->mReason;
1443 $this->mHideName = $block->mHideName;
1444 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1445 } else {
1446 $this->mBlockedby = '';
1447 $this->mHideName = 0;
1448 $this->mAllowUsertalk = false;
1451 // Extensions
1452 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1454 wfProfileOut( __METHOD__ );
1458 * Whether the given IP is in a DNS blacklist.
1460 * @param string $ip IP to check
1461 * @param bool $checkWhitelist whether to check the whitelist first
1462 * @return bool True if blacklisted.
1464 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1465 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1466 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1468 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs ) {
1469 return false;
1472 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1473 return false;
1476 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1477 return $this->inDnsBlacklist( $ip, $urls );
1481 * Whether the given IP is in a given DNS blacklist.
1483 * @param string $ip IP to check
1484 * @param string|array $bases of Strings: URL of the DNS blacklist
1485 * @return bool True if blacklisted.
1487 public function inDnsBlacklist( $ip, $bases ) {
1488 wfProfileIn( __METHOD__ );
1490 $found = false;
1491 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1492 if ( IP::isIPv4( $ip ) ) {
1493 // Reverse IP, bug 21255
1494 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1496 foreach ( (array)$bases as $base ) {
1497 // Make hostname
1498 // If we have an access key, use that too (ProjectHoneypot, etc.)
1499 if ( is_array( $base ) ) {
1500 if ( count( $base ) >= 2 ) {
1501 // Access key is 1, base URL is 0
1502 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1503 } else {
1504 $host = "$ipReversed.{$base[0]}";
1506 } else {
1507 $host = "$ipReversed.$base";
1510 // Send query
1511 $ipList = gethostbynamel( $host );
1513 if ( $ipList ) {
1514 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1515 $found = true;
1516 break;
1517 } else {
1518 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1523 wfProfileOut( __METHOD__ );
1524 return $found;
1528 * Check if an IP address is in the local proxy list
1530 * @param $ip string
1532 * @return bool
1534 public static function isLocallyBlockedProxy( $ip ) {
1535 global $wgProxyList;
1537 if ( !$wgProxyList ) {
1538 return false;
1540 wfProfileIn( __METHOD__ );
1542 if ( !is_array( $wgProxyList ) ) {
1543 // Load from the specified file
1544 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1547 if ( !is_array( $wgProxyList ) ) {
1548 $ret = false;
1549 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1550 $ret = true;
1551 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1552 // Old-style flipped proxy list
1553 $ret = true;
1554 } else {
1555 $ret = false;
1557 wfProfileOut( __METHOD__ );
1558 return $ret;
1562 * Is this user subject to rate limiting?
1564 * @return bool True if rate limited
1566 public function isPingLimitable() {
1567 global $wgRateLimitsExcludedIPs;
1568 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1569 // No other good way currently to disable rate limits
1570 // for specific IPs. :P
1571 // But this is a crappy hack and should die.
1572 return false;
1574 return !$this->isAllowed( 'noratelimit' );
1578 * Primitive rate limits: enforce maximum actions per time period
1579 * to put a brake on flooding.
1581 * @note When using a shared cache like memcached, IP-address
1582 * last-hit counters will be shared across wikis.
1584 * @param string $action Action to enforce; 'edit' if unspecified
1585 * @param integer $incrBy Positive amount to increment counter by [defaults to 1]
1586 * @return bool True if a rate limiter was tripped
1588 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1589 // Call the 'PingLimiter' hook
1590 $result = false;
1591 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1592 return $result;
1595 global $wgRateLimits;
1596 if ( !isset( $wgRateLimits[$action] ) ) {
1597 return false;
1600 // Some groups shouldn't trigger the ping limiter, ever
1601 if ( !$this->isPingLimitable() ) {
1602 return false;
1605 global $wgMemc, $wgRateLimitLog;
1606 wfProfileIn( __METHOD__ );
1608 $limits = $wgRateLimits[$action];
1609 $keys = array();
1610 $id = $this->getId();
1611 $userLimit = false;
1613 if ( isset( $limits['anon'] ) && $id == 0 ) {
1614 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1617 if ( isset( $limits['user'] ) && $id != 0 ) {
1618 $userLimit = $limits['user'];
1620 if ( $this->isNewbie() ) {
1621 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1622 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1624 if ( isset( $limits['ip'] ) ) {
1625 $ip = $this->getRequest()->getIP();
1626 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1628 if ( isset( $limits['subnet'] ) ) {
1629 $ip = $this->getRequest()->getIP();
1630 $matches = array();
1631 $subnet = false;
1632 if ( IP::isIPv6( $ip ) ) {
1633 $parts = IP::parseRange( "$ip/64" );
1634 $subnet = $parts[0];
1635 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1636 // IPv4
1637 $subnet = $matches[1];
1639 if ( $subnet !== false ) {
1640 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1644 // Check for group-specific permissions
1645 // If more than one group applies, use the group with the highest limit
1646 foreach ( $this->getGroups() as $group ) {
1647 if ( isset( $limits[$group] ) ) {
1648 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1649 $userLimit = $limits[$group];
1653 // Set the user limit key
1654 if ( $userLimit !== false ) {
1655 list( $max, $period ) = $userLimit;
1656 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
1657 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1660 $triggered = false;
1661 foreach ( $keys as $key => $limit ) {
1662 list( $max, $period ) = $limit;
1663 $summary = "(limit $max in {$period}s)";
1664 $count = $wgMemc->get( $key );
1665 // Already pinged?
1666 if ( $count ) {
1667 if ( $count >= $max ) {
1668 wfDebug( __METHOD__ . ": tripped! $key at $count $summary\n" );
1669 if ( $wgRateLimitLog ) {
1670 wfSuppressWarnings();
1671 file_put_contents( $wgRateLimitLog, wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", FILE_APPEND );
1672 wfRestoreWarnings();
1674 $triggered = true;
1675 } else {
1676 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1678 } else {
1679 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1680 if ( $incrBy > 0 ) {
1681 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1684 if ( $incrBy > 0 ) {
1685 $wgMemc->incr( $key, $incrBy );
1689 wfProfileOut( __METHOD__ );
1690 return $triggered;
1694 * Check if user is blocked
1696 * @param bool $bFromSlave Whether to check the slave database instead of the master
1697 * @return bool True if blocked, false otherwise
1699 public function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1700 return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
1704 * Get the block affecting the user, or null if the user is not blocked
1706 * @param bool $bFromSlave Whether to check the slave database instead of the master
1707 * @return Block|null
1709 public function getBlock( $bFromSlave = true ) {
1710 $this->getBlockedStatus( $bFromSlave );
1711 return $this->mBlock instanceof Block ? $this->mBlock : null;
1715 * Check if user is blocked from editing a particular article
1717 * @param Title $title Title to check
1718 * @param bool $bFromSlave whether to check the slave database instead of the master
1719 * @return bool
1721 public function isBlockedFrom( $title, $bFromSlave = false ) {
1722 global $wgBlockAllowsUTEdit;
1723 wfProfileIn( __METHOD__ );
1725 $blocked = $this->isBlocked( $bFromSlave );
1726 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1727 // If a user's name is suppressed, they cannot make edits anywhere
1728 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName()
1729 && $title->getNamespace() == NS_USER_TALK ) {
1730 $blocked = false;
1731 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1734 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1736 wfProfileOut( __METHOD__ );
1737 return $blocked;
1741 * If user is blocked, return the name of the user who placed the block
1742 * @return string Name of blocker
1744 public function blockedBy() {
1745 $this->getBlockedStatus();
1746 return $this->mBlockedby;
1750 * If user is blocked, return the specified reason for the block
1751 * @return string Blocking reason
1753 public function blockedFor() {
1754 $this->getBlockedStatus();
1755 return $this->mBlockreason;
1759 * If user is blocked, return the ID for the block
1760 * @return int Block ID
1762 public function getBlockId() {
1763 $this->getBlockedStatus();
1764 return ( $this->mBlock ? $this->mBlock->getId() : false );
1768 * Check if user is blocked on all wikis.
1769 * Do not use for actual edit permission checks!
1770 * This is intended for quick UI checks.
1772 * @param string $ip IP address, uses current client if none given
1773 * @return bool True if blocked, false otherwise
1775 public function isBlockedGlobally( $ip = '' ) {
1776 if ( $this->mBlockedGlobally !== null ) {
1777 return $this->mBlockedGlobally;
1779 // User is already an IP?
1780 if ( IP::isIPAddress( $this->getName() ) ) {
1781 $ip = $this->getName();
1782 } elseif ( !$ip ) {
1783 $ip = $this->getRequest()->getIP();
1785 $blocked = false;
1786 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1787 $this->mBlockedGlobally = (bool)$blocked;
1788 return $this->mBlockedGlobally;
1792 * Check if user account is locked
1794 * @return bool True if locked, false otherwise
1796 public function isLocked() {
1797 if ( $this->mLocked !== null ) {
1798 return $this->mLocked;
1800 global $wgAuth;
1801 StubObject::unstub( $wgAuth );
1802 $authUser = $wgAuth->getUserInstance( $this );
1803 $this->mLocked = (bool)$authUser->isLocked();
1804 return $this->mLocked;
1808 * Check if user account is hidden
1810 * @return bool True if hidden, false otherwise
1812 public function isHidden() {
1813 if ( $this->mHideName !== null ) {
1814 return $this->mHideName;
1816 $this->getBlockedStatus();
1817 if ( !$this->mHideName ) {
1818 global $wgAuth;
1819 StubObject::unstub( $wgAuth );
1820 $authUser = $wgAuth->getUserInstance( $this );
1821 $this->mHideName = (bool)$authUser->isHidden();
1823 return $this->mHideName;
1827 * Get the user's ID.
1828 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1830 public function getId() {
1831 if ( $this->mId === null && $this->mName !== null && User::isIP( $this->mName ) ) {
1832 // Special case, we know the user is anonymous
1833 return 0;
1834 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1835 // Don't load if this was initialized from an ID
1836 $this->load();
1838 return $this->mId;
1842 * Set the user and reload all fields according to a given ID
1843 * @param int $v User ID to reload
1845 public function setId( $v ) {
1846 $this->mId = $v;
1847 $this->clearInstanceCache( 'id' );
1851 * Get the user name, or the IP of an anonymous user
1852 * @return string User's name or IP address
1854 public function getName() {
1855 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1856 // Special case optimisation
1857 return $this->mName;
1858 } else {
1859 $this->load();
1860 if ( $this->mName === false ) {
1861 // Clean up IPs
1862 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
1864 return $this->mName;
1869 * Set the user name.
1871 * This does not reload fields from the database according to the given
1872 * name. Rather, it is used to create a temporary "nonexistent user" for
1873 * later addition to the database. It can also be used to set the IP
1874 * address for an anonymous user to something other than the current
1875 * remote IP.
1877 * @note User::newFromName() has roughly the same function, when the named user
1878 * does not exist.
1879 * @param string $str New user name to set
1881 public function setName( $str ) {
1882 $this->load();
1883 $this->mName = $str;
1887 * Get the user's name escaped by underscores.
1888 * @return string Username escaped by underscores.
1890 public function getTitleKey() {
1891 return str_replace( ' ', '_', $this->getName() );
1895 * Check if the user has new messages.
1896 * @return bool True if the user has new messages
1898 public function getNewtalk() {
1899 $this->load();
1901 // Load the newtalk status if it is unloaded (mNewtalk=-1)
1902 if ( $this->mNewtalk === -1 ) {
1903 $this->mNewtalk = false; # reset talk page status
1905 // Check memcached separately for anons, who have no
1906 // entire User object stored in there.
1907 if ( !$this->mId ) {
1908 global $wgDisableAnonTalk;
1909 if ( $wgDisableAnonTalk ) {
1910 // Anon newtalk disabled by configuration.
1911 $this->mNewtalk = false;
1912 } else {
1913 global $wgMemc;
1914 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1915 $newtalk = $wgMemc->get( $key );
1916 if ( strval( $newtalk ) !== '' ) {
1917 $this->mNewtalk = (bool)$newtalk;
1918 } else {
1919 // Since we are caching this, make sure it is up to date by getting it
1920 // from the master
1921 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1922 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1925 } else {
1926 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1930 return (bool)$this->mNewtalk;
1934 * Return the data needed to construct links for new talk page message
1935 * alerts. If there are new messages, this will return an associative array
1936 * with the following data:
1937 * wiki: The database name of the wiki
1938 * link: Root-relative link to the user's talk page
1939 * rev: The last talk page revision that the user has seen or null. This
1940 * is useful for building diff links.
1941 * If there are no new messages, it returns an empty array.
1942 * @note This function was designed to accomodate multiple talk pages, but
1943 * currently only returns a single link and revision.
1944 * @return Array
1946 public function getNewMessageLinks() {
1947 $talks = array();
1948 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
1949 return $talks;
1950 } elseif ( !$this->getNewtalk() ) {
1951 return array();
1953 $utp = $this->getTalkPage();
1954 $dbr = wfGetDB( DB_SLAVE );
1955 // Get the "last viewed rev" timestamp from the oldest message notification
1956 $timestamp = $dbr->selectField( 'user_newtalk',
1957 'MIN(user_last_timestamp)',
1958 $this->isAnon() ? array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
1959 __METHOD__ );
1960 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
1961 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
1965 * Get the revision ID for the last talk page revision viewed by the talk
1966 * page owner.
1967 * @return int|null Revision ID or null
1969 public function getNewMessageRevisionId() {
1970 $newMessageRevisionId = null;
1971 $newMessageLinks = $this->getNewMessageLinks();
1972 if ( $newMessageLinks ) {
1973 // Note: getNewMessageLinks() never returns more than a single link
1974 // and it is always for the same wiki, but we double-check here in
1975 // case that changes some time in the future.
1976 if ( count( $newMessageLinks ) === 1
1977 && $newMessageLinks[0]['wiki'] === wfWikiID()
1978 && $newMessageLinks[0]['rev']
1980 $newMessageRevision = $newMessageLinks[0]['rev'];
1981 $newMessageRevisionId = $newMessageRevision->getId();
1984 return $newMessageRevisionId;
1988 * Internal uncached check for new messages
1990 * @see getNewtalk()
1991 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1992 * @param string|int $id User's IP address for anonymous users, User ID otherwise
1993 * @param bool $fromMaster true to fetch from the master, false for a slave
1994 * @return bool True if the user has new messages
1996 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
1997 if ( $fromMaster ) {
1998 $db = wfGetDB( DB_MASTER );
1999 } else {
2000 $db = wfGetDB( DB_SLAVE );
2002 $ok = $db->selectField( 'user_newtalk', $field,
2003 array( $field => $id ), __METHOD__ );
2004 return $ok !== false;
2008 * Add or update the new messages flag
2009 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2010 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2011 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null.
2012 * @return bool True if successful, false otherwise
2014 protected function updateNewtalk( $field, $id, $curRev = null ) {
2015 // Get timestamp of the talk page revision prior to the current one
2016 $prevRev = $curRev ? $curRev->getPrevious() : false;
2017 $ts = $prevRev ? $prevRev->getTimestamp() : null;
2018 // Mark the user as having new messages since this revision
2019 $dbw = wfGetDB( DB_MASTER );
2020 $dbw->insert( 'user_newtalk',
2021 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2022 __METHOD__,
2023 'IGNORE' );
2024 if ( $dbw->affectedRows() ) {
2025 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
2026 return true;
2027 } else {
2028 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
2029 return false;
2034 * Clear the new messages flag for the given user
2035 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2036 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2037 * @return bool True if successful, false otherwise
2039 protected function deleteNewtalk( $field, $id ) {
2040 $dbw = wfGetDB( DB_MASTER );
2041 $dbw->delete( 'user_newtalk',
2042 array( $field => $id ),
2043 __METHOD__ );
2044 if ( $dbw->affectedRows() ) {
2045 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
2046 return true;
2047 } else {
2048 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
2049 return false;
2054 * Update the 'You have new messages!' status.
2055 * @param bool $val Whether the user has new messages
2056 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null or !$val.
2058 public function setNewtalk( $val, $curRev = null ) {
2059 if ( wfReadOnly() ) {
2060 return;
2063 $this->load();
2064 $this->mNewtalk = $val;
2066 if ( $this->isAnon() ) {
2067 $field = 'user_ip';
2068 $id = $this->getName();
2069 } else {
2070 $field = 'user_id';
2071 $id = $this->getId();
2073 global $wgMemc;
2075 if ( $val ) {
2076 $changed = $this->updateNewtalk( $field, $id, $curRev );
2077 } else {
2078 $changed = $this->deleteNewtalk( $field, $id );
2081 if ( $this->isAnon() ) {
2082 // Anons have a separate memcached space, since
2083 // user records aren't kept for them.
2084 $key = wfMemcKey( 'newtalk', 'ip', $id );
2085 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
2087 if ( $changed ) {
2088 $this->invalidateCache();
2093 * Generate a current or new-future timestamp to be stored in the
2094 * user_touched field when we update things.
2095 * @return string Timestamp in TS_MW format
2097 private static function newTouchedTimestamp() {
2098 global $wgClockSkewFudge;
2099 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
2103 * Clear user data from memcached.
2104 * Use after applying fun updates to the database; caller's
2105 * responsibility to update user_touched if appropriate.
2107 * Called implicitly from invalidateCache() and saveSettings().
2109 private function clearSharedCache() {
2110 $this->load();
2111 if ( $this->mId ) {
2112 global $wgMemc;
2113 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
2118 * Immediately touch the user data cache for this account.
2119 * Updates user_touched field, and removes account data from memcached
2120 * for reload on the next hit.
2122 public function invalidateCache() {
2123 if ( wfReadOnly() ) {
2124 return;
2126 $this->load();
2127 if ( $this->mId ) {
2128 $this->mTouched = self::newTouchedTimestamp();
2130 $dbw = wfGetDB( DB_MASTER );
2131 $userid = $this->mId;
2132 $touched = $this->mTouched;
2133 $method = __METHOD__;
2134 $dbw->onTransactionIdle( function() use ( $dbw, $userid, $touched, $method ) {
2135 // Prevent contention slams by checking user_touched first
2136 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2137 $needsPurge = $dbw->selectField( 'user', '1',
2138 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2139 if ( $needsPurge ) {
2140 $dbw->update( 'user',
2141 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2142 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2143 $method
2146 } );
2147 $this->clearSharedCache();
2152 * Validate the cache for this account.
2153 * @param string $timestamp A timestamp in TS_MW format
2154 * @return bool
2156 public function validateCache( $timestamp ) {
2157 $this->load();
2158 return ( $timestamp >= $this->mTouched );
2162 * Get the user touched timestamp
2163 * @return string timestamp
2165 public function getTouched() {
2166 $this->load();
2167 return $this->mTouched;
2171 * Set the password and reset the random token.
2172 * Calls through to authentication plugin if necessary;
2173 * will have no effect if the auth plugin refuses to
2174 * pass the change through or if the legal password
2175 * checks fail.
2177 * As a special case, setting the password to null
2178 * wipes it, so the account cannot be logged in until
2179 * a new password is set, for instance via e-mail.
2181 * @param string $str New password to set
2182 * @throws PasswordError on failure
2184 * @return bool
2186 public function setPassword( $str ) {
2187 global $wgAuth;
2189 if ( $str !== null ) {
2190 if ( !$wgAuth->allowPasswordChange() ) {
2191 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2194 if ( !$this->isValidPassword( $str ) ) {
2195 global $wgMinimalPasswordLength;
2196 $valid = $this->getPasswordValidity( $str );
2197 if ( is_array( $valid ) ) {
2198 $message = array_shift( $valid );
2199 $params = $valid;
2200 } else {
2201 $message = $valid;
2202 $params = array( $wgMinimalPasswordLength );
2204 throw new PasswordError( wfMessage( $message, $params )->text() );
2208 if ( !$wgAuth->setPassword( $this, $str ) ) {
2209 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2212 $this->setInternalPassword( $str );
2214 return true;
2218 * Set the password and reset the random token unconditionally.
2220 * @param string|null $str New password to set or null to set an invalid
2221 * password hash meaning that the user will not be able to log in
2222 * through the web interface.
2224 public function setInternalPassword( $str ) {
2225 $this->load();
2226 $this->setToken();
2228 if ( $str === null ) {
2229 // Save an invalid hash...
2230 $this->mPassword = '';
2231 } else {
2232 $this->mPassword = self::crypt( $str );
2234 $this->mNewpassword = '';
2235 $this->mNewpassTime = null;
2239 * Get the user's current token.
2240 * @param bool $forceCreation Force the generation of a new token if the user doesn't have one (default=true for backwards compatibility)
2241 * @return string Token
2243 public function getToken( $forceCreation = true ) {
2244 $this->load();
2245 if ( !$this->mToken && $forceCreation ) {
2246 $this->setToken();
2248 return $this->mToken;
2252 * Set the random token (used for persistent authentication)
2253 * Called from loadDefaults() among other places.
2255 * @param string|bool $token If specified, set the token to this value
2257 public function setToken( $token = false ) {
2258 $this->load();
2259 if ( !$token ) {
2260 $this->mToken = MWCryptRand::generateHex( USER_TOKEN_LENGTH );
2261 } else {
2262 $this->mToken = $token;
2267 * Set the password for a password reminder or new account email
2269 * @param $str New password to set or null to set an invalid
2270 * password hash meaning that the user will not be able to use it
2271 * @param bool $throttle If true, reset the throttle timestamp to the present
2273 public function setNewpassword( $str, $throttle = true ) {
2274 $this->load();
2276 if ( $str === null ) {
2277 $this->mNewpassword = '';
2278 $this->mNewpassTime = null;
2279 } else {
2280 $this->mNewpassword = self::crypt( $str );
2281 if ( $throttle ) {
2282 $this->mNewpassTime = wfTimestampNow();
2288 * Has password reminder email been sent within the last
2289 * $wgPasswordReminderResendTime hours?
2290 * @return bool
2292 public function isPasswordReminderThrottled() {
2293 global $wgPasswordReminderResendTime;
2294 $this->load();
2295 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
2296 return false;
2298 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
2299 return time() < $expiry;
2303 * Get the user's e-mail address
2304 * @return string User's email address
2306 public function getEmail() {
2307 $this->load();
2308 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
2309 return $this->mEmail;
2313 * Get the timestamp of the user's e-mail authentication
2314 * @return string TS_MW timestamp
2316 public function getEmailAuthenticationTimestamp() {
2317 $this->load();
2318 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2319 return $this->mEmailAuthenticated;
2323 * Set the user's e-mail address
2324 * @param string $str New e-mail address
2326 public function setEmail( $str ) {
2327 $this->load();
2328 if ( $str == $this->mEmail ) {
2329 return;
2331 $this->mEmail = $str;
2332 $this->invalidateEmail();
2333 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
2337 * Set the user's e-mail address and a confirmation mail if needed.
2339 * @since 1.20
2340 * @param string $str New e-mail address
2341 * @return Status
2343 public function setEmailWithConfirmation( $str ) {
2344 global $wgEnableEmail, $wgEmailAuthentication;
2346 if ( !$wgEnableEmail ) {
2347 return Status::newFatal( 'emaildisabled' );
2350 $oldaddr = $this->getEmail();
2351 if ( $str === $oldaddr ) {
2352 return Status::newGood( true );
2355 $this->setEmail( $str );
2357 if ( $str !== '' && $wgEmailAuthentication ) {
2358 // Send a confirmation request to the new address if needed
2359 $type = $oldaddr != '' ? 'changed' : 'set';
2360 $result = $this->sendConfirmationMail( $type );
2361 if ( $result->isGood() ) {
2362 // Say the the caller that a confirmation mail has been sent
2363 $result->value = 'eauth';
2365 } else {
2366 $result = Status::newGood( true );
2369 return $result;
2373 * Get the user's real name
2374 * @return string User's real name
2376 public function getRealName() {
2377 if ( !$this->isItemLoaded( 'realname' ) ) {
2378 $this->load();
2381 return $this->mRealName;
2385 * Set the user's real name
2386 * @param string $str New real name
2388 public function setRealName( $str ) {
2389 $this->load();
2390 $this->mRealName = $str;
2394 * Get the user's current setting for a given option.
2396 * @param string $oname The option to check
2397 * @param string $defaultOverride A default value returned if the option does not exist
2398 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2399 * @return string User's current value for the option
2400 * @see getBoolOption()
2401 * @see getIntOption()
2403 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2404 global $wgHiddenPrefs;
2405 $this->loadOptions();
2407 # We want 'disabled' preferences to always behave as the default value for
2408 # users, even if they have set the option explicitly in their settings (ie they
2409 # set it, and then it was disabled removing their ability to change it). But
2410 # we don't want to erase the preferences in the database in case the preference
2411 # is re-enabled again. So don't touch $mOptions, just override the returned value
2412 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2413 return self::getDefaultOption( $oname );
2416 if ( array_key_exists( $oname, $this->mOptions ) ) {
2417 return $this->mOptions[$oname];
2418 } else {
2419 return $defaultOverride;
2424 * Get all user's options
2426 * @return array
2428 public function getOptions() {
2429 global $wgHiddenPrefs;
2430 $this->loadOptions();
2431 $options = $this->mOptions;
2433 # We want 'disabled' preferences to always behave as the default value for
2434 # users, even if they have set the option explicitly in their settings (ie they
2435 # set it, and then it was disabled removing their ability to change it). But
2436 # we don't want to erase the preferences in the database in case the preference
2437 # is re-enabled again. So don't touch $mOptions, just override the returned value
2438 foreach ( $wgHiddenPrefs as $pref ) {
2439 $default = self::getDefaultOption( $pref );
2440 if ( $default !== null ) {
2441 $options[$pref] = $default;
2445 return $options;
2449 * Get the user's current setting for a given option, as a boolean value.
2451 * @param string $oname The option to check
2452 * @return bool User's current value for the option
2453 * @see getOption()
2455 public function getBoolOption( $oname ) {
2456 return (bool)$this->getOption( $oname );
2460 * Get the user's current setting for a given option, as an integer value.
2462 * @param string $oname The option to check
2463 * @param int $defaultOverride A default value returned if the option does not exist
2464 * @return int User's current value for the option
2465 * @see getOption()
2467 public function getIntOption( $oname, $defaultOverride = 0 ) {
2468 $val = $this->getOption( $oname );
2469 if ( $val == '' ) {
2470 $val = $defaultOverride;
2472 return intval( $val );
2476 * Set the given option for a user.
2478 * @param string $oname The option to set
2479 * @param mixed $val New value to set
2481 public function setOption( $oname, $val ) {
2482 $this->loadOptions();
2484 // Explicitly NULL values should refer to defaults
2485 if ( is_null( $val ) ) {
2486 $val = self::getDefaultOption( $oname );
2489 $this->mOptions[$oname] = $val;
2493 * Get a token stored in the preferences (like the watchlist one),
2494 * resetting it if it's empty (and saving changes).
2496 * @param string $oname The option name to retrieve the token from
2497 * @return string|bool User's current value for the option, or false if this option is disabled.
2498 * @see resetTokenFromOption()
2499 * @see getOption()
2501 public function getTokenFromOption( $oname ) {
2502 global $wgHiddenPrefs;
2503 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2504 return false;
2507 $token = $this->getOption( $oname );
2508 if ( !$token ) {
2509 $token = $this->resetTokenFromOption( $oname );
2510 $this->saveSettings();
2512 return $token;
2516 * Reset a token stored in the preferences (like the watchlist one).
2517 * *Does not* save user's preferences (similarly to setOption()).
2519 * @param string $oname The option name to reset the token in
2520 * @return string|bool New token value, or false if this option is disabled.
2521 * @see getTokenFromOption()
2522 * @see setOption()
2524 public function resetTokenFromOption( $oname ) {
2525 global $wgHiddenPrefs;
2526 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2527 return false;
2530 $token = MWCryptRand::generateHex( 40 );
2531 $this->setOption( $oname, $token );
2532 return $token;
2536 * Return a list of the types of user options currently returned by
2537 * User::getOptionKinds().
2539 * Currently, the option kinds are:
2540 * - 'registered' - preferences which are registered in core MediaWiki or
2541 * by extensions using the UserGetDefaultOptions hook.
2542 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2543 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2544 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2545 * be used by user scripts.
2546 * - 'special' - "preferences" that are not accessible via User::getOptions
2547 * or User::setOptions.
2548 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2549 * These are usually legacy options, removed in newer versions.
2551 * The API (and possibly others) use this function to determine the possible
2552 * option types for validation purposes, so make sure to update this when a
2553 * new option kind is added.
2555 * @see User::getOptionKinds
2556 * @return array Option kinds
2558 public static function listOptionKinds() {
2559 return array(
2560 'registered',
2561 'registered-multiselect',
2562 'registered-checkmatrix',
2563 'userjs',
2564 'special',
2565 'unused'
2570 * Return an associative array mapping preferences keys to the kind of a preference they're
2571 * used for. Different kinds are handled differently when setting or reading preferences.
2573 * See User::listOptionKinds for the list of valid option types that can be provided.
2575 * @see User::listOptionKinds
2576 * @param $context IContextSource
2577 * @param array $options assoc. array with options keys to check as keys. Defaults to $this->mOptions.
2578 * @return array the key => kind mapping data
2580 public function getOptionKinds( IContextSource $context, $options = null ) {
2581 $this->loadOptions();
2582 if ( $options === null ) {
2583 $options = $this->mOptions;
2586 $prefs = Preferences::getPreferences( $this, $context );
2587 $mapping = array();
2589 // Pull out the "special" options, so they don't get converted as
2590 // multiselect or checkmatrix.
2591 $specialOptions = array_fill_keys( Preferences::getSaveBlacklist(), true );
2592 foreach ( $specialOptions as $name => $value ) {
2593 unset( $prefs[$name] );
2596 // Multiselect and checkmatrix options are stored in the database with
2597 // one key per option, each having a boolean value. Extract those keys.
2598 $multiselectOptions = array();
2599 foreach ( $prefs as $name => $info ) {
2600 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2601 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2602 $opts = HTMLFormField::flattenOptions( $info['options'] );
2603 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2605 foreach ( $opts as $value ) {
2606 $multiselectOptions["$prefix$value"] = true;
2609 unset( $prefs[$name] );
2612 $checkmatrixOptions = array();
2613 foreach ( $prefs as $name => $info ) {
2614 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2615 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2616 $columns = HTMLFormField::flattenOptions( $info['columns'] );
2617 $rows = HTMLFormField::flattenOptions( $info['rows'] );
2618 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2620 foreach ( $columns as $column ) {
2621 foreach ( $rows as $row ) {
2622 $checkmatrixOptions["$prefix-$column-$row"] = true;
2626 unset( $prefs[$name] );
2630 // $value is ignored
2631 foreach ( $options as $key => $value ) {
2632 if ( isset( $prefs[$key] ) ) {
2633 $mapping[$key] = 'registered';
2634 } elseif ( isset( $multiselectOptions[$key] ) ) {
2635 $mapping[$key] = 'registered-multiselect';
2636 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2637 $mapping[$key] = 'registered-checkmatrix';
2638 } elseif ( isset( $specialOptions[$key] ) ) {
2639 $mapping[$key] = 'special';
2640 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2641 $mapping[$key] = 'userjs';
2642 } else {
2643 $mapping[$key] = 'unused';
2647 return $mapping;
2651 * Reset certain (or all) options to the site defaults
2653 * The optional parameter determines which kinds of preferences will be reset.
2654 * Supported values are everything that can be reported by getOptionKinds()
2655 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2657 * @param array|string $resetKinds which kinds of preferences to reset. Defaults to
2658 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2659 * for backwards-compatibility.
2660 * @param $context IContextSource|null context source used when $resetKinds
2661 * does not contain 'all', passed to getOptionKinds().
2662 * Defaults to RequestContext::getMain() when null.
2664 public function resetOptions(
2665 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2666 IContextSource $context = null
2668 $this->load();
2669 $defaultOptions = self::getDefaultOptions();
2671 if ( !is_array( $resetKinds ) ) {
2672 $resetKinds = array( $resetKinds );
2675 if ( in_array( 'all', $resetKinds ) ) {
2676 $newOptions = $defaultOptions;
2677 } else {
2678 if ( $context === null ) {
2679 $context = RequestContext::getMain();
2682 $optionKinds = $this->getOptionKinds( $context );
2683 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
2684 $newOptions = array();
2686 // Use default values for the options that should be deleted, and
2687 // copy old values for the ones that shouldn't.
2688 foreach ( $this->mOptions as $key => $value ) {
2689 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2690 if ( array_key_exists( $key, $defaultOptions ) ) {
2691 $newOptions[$key] = $defaultOptions[$key];
2693 } else {
2694 $newOptions[$key] = $value;
2699 $this->mOptions = $newOptions;
2700 $this->mOptionsLoaded = true;
2704 * Get the user's preferred date format.
2705 * @return string User's preferred date format
2707 public function getDatePreference() {
2708 // Important migration for old data rows
2709 if ( is_null( $this->mDatePreference ) ) {
2710 global $wgLang;
2711 $value = $this->getOption( 'date' );
2712 $map = $wgLang->getDatePreferenceMigrationMap();
2713 if ( isset( $map[$value] ) ) {
2714 $value = $map[$value];
2716 $this->mDatePreference = $value;
2718 return $this->mDatePreference;
2722 * Determine based on the wiki configuration and the user's options,
2723 * whether this user must be over HTTPS no matter what.
2725 * @return bool
2727 public function requiresHTTPS() {
2728 global $wgSecureLogin;
2729 if ( !$wgSecureLogin ) {
2730 return false;
2731 } else {
2732 $https = $this->getBoolOption( 'prefershttps' );
2733 wfRunHooks( 'UserRequiresHTTPS', array( $this, &$https ) );
2734 if ( $https ) {
2735 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2737 return $https;
2742 * Get the user preferred stub threshold
2744 * @return int
2746 public function getStubThreshold() {
2747 global $wgMaxArticleSize; # Maximum article size, in Kb
2748 $threshold = $this->getIntOption( 'stubthreshold' );
2749 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2750 // If they have set an impossible value, disable the preference
2751 // so we can use the parser cache again.
2752 $threshold = 0;
2754 return $threshold;
2758 * Get the permissions this user has.
2759 * @return Array of String permission names
2761 public function getRights() {
2762 if ( is_null( $this->mRights ) ) {
2763 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2764 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
2765 // Force reindexation of rights when a hook has unset one of them
2766 $this->mRights = array_values( array_unique( $this->mRights ) );
2768 return $this->mRights;
2772 * Get the list of explicit group memberships this user has.
2773 * The implicit * and user groups are not included.
2774 * @return Array of String internal group names
2776 public function getGroups() {
2777 $this->load();
2778 $this->loadGroups();
2779 return $this->mGroups;
2783 * Get the list of implicit group memberships this user has.
2784 * This includes all explicit groups, plus 'user' if logged in,
2785 * '*' for all accounts, and autopromoted groups
2786 * @param bool $recache Whether to avoid the cache
2787 * @return Array of String internal group names
2789 public function getEffectiveGroups( $recache = false ) {
2790 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
2791 wfProfileIn( __METHOD__ );
2792 $this->mEffectiveGroups = array_unique( array_merge(
2793 $this->getGroups(), // explicit groups
2794 $this->getAutomaticGroups( $recache ) // implicit groups
2795 ) );
2796 // Hook for additional groups
2797 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
2798 // Force reindexation of groups when a hook has unset one of them
2799 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
2800 wfProfileOut( __METHOD__ );
2802 return $this->mEffectiveGroups;
2806 * Get the list of implicit group memberships this user has.
2807 * This includes 'user' if logged in, '*' for all accounts,
2808 * and autopromoted groups
2809 * @param bool $recache Whether to avoid the cache
2810 * @return Array of String internal group names
2812 public function getAutomaticGroups( $recache = false ) {
2813 if ( $recache || is_null( $this->mImplicitGroups ) ) {
2814 wfProfileIn( __METHOD__ );
2815 $this->mImplicitGroups = array( '*' );
2816 if ( $this->getId() ) {
2817 $this->mImplicitGroups[] = 'user';
2819 $this->mImplicitGroups = array_unique( array_merge(
2820 $this->mImplicitGroups,
2821 Autopromote::getAutopromoteGroups( $this )
2822 ) );
2824 if ( $recache ) {
2825 // Assure data consistency with rights/groups,
2826 // as getEffectiveGroups() depends on this function
2827 $this->mEffectiveGroups = null;
2829 wfProfileOut( __METHOD__ );
2831 return $this->mImplicitGroups;
2835 * Returns the groups the user has belonged to.
2837 * The user may still belong to the returned groups. Compare with getGroups().
2839 * The function will not return groups the user had belonged to before MW 1.17
2841 * @return array Names of the groups the user has belonged to.
2843 public function getFormerGroups() {
2844 if ( is_null( $this->mFormerGroups ) ) {
2845 $dbr = wfGetDB( DB_MASTER );
2846 $res = $dbr->select( 'user_former_groups',
2847 array( 'ufg_group' ),
2848 array( 'ufg_user' => $this->mId ),
2849 __METHOD__ );
2850 $this->mFormerGroups = array();
2851 foreach ( $res as $row ) {
2852 $this->mFormerGroups[] = $row->ufg_group;
2855 return $this->mFormerGroups;
2859 * Get the user's edit count.
2860 * @return int, null for anonymous users
2862 public function getEditCount() {
2863 if ( !$this->getId() ) {
2864 return null;
2867 if ( !isset( $this->mEditCount ) ) {
2868 /* Populate the count, if it has not been populated yet */
2869 wfProfileIn( __METHOD__ );
2870 $dbr = wfGetDB( DB_SLAVE );
2871 // check if the user_editcount field has been initialized
2872 $count = $dbr->selectField(
2873 'user', 'user_editcount',
2874 array( 'user_id' => $this->mId ),
2875 __METHOD__
2878 if ( $count === null ) {
2879 // it has not been initialized. do so.
2880 $count = $this->initEditCount();
2882 $this->mEditCount = $count;
2883 wfProfileOut( __METHOD__ );
2885 return (int)$this->mEditCount;
2889 * Add the user to the given group.
2890 * This takes immediate effect.
2891 * @param string $group Name of the group to add
2893 public function addGroup( $group ) {
2894 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2895 $dbw = wfGetDB( DB_MASTER );
2896 if ( $this->getId() ) {
2897 $dbw->insert( 'user_groups',
2898 array(
2899 'ug_user' => $this->getID(),
2900 'ug_group' => $group,
2902 __METHOD__,
2903 array( 'IGNORE' ) );
2906 $this->loadGroups();
2907 $this->mGroups[] = $group;
2908 // In case loadGroups was not called before, we now have the right twice.
2909 // Get rid of the duplicate.
2910 $this->mGroups = array_unique( $this->mGroups );
2912 // Refresh the groups caches, and clear the rights cache so it will be
2913 // refreshed on the next call to $this->getRights().
2914 $this->getEffectiveGroups( true );
2915 $this->mRights = null;
2917 $this->invalidateCache();
2921 * Remove the user from the given group.
2922 * This takes immediate effect.
2923 * @param string $group Name of the group to remove
2925 public function removeGroup( $group ) {
2926 $this->load();
2927 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
2928 $dbw = wfGetDB( DB_MASTER );
2929 $dbw->delete( 'user_groups',
2930 array(
2931 'ug_user' => $this->getID(),
2932 'ug_group' => $group,
2933 ), __METHOD__ );
2934 // Remember that the user was in this group
2935 $dbw->insert( 'user_former_groups',
2936 array(
2937 'ufg_user' => $this->getID(),
2938 'ufg_group' => $group,
2940 __METHOD__,
2941 array( 'IGNORE' ) );
2943 $this->loadGroups();
2944 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
2946 // Refresh the groups caches, and clear the rights cache so it will be
2947 // refreshed on the next call to $this->getRights().
2948 $this->getEffectiveGroups( true );
2949 $this->mRights = null;
2951 $this->invalidateCache();
2955 * Get whether the user is logged in
2956 * @return bool
2958 public function isLoggedIn() {
2959 return $this->getID() != 0;
2963 * Get whether the user is anonymous
2964 * @return bool
2966 public function isAnon() {
2967 return !$this->isLoggedIn();
2971 * Check if user is allowed to access a feature / make an action
2973 * @internal param \String $varargs permissions to test
2974 * @return boolean: True if user is allowed to perform *any* of the given actions
2976 * @return bool
2978 public function isAllowedAny( /*...*/ ) {
2979 $permissions = func_get_args();
2980 foreach ( $permissions as $permission ) {
2981 if ( $this->isAllowed( $permission ) ) {
2982 return true;
2985 return false;
2990 * @internal param $varargs string
2991 * @return bool True if the user is allowed to perform *all* of the given actions
2993 public function isAllowedAll( /*...*/ ) {
2994 $permissions = func_get_args();
2995 foreach ( $permissions as $permission ) {
2996 if ( !$this->isAllowed( $permission ) ) {
2997 return false;
3000 return true;
3004 * Internal mechanics of testing a permission
3005 * @param string $action
3006 * @return bool
3008 public function isAllowed( $action = '' ) {
3009 if ( $action === '' ) {
3010 return true; // In the spirit of DWIM
3012 // Patrolling may not be enabled
3013 if ( $action === 'patrol' || $action === 'autopatrol' ) {
3014 global $wgUseRCPatrol, $wgUseNPPatrol;
3015 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3016 return false;
3019 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3020 // by misconfiguration: 0 == 'foo'
3021 return in_array( $action, $this->getRights(), true );
3025 * Check whether to enable recent changes patrol features for this user
3026 * @return boolean: True or false
3028 public function useRCPatrol() {
3029 global $wgUseRCPatrol;
3030 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3034 * Check whether to enable new pages patrol features for this user
3035 * @return bool True or false
3037 public function useNPPatrol() {
3038 global $wgUseRCPatrol, $wgUseNPPatrol;
3039 return (
3040 ( $wgUseRCPatrol || $wgUseNPPatrol )
3041 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3046 * Get the WebRequest object to use with this object
3048 * @return WebRequest
3050 public function getRequest() {
3051 if ( $this->mRequest ) {
3052 return $this->mRequest;
3053 } else {
3054 global $wgRequest;
3055 return $wgRequest;
3060 * Get the current skin, loading it if required
3061 * @return Skin The current skin
3062 * @todo FIXME: Need to check the old failback system [AV]
3063 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3065 public function getSkin() {
3066 wfDeprecated( __METHOD__, '1.18' );
3067 return RequestContext::getMain()->getSkin();
3071 * Get a WatchedItem for this user and $title.
3073 * @since 1.22 $checkRights parameter added
3074 * @param $title Title
3075 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3076 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3077 * @return WatchedItem
3079 public function getWatchedItem( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3080 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3082 if ( isset( $this->mWatchedItems[$key] ) ) {
3083 return $this->mWatchedItems[$key];
3086 if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
3087 $this->mWatchedItems = array();
3090 $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title, $checkRights );
3091 return $this->mWatchedItems[$key];
3095 * Check the watched status of an article.
3096 * @since 1.22 $checkRights parameter added
3097 * @param $title Title of the article to look at
3098 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3099 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3100 * @return bool
3102 public function isWatched( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3103 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3107 * Watch an article.
3108 * @since 1.22 $checkRights parameter added
3109 * @param $title Title of the article to look at
3110 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3111 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3113 public function addWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3114 $this->getWatchedItem( $title, $checkRights )->addWatch();
3115 $this->invalidateCache();
3119 * Stop watching an article.
3120 * @since 1.22 $checkRights parameter added
3121 * @param $title Title of the article to look at
3122 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3123 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3125 public function removeWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3126 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3127 $this->invalidateCache();
3131 * Clear the user's notification timestamp for the given title.
3132 * If e-notif e-mails are on, they will receive notification mails on
3133 * the next change of the page if it's watched etc.
3134 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3135 * @param $title Title of the article to look at
3136 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3138 public function clearNotification( &$title, $oldid = 0 ) {
3139 global $wgUseEnotif, $wgShowUpdatedMarker;
3141 // Do nothing if the database is locked to writes
3142 if ( wfReadOnly() ) {
3143 return;
3146 // Do nothing if not allowed to edit the watchlist
3147 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3148 return;
3151 // If we're working on user's talk page, we should update the talk page message indicator
3152 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3153 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3154 return;
3157 $nextid = $oldid ? $title->getNextRevisionID( $oldid ) : null;
3159 if ( !$oldid || !$nextid ) {
3160 // If we're looking at the latest revision, we should definitely clear it
3161 $this->setNewtalk( false );
3162 } else {
3163 // Otherwise we should update its revision, if it's present
3164 if ( $this->getNewtalk() ) {
3165 // Naturally the other one won't clear by itself
3166 $this->setNewtalk( false );
3167 $this->setNewtalk( true, Revision::newFromId( $nextid ) );
3172 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3173 return;
3176 if ( $this->isAnon() ) {
3177 // Nothing else to do...
3178 return;
3181 // Only update the timestamp if the page is being watched.
3182 // The query to find out if it is watched is cached both in memcached and per-invocation,
3183 // and when it does have to be executed, it can be on a slave
3184 // If this is the user's newtalk page, we always update the timestamp
3185 $force = '';
3186 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3187 $force = 'force';
3190 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3194 * Resets all of the given user's page-change notification timestamps.
3195 * If e-notif e-mails are on, they will receive notification mails on
3196 * the next change of any watched page.
3197 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3199 public function clearAllNotifications() {
3200 if ( wfReadOnly() ) {
3201 return;
3204 // Do nothing if not allowed to edit the watchlist
3205 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3206 return;
3209 global $wgUseEnotif, $wgShowUpdatedMarker;
3210 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3211 $this->setNewtalk( false );
3212 return;
3214 $id = $this->getId();
3215 if ( $id != 0 ) {
3216 $dbw = wfGetDB( DB_MASTER );
3217 $dbw->update( 'watchlist',
3218 array( /* SET */ 'wl_notificationtimestamp' => null ),
3219 array( /* WHERE */ 'wl_user' => $id ),
3220 __METHOD__
3222 // We also need to clear here the "you have new message" notification for the own user_talk page;
3223 // it's cleared one page view later in WikiPage::doViewUpdates().
3228 * Set this user's options from an encoded string
3229 * @param string $str Encoded options to import
3231 * @deprecated in 1.19 due to removal of user_options from the user table
3233 private function decodeOptions( $str ) {
3234 wfDeprecated( __METHOD__, '1.19' );
3235 if ( !$str ) {
3236 return;
3239 $this->mOptionsLoaded = true;
3240 $this->mOptionOverrides = array();
3242 // If an option is not set in $str, use the default value
3243 $this->mOptions = self::getDefaultOptions();
3245 $a = explode( "\n", $str );
3246 foreach ( $a as $s ) {
3247 $m = array();
3248 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
3249 $this->mOptions[$m[1]] = $m[2];
3250 $this->mOptionOverrides[$m[1]] = $m[2];
3256 * Set a cookie on the user's client. Wrapper for
3257 * WebResponse::setCookie
3258 * @param string $name Name of the cookie to set
3259 * @param string $value Value to set
3260 * @param int $exp Expiration time, as a UNIX time value;
3261 * if 0 or not specified, use the default $wgCookieExpiration
3262 * @param bool $secure
3263 * true: Force setting the secure attribute when setting the cookie
3264 * false: Force NOT setting the secure attribute when setting the cookie
3265 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3266 * @param array $params Array of options sent passed to WebResponse::setcookie()
3268 protected function setCookie( $name, $value, $exp = 0, $secure = null, $params = array() ) {
3269 $params['secure'] = $secure;
3270 $this->getRequest()->response()->setcookie( $name, $value, $exp, $params );
3274 * Clear a cookie on the user's client
3275 * @param string $name Name of the cookie to clear
3276 * @param bool $secure
3277 * true: Force setting the secure attribute when setting the cookie
3278 * false: Force NOT setting the secure attribute when setting the cookie
3279 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3280 * @param array $params Array of options sent passed to WebResponse::setcookie()
3282 protected function clearCookie( $name, $secure = null, $params = array() ) {
3283 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3287 * Set the default cookies for this session on the user's client.
3289 * @param $request WebRequest object to use; $wgRequest will be used if null
3290 * is passed.
3291 * @param bool $secure Whether to force secure/insecure cookies or use default
3293 public function setCookies( $request = null, $secure = null ) {
3294 if ( $request === null ) {
3295 $request = $this->getRequest();
3298 $this->load();
3299 if ( 0 == $this->mId ) {
3300 return;
3302 if ( !$this->mToken ) {
3303 // When token is empty or NULL generate a new one and then save it to the database
3304 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3305 // Simply by setting every cell in the user_token column to NULL and letting them be
3306 // regenerated as users log back into the wiki.
3307 $this->setToken();
3308 $this->saveSettings();
3310 $session = array(
3311 'wsUserID' => $this->mId,
3312 'wsToken' => $this->mToken,
3313 'wsUserName' => $this->getName()
3315 $cookies = array(
3316 'UserID' => $this->mId,
3317 'UserName' => $this->getName(),
3319 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
3320 $cookies['Token'] = $this->mToken;
3321 } else {
3322 $cookies['Token'] = false;
3325 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3327 foreach ( $session as $name => $value ) {
3328 $request->setSessionData( $name, $value );
3330 foreach ( $cookies as $name => $value ) {
3331 if ( $value === false ) {
3332 $this->clearCookie( $name );
3333 } else {
3334 $this->setCookie( $name, $value, 0, $secure );
3339 * If wpStickHTTPS was selected, also set an insecure cookie that
3340 * will cause the site to redirect the user to HTTPS, if they access
3341 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3342 * as the one set by centralauth (bug 53538). Also set it to session, or
3343 * standard time setting, based on if rememberme was set.
3345 if ( $request->getCheck( 'wpStickHTTPS' ) || $this->requiresHTTPS() ) {
3346 $time = null;
3347 if ( ( 1 == $this->getOption( 'rememberpassword' ) ) ) {
3348 $time = 0; // set to $wgCookieExpiration
3350 $this->setCookie(
3351 'forceHTTPS',
3352 'true',
3353 $time,
3354 false,
3355 array( 'prefix' => '' ) // no prefix
3361 * Log this user out.
3363 public function logout() {
3364 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3365 $this->doLogout();
3370 * Clear the user's cookies and session, and reset the instance cache.
3371 * @see logout()
3373 public function doLogout() {
3374 $this->clearInstanceCache( 'defaults' );
3376 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3378 $this->clearCookie( 'UserID' );
3379 $this->clearCookie( 'Token' );
3380 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3382 // Remember when user logged out, to prevent seeing cached pages
3383 $this->setCookie( 'LoggedOut', time(), time() + 86400 );
3387 * Save this user's settings into the database.
3388 * @todo Only rarely do all these fields need to be set!
3390 public function saveSettings() {
3391 global $wgAuth;
3393 $this->load();
3394 if ( wfReadOnly() ) {
3395 return;
3397 if ( 0 == $this->mId ) {
3398 return;
3401 $this->mTouched = self::newTouchedTimestamp();
3402 if ( !$wgAuth->allowSetLocalPassword() ) {
3403 $this->mPassword = '';
3406 $dbw = wfGetDB( DB_MASTER );
3407 $dbw->update( 'user',
3408 array( /* SET */
3409 'user_name' => $this->mName,
3410 'user_password' => $this->mPassword,
3411 'user_newpassword' => $this->mNewpassword,
3412 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3413 'user_real_name' => $this->mRealName,
3414 'user_email' => $this->mEmail,
3415 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3416 'user_touched' => $dbw->timestamp( $this->mTouched ),
3417 'user_token' => strval( $this->mToken ),
3418 'user_email_token' => $this->mEmailToken,
3419 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3420 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires ),
3421 ), array( /* WHERE */
3422 'user_id' => $this->mId
3423 ), __METHOD__
3426 $this->saveOptions();
3428 wfRunHooks( 'UserSaveSettings', array( $this ) );
3429 $this->clearSharedCache();
3430 $this->getUserPage()->invalidateCache();
3434 * If only this user's username is known, and it exists, return the user ID.
3435 * @return int
3437 public function idForName() {
3438 $s = trim( $this->getName() );
3439 if ( $s === '' ) {
3440 return 0;
3443 $dbr = wfGetDB( DB_SLAVE );
3444 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
3445 if ( $id === false ) {
3446 $id = 0;
3448 return $id;
3452 * Add a user to the database, return the user object
3454 * @param string $name Username to add
3455 * @param array $params of Strings Non-default parameters to save to the database as user_* fields:
3456 * - password The user's password hash. Password logins will be disabled if this is omitted.
3457 * - newpassword Hash for a temporary password that has been mailed to the user
3458 * - email The user's email address
3459 * - email_authenticated The email authentication timestamp
3460 * - real_name The user's real name
3461 * - options An associative array of non-default options
3462 * - token Random authentication token. Do not set.
3463 * - registration Registration timestamp. Do not set.
3465 * @return User object, or null if the username already exists
3467 public static function createNew( $name, $params = array() ) {
3468 $user = new User;
3469 $user->load();
3470 $user->setToken(); // init token
3471 if ( isset( $params['options'] ) ) {
3472 $user->mOptions = $params['options'] + (array)$user->mOptions;
3473 unset( $params['options'] );
3475 $dbw = wfGetDB( DB_MASTER );
3476 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3478 $fields = array(
3479 'user_id' => $seqVal,
3480 'user_name' => $name,
3481 'user_password' => $user->mPassword,
3482 'user_newpassword' => $user->mNewpassword,
3483 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
3484 'user_email' => $user->mEmail,
3485 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3486 'user_real_name' => $user->mRealName,
3487 'user_token' => strval( $user->mToken ),
3488 'user_registration' => $dbw->timestamp( $user->mRegistration ),
3489 'user_editcount' => 0,
3490 'user_touched' => $dbw->timestamp( self::newTouchedTimestamp() ),
3492 foreach ( $params as $name => $value ) {
3493 $fields["user_$name"] = $value;
3495 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
3496 if ( $dbw->affectedRows() ) {
3497 $newUser = User::newFromId( $dbw->insertId() );
3498 } else {
3499 $newUser = null;
3501 return $newUser;
3505 * Add this existing user object to the database. If the user already
3506 * exists, a fatal status object is returned, and the user object is
3507 * initialised with the data from the database.
3509 * Previously, this function generated a DB error due to a key conflict
3510 * if the user already existed. Many extension callers use this function
3511 * in code along the lines of:
3513 * $user = User::newFromName( $name );
3514 * if ( !$user->isLoggedIn() ) {
3515 * $user->addToDatabase();
3517 * // do something with $user...
3519 * However, this was vulnerable to a race condition (bug 16020). By
3520 * initialising the user object if the user exists, we aim to support this
3521 * calling sequence as far as possible.
3523 * Note that if the user exists, this function will acquire a write lock,
3524 * so it is still advisable to make the call conditional on isLoggedIn(),
3525 * and to commit the transaction after calling.
3527 * @throws MWException
3528 * @return Status
3530 public function addToDatabase() {
3531 $this->load();
3532 if ( !$this->mToken ) {
3533 $this->setToken(); // init token
3536 $this->mTouched = self::newTouchedTimestamp();
3538 $dbw = wfGetDB( DB_MASTER );
3539 $inWrite = $dbw->writesOrCallbacksPending();
3540 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3541 $dbw->insert( 'user',
3542 array(
3543 'user_id' => $seqVal,
3544 'user_name' => $this->mName,
3545 'user_password' => $this->mPassword,
3546 'user_newpassword' => $this->mNewpassword,
3547 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3548 'user_email' => $this->mEmail,
3549 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3550 'user_real_name' => $this->mRealName,
3551 'user_token' => strval( $this->mToken ),
3552 'user_registration' => $dbw->timestamp( $this->mRegistration ),
3553 'user_editcount' => 0,
3554 'user_touched' => $dbw->timestamp( $this->mTouched ),
3555 ), __METHOD__,
3556 array( 'IGNORE' )
3558 if ( !$dbw->affectedRows() ) {
3559 if ( !$inWrite ) {
3560 // XXX: Get out of REPEATABLE-READ so the SELECT below works.
3561 // Often this case happens early in views before any writes.
3562 // This shows up at least with CentralAuth.
3563 $dbw->commit( __METHOD__, 'flush' );
3565 $this->mId = $dbw->selectField( 'user', 'user_id',
3566 array( 'user_name' => $this->mName ), __METHOD__ );
3567 $loaded = false;
3568 if ( $this->mId ) {
3569 if ( $this->loadFromDatabase() ) {
3570 $loaded = true;
3573 if ( !$loaded ) {
3574 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
3575 "to insert user '{$this->mName}' row, but it was not present in select!" );
3577 return Status::newFatal( 'userexists' );
3579 $this->mId = $dbw->insertId();
3581 // Clear instance cache other than user table data, which is already accurate
3582 $this->clearInstanceCache();
3584 $this->saveOptions();
3585 return Status::newGood();
3589 * If this user is logged-in and blocked,
3590 * block any IP address they've successfully logged in from.
3591 * @return bool A block was spread
3593 public function spreadAnyEditBlock() {
3594 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3595 return $this->spreadBlock();
3597 return false;
3601 * If this (non-anonymous) user is blocked,
3602 * block the IP address they've successfully logged in from.
3603 * @return bool A block was spread
3605 protected function spreadBlock() {
3606 wfDebug( __METHOD__ . "()\n" );
3607 $this->load();
3608 if ( $this->mId == 0 ) {
3609 return false;
3612 $userblock = Block::newFromTarget( $this->getName() );
3613 if ( !$userblock ) {
3614 return false;
3617 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3621 * Get whether the user is explicitly blocked from account creation.
3622 * @return bool|Block
3624 public function isBlockedFromCreateAccount() {
3625 $this->getBlockedStatus();
3626 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
3627 return $this->mBlock;
3630 # bug 13611: if the IP address the user is trying to create an account from is
3631 # blocked with createaccount disabled, prevent new account creation there even
3632 # when the user is logged in
3633 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3634 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
3636 return $this->mBlockedFromCreateAccount instanceof Block && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
3637 ? $this->mBlockedFromCreateAccount
3638 : false;
3642 * Get whether the user is blocked from using Special:Emailuser.
3643 * @return bool
3645 public function isBlockedFromEmailuser() {
3646 $this->getBlockedStatus();
3647 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
3651 * Get whether the user is allowed to create an account.
3652 * @return bool
3654 public function isAllowedToCreateAccount() {
3655 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3659 * Get this user's personal page title.
3661 * @return Title: User's personal page title
3663 public function getUserPage() {
3664 return Title::makeTitle( NS_USER, $this->getName() );
3668 * Get this user's talk page title.
3670 * @return Title: User's talk page title
3672 public function getTalkPage() {
3673 $title = $this->getUserPage();
3674 return $title->getTalkPage();
3678 * Determine whether the user is a newbie. Newbies are either
3679 * anonymous IPs, or the most recently created accounts.
3680 * @return bool
3682 public function isNewbie() {
3683 return !$this->isAllowed( 'autoconfirmed' );
3687 * Check to see if the given clear-text password is one of the accepted passwords
3688 * @param string $password user password.
3689 * @return boolean: True if the given password is correct, otherwise False.
3691 public function checkPassword( $password ) {
3692 global $wgAuth, $wgLegacyEncoding;
3693 $this->load();
3695 // Even though we stop people from creating passwords that
3696 // are shorter than this, doesn't mean people wont be able
3697 // to. Certain authentication plugins do NOT want to save
3698 // domain passwords in a mysql database, so we should
3699 // check this (in case $wgAuth->strict() is false).
3700 if ( !$this->isValidPassword( $password ) ) {
3701 return false;
3704 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3705 return true;
3706 } elseif ( $wgAuth->strict() ) {
3707 // Auth plugin doesn't allow local authentication
3708 return false;
3709 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3710 // Auth plugin doesn't allow local authentication for this user name
3711 return false;
3713 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
3714 return true;
3715 } elseif ( $wgLegacyEncoding ) {
3716 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3717 // Check for this with iconv
3718 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3719 if ( $cp1252Password != $password
3720 && self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId )
3722 return true;
3725 return false;
3729 * Check if the given clear-text password matches the temporary password
3730 * sent by e-mail for password reset operations.
3732 * @param $plaintext string
3734 * @return boolean: True if matches, false otherwise
3736 public function checkTemporaryPassword( $plaintext ) {
3737 global $wgNewPasswordExpiry;
3739 $this->load();
3740 if ( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) {
3741 if ( is_null( $this->mNewpassTime ) ) {
3742 return true;
3744 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
3745 return ( time() < $expiry );
3746 } else {
3747 return false;
3752 * Alias for getEditToken.
3753 * @deprecated since 1.19, use getEditToken instead.
3755 * @param string|array $salt of Strings Optional function-specific data for hashing
3756 * @param $request WebRequest object to use or null to use $wgRequest
3757 * @return string The new edit token
3759 public function editToken( $salt = '', $request = null ) {
3760 wfDeprecated( __METHOD__, '1.19' );
3761 return $this->getEditToken( $salt, $request );
3765 * Initialize (if necessary) and return a session token value
3766 * which can be used in edit forms to show that the user's
3767 * login credentials aren't being hijacked with a foreign form
3768 * submission.
3770 * @since 1.19
3772 * @param string|array $salt of Strings Optional function-specific data for hashing
3773 * @param $request WebRequest object to use or null to use $wgRequest
3774 * @return string The new edit token
3776 public function getEditToken( $salt = '', $request = null ) {
3777 if ( $request == null ) {
3778 $request = $this->getRequest();
3781 if ( $this->isAnon() ) {
3782 return EDIT_TOKEN_SUFFIX;
3783 } else {
3784 $token = $request->getSessionData( 'wsEditToken' );
3785 if ( $token === null ) {
3786 $token = MWCryptRand::generateHex( 32 );
3787 $request->setSessionData( 'wsEditToken', $token );
3789 if ( is_array( $salt ) ) {
3790 $salt = implode( '|', $salt );
3792 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
3797 * Generate a looking random token for various uses.
3799 * @return string The new random token
3800 * @deprecated since 1.20: Use MWCryptRand for secure purposes or wfRandomString for pseudo-randomness
3802 public static function generateToken() {
3803 return MWCryptRand::generateHex( 32 );
3807 * Check given value against the token value stored in the session.
3808 * A match should confirm that the form was submitted from the
3809 * user's own login session, not a form submission from a third-party
3810 * site.
3812 * @param string $val Input value to compare
3813 * @param string $salt Optional function-specific data for hashing
3814 * @param WebRequest $request Object to use or null to use $wgRequest
3815 * @return boolean: Whether the token matches
3817 public function matchEditToken( $val, $salt = '', $request = null ) {
3818 $sessionToken = $this->getEditToken( $salt, $request );
3819 if ( $val != $sessionToken ) {
3820 wfDebug( "User::matchEditToken: broken session data\n" );
3822 return $val == $sessionToken;
3826 * Check given value against the token value stored in the session,
3827 * ignoring the suffix.
3829 * @param string $val Input value to compare
3830 * @param string $salt Optional function-specific data for hashing
3831 * @param WebRequest $request object to use or null to use $wgRequest
3832 * @return boolean: Whether the token matches
3834 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3835 $sessionToken = $this->getEditToken( $salt, $request );
3836 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3840 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3841 * mail to the user's given address.
3843 * @param string $type message to send, either "created", "changed" or "set"
3844 * @return Status object
3846 public function sendConfirmationMail( $type = 'created' ) {
3847 global $wgLang;
3848 $expiration = null; // gets passed-by-ref and defined in next line.
3849 $token = $this->confirmationToken( $expiration );
3850 $url = $this->confirmationTokenUrl( $token );
3851 $invalidateURL = $this->invalidationTokenUrl( $token );
3852 $this->saveSettings();
3854 if ( $type == 'created' || $type === false ) {
3855 $message = 'confirmemail_body';
3856 } elseif ( $type === true ) {
3857 $message = 'confirmemail_body_changed';
3858 } else {
3859 // Messages: confirmemail_body_changed, confirmemail_body_set
3860 $message = 'confirmemail_body_' . $type;
3863 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3864 wfMessage( $message,
3865 $this->getRequest()->getIP(),
3866 $this->getName(),
3867 $url,
3868 $wgLang->timeanddate( $expiration, false ),
3869 $invalidateURL,
3870 $wgLang->date( $expiration, false ),
3871 $wgLang->time( $expiration, false ) )->text() );
3875 * Send an e-mail to this user's account. Does not check for
3876 * confirmed status or validity.
3878 * @param string $subject Message subject
3879 * @param string $body Message body
3880 * @param string $from Optional From address; if unspecified, default $wgPasswordSender will be used
3881 * @param string $replyto Reply-To address
3882 * @return Status
3884 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3885 if ( is_null( $from ) ) {
3886 global $wgPasswordSender;
3887 $sender = new MailAddress( $wgPasswordSender,
3888 wfMessage( 'emailsender' )->inContentLanguage()->text() );
3889 } else {
3890 $sender = new MailAddress( $from );
3893 $to = new MailAddress( $this );
3894 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
3898 * Generate, store, and return a new e-mail confirmation code.
3899 * A hash (unsalted, since it's used as a key) is stored.
3901 * @note Call saveSettings() after calling this function to commit
3902 * this change to the database.
3904 * @param &$expiration \mixed Accepts the expiration time
3905 * @return string New token
3907 protected function confirmationToken( &$expiration ) {
3908 global $wgUserEmailConfirmationTokenExpiry;
3909 $now = time();
3910 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
3911 $expiration = wfTimestamp( TS_MW, $expires );
3912 $this->load();
3913 $token = MWCryptRand::generateHex( 32 );
3914 $hash = md5( $token );
3915 $this->mEmailToken = $hash;
3916 $this->mEmailTokenExpires = $expiration;
3917 return $token;
3921 * Return a URL the user can use to confirm their email address.
3922 * @param string $token Accepts the email confirmation token
3923 * @return string New token URL
3925 protected function confirmationTokenUrl( $token ) {
3926 return $this->getTokenUrl( 'ConfirmEmail', $token );
3930 * Return a URL the user can use to invalidate their email address.
3931 * @param string $token Accepts the email confirmation token
3932 * @return string New token URL
3934 protected function invalidationTokenUrl( $token ) {
3935 return $this->getTokenUrl( 'InvalidateEmail', $token );
3939 * Internal function to format the e-mail validation/invalidation URLs.
3940 * This uses a quickie hack to use the
3941 * hardcoded English names of the Special: pages, for ASCII safety.
3943 * @note Since these URLs get dropped directly into emails, using the
3944 * short English names avoids insanely long URL-encoded links, which
3945 * also sometimes can get corrupted in some browsers/mailers
3946 * (bug 6957 with Gmail and Internet Explorer).
3948 * @param string $page Special page
3949 * @param string $token Token
3950 * @return string Formatted URL
3952 protected function getTokenUrl( $page, $token ) {
3953 // Hack to bypass localization of 'Special:'
3954 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
3955 return $title->getCanonicalURL();
3959 * Mark the e-mail address confirmed.
3961 * @note Call saveSettings() after calling this function to commit the change.
3963 * @return bool
3965 public function confirmEmail() {
3966 // Check if it's already confirmed, so we don't touch the database
3967 // and fire the ConfirmEmailComplete hook on redundant confirmations.
3968 if ( !$this->isEmailConfirmed() ) {
3969 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3970 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3972 return true;
3976 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3977 * address if it was already confirmed.
3979 * @note Call saveSettings() after calling this function to commit the change.
3980 * @return bool Returns true
3982 public function invalidateEmail() {
3983 $this->load();
3984 $this->mEmailToken = null;
3985 $this->mEmailTokenExpires = null;
3986 $this->setEmailAuthenticationTimestamp( null );
3987 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3988 return true;
3992 * Set the e-mail authentication timestamp.
3993 * @param string $timestamp TS_MW timestamp
3995 public function setEmailAuthenticationTimestamp( $timestamp ) {
3996 $this->load();
3997 $this->mEmailAuthenticated = $timestamp;
3998 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
4002 * Is this user allowed to send e-mails within limits of current
4003 * site configuration?
4004 * @return bool
4006 public function canSendEmail() {
4007 global $wgEnableEmail, $wgEnableUserEmail;
4008 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4009 return false;
4011 $canSend = $this->isEmailConfirmed();
4012 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
4013 return $canSend;
4017 * Is this user allowed to receive e-mails within limits of current
4018 * site configuration?
4019 * @return bool
4021 public function canReceiveEmail() {
4022 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4026 * Is this user's e-mail address valid-looking and confirmed within
4027 * limits of the current site configuration?
4029 * @note If $wgEmailAuthentication is on, this may require the user to have
4030 * confirmed their address by returning a code or using a password
4031 * sent to the address from the wiki.
4033 * @return bool
4035 public function isEmailConfirmed() {
4036 global $wgEmailAuthentication;
4037 $this->load();
4038 $confirmed = true;
4039 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4040 if ( $this->isAnon() ) {
4041 return false;
4043 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4044 return false;
4046 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4047 return false;
4049 return true;
4050 } else {
4051 return $confirmed;
4056 * Check whether there is an outstanding request for e-mail confirmation.
4057 * @return bool
4059 public function isEmailConfirmationPending() {
4060 global $wgEmailAuthentication;
4061 return $wgEmailAuthentication &&
4062 !$this->isEmailConfirmed() &&
4063 $this->mEmailToken &&
4064 $this->mEmailTokenExpires > wfTimestamp();
4068 * Get the timestamp of account creation.
4070 * @return string|bool|null Timestamp of account creation, false for
4071 * non-existent/anonymous user accounts, or null if existing account
4072 * but information is not in database.
4074 public function getRegistration() {
4075 if ( $this->isAnon() ) {
4076 return false;
4078 $this->load();
4079 return $this->mRegistration;
4083 * Get the timestamp of the first edit
4085 * @return string|bool Timestamp of first edit, or false for
4086 * non-existent/anonymous user accounts.
4088 public function getFirstEditTimestamp() {
4089 if ( $this->getId() == 0 ) {
4090 return false; // anons
4092 $dbr = wfGetDB( DB_SLAVE );
4093 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4094 array( 'rev_user' => $this->getId() ),
4095 __METHOD__,
4096 array( 'ORDER BY' => 'rev_timestamp ASC' )
4098 if ( !$time ) {
4099 return false; // no edits
4101 return wfTimestamp( TS_MW, $time );
4105 * Get the permissions associated with a given list of groups
4107 * @param array $groups of Strings List of internal group names
4108 * @return Array of Strings List of permission key names for given groups combined
4110 public static function getGroupPermissions( $groups ) {
4111 global $wgGroupPermissions, $wgRevokePermissions;
4112 $rights = array();
4113 // grant every granted permission first
4114 foreach ( $groups as $group ) {
4115 if ( isset( $wgGroupPermissions[$group] ) ) {
4116 $rights = array_merge( $rights,
4117 // array_filter removes empty items
4118 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4121 // now revoke the revoked permissions
4122 foreach ( $groups as $group ) {
4123 if ( isset( $wgRevokePermissions[$group] ) ) {
4124 $rights = array_diff( $rights,
4125 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4128 return array_unique( $rights );
4132 * Get all the groups who have a given permission
4134 * @param string $role Role to check
4135 * @return Array of Strings List of internal group names with the given permission
4137 public static function getGroupsWithPermission( $role ) {
4138 global $wgGroupPermissions;
4139 $allowedGroups = array();
4140 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4141 if ( self::groupHasPermission( $group, $role ) ) {
4142 $allowedGroups[] = $group;
4145 return $allowedGroups;
4149 * Check, if the given group has the given permission
4151 * If you're wanting to check whether all users have a permission, use
4152 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4153 * from anyone.
4155 * @since 1.21
4156 * @param string $group Group to check
4157 * @param string $role Role to check
4158 * @return bool
4160 public static function groupHasPermission( $group, $role ) {
4161 global $wgGroupPermissions, $wgRevokePermissions;
4162 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4163 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4167 * Check if all users have the given permission
4169 * @since 1.22
4170 * @param string $right Right to check
4171 * @return bool
4173 public static function isEveryoneAllowed( $right ) {
4174 global $wgGroupPermissions, $wgRevokePermissions;
4175 static $cache = array();
4177 // Use the cached results, except in unit tests which rely on
4178 // being able change the permission mid-request
4179 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4180 return $cache[$right];
4183 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
4184 $cache[$right] = false;
4185 return false;
4188 // If it's revoked anywhere, then everyone doesn't have it
4189 foreach ( $wgRevokePermissions as $rights ) {
4190 if ( isset( $rights[$right] ) && $rights[$right] ) {
4191 $cache[$right] = false;
4192 return false;
4196 // Allow extensions (e.g. OAuth) to say false
4197 if ( !wfRunHooks( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4198 $cache[$right] = false;
4199 return false;
4202 $cache[$right] = true;
4203 return true;
4207 * Get the localized descriptive name for a group, if it exists
4209 * @param string $group Internal group name
4210 * @return string Localized descriptive group name
4212 public static function getGroupName( $group ) {
4213 $msg = wfMessage( "group-$group" );
4214 return $msg->isBlank() ? $group : $msg->text();
4218 * Get the localized descriptive name for a member of a group, if it exists
4220 * @param string $group Internal group name
4221 * @param string $username Username for gender (since 1.19)
4222 * @return string Localized name for group member
4224 public static function getGroupMember( $group, $username = '#' ) {
4225 $msg = wfMessage( "group-$group-member", $username );
4226 return $msg->isBlank() ? $group : $msg->text();
4230 * Return the set of defined explicit groups.
4231 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4232 * are not included, as they are defined automatically, not in the database.
4233 * @return Array of internal group names
4235 public static function getAllGroups() {
4236 global $wgGroupPermissions, $wgRevokePermissions;
4237 return array_diff(
4238 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4239 self::getImplicitGroups()
4244 * Get a list of all available permissions.
4245 * @return Array of permission names
4247 public static function getAllRights() {
4248 if ( self::$mAllRights === false ) {
4249 global $wgAvailableRights;
4250 if ( count( $wgAvailableRights ) ) {
4251 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
4252 } else {
4253 self::$mAllRights = self::$mCoreRights;
4255 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
4257 return self::$mAllRights;
4261 * Get a list of implicit groups
4262 * @return Array of Strings Array of internal group names
4264 public static function getImplicitGroups() {
4265 global $wgImplicitGroups;
4266 $groups = $wgImplicitGroups;
4267 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
4268 return $groups;
4272 * Get the title of a page describing a particular group
4274 * @param string $group Internal group name
4275 * @return Title|bool Title of the page if it exists, false otherwise
4277 public static function getGroupPage( $group ) {
4278 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4279 if ( $msg->exists() ) {
4280 $title = Title::newFromText( $msg->text() );
4281 if ( is_object( $title ) ) {
4282 return $title;
4285 return false;
4289 * Create a link to the group in HTML, if available;
4290 * else return the group name.
4292 * @param string $group Internal name of the group
4293 * @param string $text The text of the link
4294 * @return string HTML link to the group
4296 public static function makeGroupLinkHTML( $group, $text = '' ) {
4297 if ( $text == '' ) {
4298 $text = self::getGroupName( $group );
4300 $title = self::getGroupPage( $group );
4301 if ( $title ) {
4302 return Linker::link( $title, htmlspecialchars( $text ) );
4303 } else {
4304 return $text;
4309 * Create a link to the group in Wikitext, if available;
4310 * else return the group name.
4312 * @param string $group Internal name of the group
4313 * @param string $text The text of the link
4314 * @return string Wikilink to the group
4316 public static function makeGroupLinkWiki( $group, $text = '' ) {
4317 if ( $text == '' ) {
4318 $text = self::getGroupName( $group );
4320 $title = self::getGroupPage( $group );
4321 if ( $title ) {
4322 $page = $title->getPrefixedText();
4323 return "[[$page|$text]]";
4324 } else {
4325 return $text;
4330 * Returns an array of the groups that a particular group can add/remove.
4332 * @param string $group the group to check for whether it can add/remove
4333 * @return Array array( 'add' => array( addablegroups ),
4334 * 'remove' => array( removablegroups ),
4335 * 'add-self' => array( addablegroups to self),
4336 * 'remove-self' => array( removable groups from self) )
4338 public static function changeableByGroup( $group ) {
4339 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4341 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
4342 if ( empty( $wgAddGroups[$group] ) ) {
4343 // Don't add anything to $groups
4344 } elseif ( $wgAddGroups[$group] === true ) {
4345 // You get everything
4346 $groups['add'] = self::getAllGroups();
4347 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4348 $groups['add'] = $wgAddGroups[$group];
4351 // Same thing for remove
4352 if ( empty( $wgRemoveGroups[$group] ) ) {
4353 } elseif ( $wgRemoveGroups[$group] === true ) {
4354 $groups['remove'] = self::getAllGroups();
4355 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4356 $groups['remove'] = $wgRemoveGroups[$group];
4359 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4360 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4361 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4362 if ( is_int( $key ) ) {
4363 $wgGroupsAddToSelf['user'][] = $value;
4368 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4369 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4370 if ( is_int( $key ) ) {
4371 $wgGroupsRemoveFromSelf['user'][] = $value;
4376 // Now figure out what groups the user can add to him/herself
4377 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4378 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4379 // No idea WHY this would be used, but it's there
4380 $groups['add-self'] = User::getAllGroups();
4381 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4382 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4385 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4386 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4387 $groups['remove-self'] = User::getAllGroups();
4388 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4389 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4392 return $groups;
4396 * Returns an array of groups that this user can add and remove
4397 * @return Array array( 'add' => array( addablegroups ),
4398 * 'remove' => array( removablegroups ),
4399 * 'add-self' => array( addablegroups to self),
4400 * 'remove-self' => array( removable groups from self) )
4402 public function changeableGroups() {
4403 if ( $this->isAllowed( 'userrights' ) ) {
4404 // This group gives the right to modify everything (reverse-
4405 // compatibility with old "userrights lets you change
4406 // everything")
4407 // Using array_merge to make the groups reindexed
4408 $all = array_merge( User::getAllGroups() );
4409 return array(
4410 'add' => $all,
4411 'remove' => $all,
4412 'add-self' => array(),
4413 'remove-self' => array()
4417 // Okay, it's not so simple, we will have to go through the arrays
4418 $groups = array(
4419 'add' => array(),
4420 'remove' => array(),
4421 'add-self' => array(),
4422 'remove-self' => array()
4424 $addergroups = $this->getEffectiveGroups();
4426 foreach ( $addergroups as $addergroup ) {
4427 $groups = array_merge_recursive(
4428 $groups, $this->changeableByGroup( $addergroup )
4430 $groups['add'] = array_unique( $groups['add'] );
4431 $groups['remove'] = array_unique( $groups['remove'] );
4432 $groups['add-self'] = array_unique( $groups['add-self'] );
4433 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4435 return $groups;
4439 * Increment the user's edit-count field.
4440 * Will have no effect for anonymous users.
4442 public function incEditCount() {
4443 if ( !$this->isAnon() ) {
4444 $dbw = wfGetDB( DB_MASTER );
4445 $dbw->update(
4446 'user',
4447 array( 'user_editcount=user_editcount+1' ),
4448 array( 'user_id' => $this->getId() ),
4449 __METHOD__
4452 // Lazy initialization check...
4453 if ( $dbw->affectedRows() == 0 ) {
4454 // Now here's a goddamn hack...
4455 $dbr = wfGetDB( DB_SLAVE );
4456 if ( $dbr !== $dbw ) {
4457 // If we actually have a slave server, the count is
4458 // at least one behind because the current transaction
4459 // has not been committed and replicated.
4460 $this->initEditCount( 1 );
4461 } else {
4462 // But if DB_SLAVE is selecting the master, then the
4463 // count we just read includes the revision that was
4464 // just added in the working transaction.
4465 $this->initEditCount();
4469 // edit count in user cache too
4470 $this->invalidateCache();
4474 * Initialize user_editcount from data out of the revision table
4476 * @param $add Integer Edits to add to the count from the revision table
4477 * @return integer Number of edits
4479 protected function initEditCount( $add = 0 ) {
4480 // Pull from a slave to be less cruel to servers
4481 // Accuracy isn't the point anyway here
4482 $dbr = wfGetDB( DB_SLAVE );
4483 $count = (int)$dbr->selectField(
4484 'revision',
4485 'COUNT(rev_user)',
4486 array( 'rev_user' => $this->getId() ),
4487 __METHOD__
4489 $count = $count + $add;
4491 $dbw = wfGetDB( DB_MASTER );
4492 $dbw->update(
4493 'user',
4494 array( 'user_editcount' => $count ),
4495 array( 'user_id' => $this->getId() ),
4496 __METHOD__
4499 return $count;
4503 * Get the description of a given right
4505 * @param string $right Right to query
4506 * @return string Localized description of the right
4508 public static function getRightDescription( $right ) {
4509 $key = "right-$right";
4510 $msg = wfMessage( $key );
4511 return $msg->isBlank() ? $right : $msg->text();
4515 * Make an old-style password hash
4517 * @param string $password Plain-text password
4518 * @param string $userId User ID
4519 * @return string Password hash
4521 public static function oldCrypt( $password, $userId ) {
4522 global $wgPasswordSalt;
4523 if ( $wgPasswordSalt ) {
4524 return md5( $userId . '-' . md5( $password ) );
4525 } else {
4526 return md5( $password );
4531 * Make a new-style password hash
4533 * @param string $password Plain-text password
4534 * @param bool|string $salt Optional salt, may be random or the user ID.
4535 * If unspecified or false, will generate one automatically
4536 * @return string Password hash
4538 public static function crypt( $password, $salt = false ) {
4539 global $wgPasswordSalt;
4541 $hash = '';
4542 if ( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
4543 return $hash;
4546 if ( $wgPasswordSalt ) {
4547 if ( $salt === false ) {
4548 $salt = MWCryptRand::generateHex( 8 );
4550 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
4551 } else {
4552 return ':A:' . md5( $password );
4557 * Compare a password hash with a plain-text password. Requires the user
4558 * ID if there's a chance that the hash is an old-style hash.
4560 * @param string $hash Password hash
4561 * @param string $password Plain-text password to compare
4562 * @param string|bool $userId User ID for old-style password salt
4564 * @return boolean
4566 public static function comparePasswords( $hash, $password, $userId = false ) {
4567 $type = substr( $hash, 0, 3 );
4569 $result = false;
4570 if ( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
4571 return $result;
4574 if ( $type == ':A:' ) {
4575 // Unsalted
4576 return md5( $password ) === substr( $hash, 3 );
4577 } elseif ( $type == ':B:' ) {
4578 // Salted
4579 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
4580 return md5( $salt . '-' . md5( $password ) ) === $realHash;
4581 } else {
4582 // Old-style
4583 return self::oldCrypt( $password, $userId ) === $hash;
4588 * Add a newuser log entry for this user.
4589 * Before 1.19 the return value was always true.
4591 * @param string|bool $action account creation type.
4592 * - String, one of the following values:
4593 * - 'create' for an anonymous user creating an account for himself.
4594 * This will force the action's performer to be the created user itself,
4595 * no matter the value of $wgUser
4596 * - 'create2' for a logged in user creating an account for someone else
4597 * - 'byemail' when the created user will receive its password by e-mail
4598 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4599 * - Boolean means whether the account was created by e-mail (deprecated):
4600 * - true will be converted to 'byemail'
4601 * - false will be converted to 'create' if this object is the same as
4602 * $wgUser and to 'create2' otherwise
4604 * @param string $reason user supplied reason
4606 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4608 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4609 global $wgUser, $wgNewUserLog;
4610 if ( empty( $wgNewUserLog ) ) {
4611 return true; // disabled
4614 if ( $action === true ) {
4615 $action = 'byemail';
4616 } elseif ( $action === false ) {
4617 if ( $this->getName() == $wgUser->getName() ) {
4618 $action = 'create';
4619 } else {
4620 $action = 'create2';
4624 if ( $action === 'create' || $action === 'autocreate' ) {
4625 $performer = $this;
4626 } else {
4627 $performer = $wgUser;
4630 $logEntry = new ManualLogEntry( 'newusers', $action );
4631 $logEntry->setPerformer( $performer );
4632 $logEntry->setTarget( $this->getUserPage() );
4633 $logEntry->setComment( $reason );
4634 $logEntry->setParameters( array(
4635 '4::userid' => $this->getId(),
4636 ) );
4637 $logid = $logEntry->insert();
4639 if ( $action !== 'autocreate' ) {
4640 $logEntry->publish( $logid );
4643 return (int)$logid;
4647 * Add an autocreate newuser log entry for this user
4648 * Used by things like CentralAuth and perhaps other authplugins.
4649 * Consider calling addNewUserLogEntry() directly instead.
4651 * @return bool
4653 public function addNewUserLogEntryAutoCreate() {
4654 $this->addNewUserLogEntry( 'autocreate' );
4656 return true;
4660 * Load the user options either from cache, the database or an array
4662 * @param array $data Rows for the current user out of the user_properties table
4664 protected function loadOptions( $data = null ) {
4665 global $wgContLang;
4667 $this->load();
4669 if ( $this->mOptionsLoaded ) {
4670 return;
4673 $this->mOptions = self::getDefaultOptions();
4675 if ( !$this->getId() ) {
4676 // For unlogged-in users, load language/variant options from request.
4677 // There's no need to do it for logged-in users: they can set preferences,
4678 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4679 // so don't override user's choice (especially when the user chooses site default).
4680 $variant = $wgContLang->getDefaultVariant();
4681 $this->mOptions['variant'] = $variant;
4682 $this->mOptions['language'] = $variant;
4683 $this->mOptionsLoaded = true;
4684 return;
4687 // Maybe load from the object
4688 if ( !is_null( $this->mOptionOverrides ) ) {
4689 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4690 foreach ( $this->mOptionOverrides as $key => $value ) {
4691 $this->mOptions[$key] = $value;
4693 } else {
4694 if ( !is_array( $data ) ) {
4695 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4696 // Load from database
4697 $dbr = wfGetDB( DB_SLAVE );
4699 $res = $dbr->select(
4700 'user_properties',
4701 array( 'up_property', 'up_value' ),
4702 array( 'up_user' => $this->getId() ),
4703 __METHOD__
4706 $this->mOptionOverrides = array();
4707 $data = array();
4708 foreach ( $res as $row ) {
4709 $data[$row->up_property] = $row->up_value;
4712 foreach ( $data as $property => $value ) {
4713 $this->mOptionOverrides[$property] = $value;
4714 $this->mOptions[$property] = $value;
4718 $this->mOptionsLoaded = true;
4720 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
4724 * @todo document
4726 protected function saveOptions() {
4727 $this->loadOptions();
4729 // Not using getOptions(), to keep hidden preferences in database
4730 $saveOptions = $this->mOptions;
4732 // Allow hooks to abort, for instance to save to a global profile.
4733 // Reset options to default state before saving.
4734 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4735 return;
4738 $userId = $this->getId();
4739 $insert_rows = array();
4740 foreach ( $saveOptions as $key => $value ) {
4741 // Don't bother storing default values
4742 $defaultOption = self::getDefaultOption( $key );
4743 if ( ( is_null( $defaultOption ) &&
4744 !( $value === false || is_null( $value ) ) ) ||
4745 $value != $defaultOption ) {
4746 $insert_rows[] = array(
4747 'up_user' => $userId,
4748 'up_property' => $key,
4749 'up_value' => $value,
4754 $dbw = wfGetDB( DB_MASTER );
4755 $hasRows = $dbw->selectField( 'user_properties', '1',
4756 array( 'up_user' => $userId ), __METHOD__ );
4758 if ( $hasRows ) {
4759 // Only do this delete if there is something there. A very large portion of
4760 // calls to this function are for setting 'rememberpassword' for new accounts.
4761 // Doing this delete for new accounts with no rows in the table rougly causes
4762 // gap locks on [max user ID,+infinity) which causes high contention since many
4763 // updates will pile up on each other since they are for higher (newer) user IDs.
4764 $dbw->delete( 'user_properties', array( 'up_user' => $userId ), __METHOD__ );
4766 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, array( 'IGNORE' ) );
4770 * Provide an array of HTML5 attributes to put on an input element
4771 * intended for the user to enter a new password. This may include
4772 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4774 * Do *not* use this when asking the user to enter his current password!
4775 * Regardless of configuration, users may have invalid passwords for whatever
4776 * reason (e.g., they were set before requirements were tightened up).
4777 * Only use it when asking for a new password, like on account creation or
4778 * ResetPass.
4780 * Obviously, you still need to do server-side checking.
4782 * NOTE: A combination of bugs in various browsers means that this function
4783 * actually just returns array() unconditionally at the moment. May as
4784 * well keep it around for when the browser bugs get fixed, though.
4786 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4788 * @return array Array of HTML attributes suitable for feeding to
4789 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4790 * That will get confused by the boolean attribute syntax used.)
4792 public static function passwordChangeInputAttribs() {
4793 global $wgMinimalPasswordLength;
4795 if ( $wgMinimalPasswordLength == 0 ) {
4796 return array();
4799 # Note that the pattern requirement will always be satisfied if the
4800 # input is empty, so we need required in all cases.
4802 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4803 # if e-mail confirmation is being used. Since HTML5 input validation
4804 # is b0rked anyway in some browsers, just return nothing. When it's
4805 # re-enabled, fix this code to not output required for e-mail
4806 # registration.
4807 #$ret = array( 'required' );
4808 $ret = array();
4810 # We can't actually do this right now, because Opera 9.6 will print out
4811 # the entered password visibly in its error message! When other
4812 # browsers add support for this attribute, or Opera fixes its support,
4813 # we can add support with a version check to avoid doing this on Opera
4814 # versions where it will be a problem. Reported to Opera as
4815 # DSK-262266, but they don't have a public bug tracker for us to follow.
4817 if ( $wgMinimalPasswordLength > 1 ) {
4818 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4819 $ret['title'] = wfMessage( 'passwordtooshort' )
4820 ->numParams( $wgMinimalPasswordLength )->text();
4824 return $ret;
4828 * Return the list of user fields that should be selected to create
4829 * a new user object.
4830 * @return array
4832 public static function selectFields() {
4833 return array(
4834 'user_id',
4835 'user_name',
4836 'user_real_name',
4837 'user_password',
4838 'user_newpassword',
4839 'user_newpass_time',
4840 'user_email',
4841 'user_touched',
4842 'user_token',
4843 'user_email_authenticated',
4844 'user_email_token',
4845 'user_email_token_expires',
4846 'user_password_expires',
4847 'user_registration',
4848 'user_editcount',
4853 * Factory function for fatal permission-denied errors
4855 * @since 1.22
4856 * @param string $permission User right required
4857 * @return Status
4859 static function newFatalPermissionDeniedStatus( $permission ) {
4860 global $wgLang;
4862 $groups = array_map(
4863 array( 'User', 'makeGroupLinkWiki' ),
4864 User::getGroupsWithPermission( $permission )
4867 if ( $groups ) {
4868 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
4869 } else {
4870 return Status::newFatal( 'badaccess-group0' );