Merge "Localisation updates from https://translatewiki.net."
[mediawiki.git] / includes / User.php
blob6b42994ef7d90c7bcbcfa978edc88409a94598b8
1 <?php
2 /**
3 * Implements the User class for the %MediaWiki software.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
23 /**
24 * String Some punctuation to prevent editing from broken text-mangling proxies.
25 * @ingroup Constants
27 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
29 /**
30 * The User object encapsulates all of the user-specific settings (user_id,
31 * name, rights, password, email address, options, last login time). Client
32 * classes use the getXXX() functions to access these fields. These functions
33 * do all the work of determining whether the user is logged in,
34 * whether the requested option can be satisfied from cookies or
35 * whether a database query is needed. Most of the settings needed
36 * for rendering normal pages are set in the cookie to minimize use
37 * of the database.
39 class User implements IDBAccessObject {
40 /**
41 * @const int Number of characters in user_token field.
43 const TOKEN_LENGTH = 32;
45 /**
46 * Global constant made accessible as class constants so that autoloader
47 * magic can be used.
49 const EDIT_TOKEN_SUFFIX = EDIT_TOKEN_SUFFIX;
51 /**
52 * @const int Serialized record version.
54 const VERSION = 10;
56 /**
57 * Maximum items in $mWatchedItems
59 const MAX_WATCHED_ITEMS_CACHE = 100;
61 /**
62 * @var PasswordFactory Lazily loaded factory object for passwords
64 private static $mPasswordFactory = null;
66 /**
67 * Array of Strings List of member variables which are saved to the
68 * shared cache (memcached). Any operation which changes the
69 * corresponding database fields must call a cache-clearing function.
70 * @showinitializer
72 protected static $mCacheVars = array(
73 // user table
74 'mId',
75 'mName',
76 'mRealName',
77 'mEmail',
78 'mTouched',
79 'mToken',
80 'mEmailAuthenticated',
81 'mEmailToken',
82 'mEmailTokenExpires',
83 'mRegistration',
84 'mEditCount',
85 // user_groups table
86 'mGroups',
87 // user_properties table
88 'mOptionOverrides',
91 /**
92 * Array of Strings Core rights.
93 * Each of these should have a corresponding message of the form
94 * "right-$right".
95 * @showinitializer
97 protected static $mCoreRights = array(
98 'apihighlimits',
99 'autoconfirmed',
100 'autopatrol',
101 'bigdelete',
102 'block',
103 'blockemail',
104 'bot',
105 'browsearchive',
106 'createaccount',
107 'createpage',
108 'createtalk',
109 'delete',
110 'deletedhistory',
111 'deletedtext',
112 'deletelogentry',
113 'deleterevision',
114 'edit',
115 'editinterface',
116 'editprotected',
117 'editmyoptions',
118 'editmyprivateinfo',
119 'editmyusercss',
120 'editmyuserjs',
121 'editmywatchlist',
122 'editsemiprotected',
123 'editusercssjs', #deprecated
124 'editusercss',
125 'edituserjs',
126 'hideuser',
127 'import',
128 'importupload',
129 'ipblock-exempt',
130 'markbotedits',
131 'mergehistory',
132 'minoredit',
133 'move',
134 'movefile',
135 'move-categorypages',
136 'move-rootuserpages',
137 'move-subpages',
138 'nominornewtalk',
139 'noratelimit',
140 'override-export-depth',
141 'pagelang',
142 'passwordreset',
143 'patrol',
144 'patrolmarks',
145 'protect',
146 'proxyunbannable',
147 'purge',
148 'read',
149 'reupload',
150 'reupload-own',
151 'reupload-shared',
152 'rollback',
153 'sendemail',
154 'siteadmin',
155 'suppressionlog',
156 'suppressredirect',
157 'suppressrevision',
158 'unblockself',
159 'undelete',
160 'unwatchedpages',
161 'upload',
162 'upload_by_url',
163 'userrights',
164 'userrights-interwiki',
165 'viewmyprivateinfo',
166 'viewmywatchlist',
167 'viewsuppressed',
168 'writeapi',
172 * String Cached results of getAllRights()
174 protected static $mAllRights = false;
176 /** @name Cache variables */
177 //@{
178 public $mId;
180 public $mName;
182 public $mRealName;
185 * @todo Make this actually private
186 * @private
188 public $mPassword;
191 * @todo Make this actually private
192 * @private
194 public $mNewpassword;
196 public $mNewpassTime;
198 public $mEmail;
200 public $mTouched;
202 protected $mToken;
204 public $mEmailAuthenticated;
206 protected $mEmailToken;
208 protected $mEmailTokenExpires;
210 protected $mRegistration;
212 protected $mEditCount;
214 public $mGroups;
216 protected $mOptionOverrides;
218 protected $mPasswordExpires;
219 //@}
222 * Bool Whether the cache variables have been loaded.
224 //@{
225 public $mOptionsLoaded;
228 * Array with already loaded items or true if all items have been loaded.
230 protected $mLoadedItems = array();
231 //@}
234 * String Initialization data source if mLoadedItems!==true. May be one of:
235 * - 'defaults' anonymous user initialised from class defaults
236 * - 'name' initialise from mName
237 * - 'id' initialise from mId
238 * - 'session' log in from cookies or session if possible
240 * Use the User::newFrom*() family of functions to set this.
242 public $mFrom;
245 * Lazy-initialized variables, invalidated with clearInstanceCache
247 protected $mNewtalk;
249 protected $mDatePreference;
251 public $mBlockedby;
253 protected $mHash;
255 public $mRights;
257 protected $mBlockreason;
259 protected $mEffectiveGroups;
261 protected $mImplicitGroups;
263 protected $mFormerGroups;
265 protected $mBlockedGlobally;
267 protected $mLocked;
269 public $mHideName;
271 public $mOptions;
274 * @var WebRequest
276 private $mRequest;
278 /** @var Block */
279 public $mBlock;
281 /** @var bool */
282 protected $mAllowUsertalk;
284 /** @var Block */
285 private $mBlockedFromCreateAccount = false;
287 /** @var array */
288 private $mWatchedItems = array();
290 public static $idCacheByName = array();
293 * Lightweight constructor for an anonymous user.
294 * Use the User::newFrom* factory functions for other kinds of users.
296 * @see newFromName()
297 * @see newFromId()
298 * @see newFromConfirmationCode()
299 * @see newFromSession()
300 * @see newFromRow()
302 public function __construct() {
303 $this->clearInstanceCache( 'defaults' );
307 * @return string
309 public function __toString() {
310 return $this->getName();
314 * Load the user table data for this object from the source given by mFrom.
316 public function load() {
317 if ( $this->mLoadedItems === true ) {
318 return;
320 wfProfileIn( __METHOD__ );
322 // Set it now to avoid infinite recursion in accessors
323 $this->mLoadedItems = true;
325 switch ( $this->mFrom ) {
326 case 'defaults':
327 $this->loadDefaults();
328 break;
329 case 'name':
330 $this->mId = self::idFromName( $this->mName );
331 if ( !$this->mId ) {
332 // Nonexistent user placeholder object
333 $this->loadDefaults( $this->mName );
334 } else {
335 $this->loadFromId();
337 break;
338 case 'id':
339 $this->loadFromId();
340 break;
341 case 'session':
342 if ( !$this->loadFromSession() ) {
343 // Loading from session failed. Load defaults.
344 $this->loadDefaults();
346 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
347 break;
348 default:
349 wfProfileOut( __METHOD__ );
350 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
352 wfProfileOut( __METHOD__ );
356 * Load user table data, given mId has already been set.
357 * @return bool False if the ID does not exist, true otherwise
359 public function loadFromId() {
360 global $wgMemc;
361 if ( $this->mId == 0 ) {
362 $this->loadDefaults();
363 return false;
366 // Try cache
367 $key = wfMemcKey( 'user', 'id', $this->mId );
368 $data = $wgMemc->get( $key );
369 if ( !is_array( $data ) || $data['mVersion'] != self::VERSION ) {
370 // Object is expired, load from DB
371 $data = false;
374 if ( !$data ) {
375 wfDebug( "User: cache miss for user {$this->mId}\n" );
376 // Load from DB
377 if ( !$this->loadFromDatabase() ) {
378 // Can't load from ID, user is anonymous
379 return false;
381 $this->saveToCache();
382 } else {
383 wfDebug( "User: got user {$this->mId} from cache\n" );
384 // Restore from cache
385 foreach ( self::$mCacheVars as $name ) {
386 $this->$name = $data[$name];
390 $this->mLoadedItems = true;
392 return true;
396 * Save user data to the shared cache
398 public function saveToCache() {
399 $this->load();
400 $this->loadGroups();
401 $this->loadOptions();
402 if ( $this->isAnon() ) {
403 // Anonymous users are uncached
404 return;
406 $data = array();
407 foreach ( self::$mCacheVars as $name ) {
408 $data[$name] = $this->$name;
410 $data['mVersion'] = self::VERSION;
411 $key = wfMemcKey( 'user', 'id', $this->mId );
412 global $wgMemc;
413 $wgMemc->set( $key, $data );
416 /** @name newFrom*() static factory methods */
417 //@{
420 * Static factory method for creation from username.
422 * This is slightly less efficient than newFromId(), so use newFromId() if
423 * you have both an ID and a name handy.
425 * @param string $name Username, validated by Title::newFromText()
426 * @param string|bool $validate Validate username. Takes the same parameters as
427 * User::getCanonicalName(), except that true is accepted as an alias
428 * for 'valid', for BC.
430 * @return User|bool User object, or false if the username is invalid
431 * (e.g. if it contains illegal characters or is an IP address). If the
432 * username is not present in the database, the result will be a user object
433 * with a name, zero user ID and default settings.
435 public static function newFromName( $name, $validate = 'valid' ) {
436 if ( $validate === true ) {
437 $validate = 'valid';
439 $name = self::getCanonicalName( $name, $validate );
440 if ( $name === false ) {
441 return false;
442 } else {
443 // Create unloaded user object
444 $u = new User;
445 $u->mName = $name;
446 $u->mFrom = 'name';
447 $u->setItemLoaded( 'name' );
448 return $u;
453 * Static factory method for creation from a given user ID.
455 * @param int $id Valid user ID
456 * @return User The corresponding User object
458 public static function newFromId( $id ) {
459 $u = new User;
460 $u->mId = $id;
461 $u->mFrom = 'id';
462 $u->setItemLoaded( 'id' );
463 return $u;
467 * Factory method to fetch whichever user has a given email confirmation code.
468 * This code is generated when an account is created or its e-mail address
469 * has changed.
471 * If the code is invalid or has expired, returns NULL.
473 * @param string $code Confirmation code
474 * @return User|null
476 public static function newFromConfirmationCode( $code ) {
477 $dbr = wfGetDB( DB_SLAVE );
478 $id = $dbr->selectField( 'user', 'user_id', array(
479 'user_email_token' => md5( $code ),
480 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
481 ) );
482 if ( $id !== false ) {
483 return User::newFromId( $id );
484 } else {
485 return null;
490 * Create a new user object using data from session or cookies. If the
491 * login credentials are invalid, the result is an anonymous user.
493 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
494 * @return User
496 public static function newFromSession( WebRequest $request = null ) {
497 $user = new User;
498 $user->mFrom = 'session';
499 $user->mRequest = $request;
500 return $user;
504 * Create a new user object from a user row.
505 * The row should have the following fields from the user table in it:
506 * - either user_name or user_id to load further data if needed (or both)
507 * - user_real_name
508 * - all other fields (email, password, etc.)
509 * It is useless to provide the remaining fields if either user_id,
510 * user_name and user_real_name are not provided because the whole row
511 * will be loaded once more from the database when accessing them.
513 * @param stdClass $row A row from the user table
514 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
515 * @return User
517 public static function newFromRow( $row, $data = null ) {
518 $user = new User;
519 $user->loadFromRow( $row, $data );
520 return $user;
523 //@}
526 * Get the username corresponding to a given user ID
527 * @param int $id User ID
528 * @return string|bool The corresponding username
530 public static function whoIs( $id ) {
531 return UserCache::singleton()->getProp( $id, 'name' );
535 * Get the real name of a user given their user ID
537 * @param int $id User ID
538 * @return string|bool The corresponding user's real name
540 public static function whoIsReal( $id ) {
541 return UserCache::singleton()->getProp( $id, 'real_name' );
545 * Get database id given a user name
546 * @param string $name Username
547 * @return int|null The corresponding user's ID, or null if user is nonexistent
549 public static function idFromName( $name ) {
550 $nt = Title::makeTitleSafe( NS_USER, $name );
551 if ( is_null( $nt ) ) {
552 // Illegal name
553 return null;
556 if ( isset( self::$idCacheByName[$name] ) ) {
557 return self::$idCacheByName[$name];
560 $dbr = wfGetDB( DB_SLAVE );
561 $s = $dbr->selectRow(
562 'user',
563 array( 'user_id' ),
564 array( 'user_name' => $nt->getText() ),
565 __METHOD__
568 if ( $s === false ) {
569 $result = null;
570 } else {
571 $result = $s->user_id;
574 self::$idCacheByName[$name] = $result;
576 if ( count( self::$idCacheByName ) > 1000 ) {
577 self::$idCacheByName = array();
580 return $result;
584 * Reset the cache used in idFromName(). For use in tests.
586 public static function resetIdByNameCache() {
587 self::$idCacheByName = array();
591 * Does the string match an anonymous IPv4 address?
593 * This function exists for username validation, in order to reject
594 * usernames which are similar in form to IP addresses. Strings such
595 * as 300.300.300.300 will return true because it looks like an IP
596 * address, despite not being strictly valid.
598 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
599 * address because the usemod software would "cloak" anonymous IP
600 * addresses like this, if we allowed accounts like this to be created
601 * new users could get the old edits of these anonymous users.
603 * @param string $name Name to match
604 * @return bool
606 public static function isIP( $name ) {
607 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
608 || IP::isIPv6( $name );
612 * Is the input a valid username?
614 * Checks if the input is a valid username, we don't want an empty string,
615 * an IP address, anything that contains slashes (would mess up subpages),
616 * is longer than the maximum allowed username size or doesn't begin with
617 * a capital letter.
619 * @param string $name Name to match
620 * @return bool
622 public static function isValidUserName( $name ) {
623 global $wgContLang, $wgMaxNameChars;
625 if ( $name == ''
626 || User::isIP( $name )
627 || strpos( $name, '/' ) !== false
628 || strlen( $name ) > $wgMaxNameChars
629 || $name != $wgContLang->ucfirst( $name ) ) {
630 wfDebugLog( 'username', __METHOD__ .
631 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
632 return false;
635 // Ensure that the name can't be misresolved as a different title,
636 // such as with extra namespace keys at the start.
637 $parsed = Title::newFromText( $name );
638 if ( is_null( $parsed )
639 || $parsed->getNamespace()
640 || strcmp( $name, $parsed->getPrefixedText() ) ) {
641 wfDebugLog( 'username', __METHOD__ .
642 ": '$name' invalid due to ambiguous prefixes" );
643 return false;
646 // Check an additional blacklist of troublemaker characters.
647 // Should these be merged into the title char list?
648 $unicodeBlacklist = '/[' .
649 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
650 '\x{00a0}' . # non-breaking space
651 '\x{2000}-\x{200f}' . # various whitespace
652 '\x{2028}-\x{202f}' . # breaks and control chars
653 '\x{3000}' . # ideographic space
654 '\x{e000}-\x{f8ff}' . # private use
655 ']/u';
656 if ( preg_match( $unicodeBlacklist, $name ) ) {
657 wfDebugLog( 'username', __METHOD__ .
658 ": '$name' invalid due to blacklisted characters" );
659 return false;
662 return true;
666 * Usernames which fail to pass this function will be blocked
667 * from user login and new account registrations, but may be used
668 * internally by batch processes.
670 * If an account already exists in this form, login will be blocked
671 * by a failure to pass this function.
673 * @param string $name Name to match
674 * @return bool
676 public static function isUsableName( $name ) {
677 global $wgReservedUsernames;
678 // Must be a valid username, obviously ;)
679 if ( !self::isValidUserName( $name ) ) {
680 return false;
683 static $reservedUsernames = false;
684 if ( !$reservedUsernames ) {
685 $reservedUsernames = $wgReservedUsernames;
686 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
689 // Certain names may be reserved for batch processes.
690 foreach ( $reservedUsernames as $reserved ) {
691 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
692 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
694 if ( $reserved == $name ) {
695 return false;
698 return true;
702 * Usernames which fail to pass this function will be blocked
703 * from new account registrations, but may be used internally
704 * either by batch processes or by user accounts which have
705 * already been created.
707 * Additional blacklisting may be added here rather than in
708 * isValidUserName() to avoid disrupting existing accounts.
710 * @param string $name String to match
711 * @return bool
713 public static function isCreatableName( $name ) {
714 global $wgInvalidUsernameCharacters;
716 // Ensure that the username isn't longer than 235 bytes, so that
717 // (at least for the builtin skins) user javascript and css files
718 // will work. (bug 23080)
719 if ( strlen( $name ) > 235 ) {
720 wfDebugLog( 'username', __METHOD__ .
721 ": '$name' invalid due to length" );
722 return false;
725 // Preg yells if you try to give it an empty string
726 if ( $wgInvalidUsernameCharacters !== '' ) {
727 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
728 wfDebugLog( 'username', __METHOD__ .
729 ": '$name' invalid due to wgInvalidUsernameCharacters" );
730 return false;
734 return self::isUsableName( $name );
738 * Is the input a valid password for this user?
740 * @param string $password Desired password
741 * @return bool
743 public function isValidPassword( $password ) {
744 //simple boolean wrapper for getPasswordValidity
745 return $this->getPasswordValidity( $password ) === true;
750 * Given unvalidated password input, return error message on failure.
752 * @param string $password Desired password
753 * @return bool|string|array True on success, string or array of error message on failure
755 public function getPasswordValidity( $password ) {
756 $result = $this->checkPasswordValidity( $password );
757 if ( $result->isGood() ) {
758 return true;
759 } else {
760 $messages = array();
761 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
762 $messages[] = $error['message'];
764 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
765 $messages[] = $warning['message'];
767 if ( count( $messages ) === 1 ) {
768 return $messages[0];
770 return $messages;
775 * Check if this is a valid password for this user. Status will be good if
776 * the password is valid, or have an array of error messages if not.
778 * @param string $password Desired password
779 * @return Status
780 * @since 1.23
782 public function checkPasswordValidity( $password ) {
783 global $wgMinimalPasswordLength, $wgContLang;
785 static $blockedLogins = array(
786 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
787 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
790 $status = Status::newGood();
792 $result = false; //init $result to false for the internal checks
794 if ( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) ) {
795 $status->error( $result );
796 return $status;
799 if ( $result === false ) {
800 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
801 $status->error( 'passwordtooshort', $wgMinimalPasswordLength );
802 return $status;
803 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName ) ) {
804 $status->error( 'password-name-match' );
805 return $status;
806 } elseif ( isset( $blockedLogins[$this->getName()] )
807 && $password == $blockedLogins[$this->getName()]
809 $status->error( 'password-login-forbidden' );
810 return $status;
811 } else {
812 //it seems weird returning a Good status here, but this is because of the
813 //initialization of $result to false above. If the hook is never run or it
814 //doesn't modify $result, then we will likely get down into this if with
815 //a valid password.
816 return $status;
818 } elseif ( $result === true ) {
819 return $status;
820 } else {
821 $status->error( $result );
822 return $status; //the isValidPassword hook set a string $result and returned true
827 * Expire a user's password
828 * @since 1.23
829 * @param int $ts Optional timestamp to convert, default 0 for the current time
831 public function expirePassword( $ts = 0 ) {
832 $this->loadPasswords();
833 $timestamp = wfTimestamp( TS_MW, $ts );
834 $this->mPasswordExpires = $timestamp;
835 $this->saveSettings();
839 * Clear the password expiration for a user
840 * @since 1.23
841 * @param bool $load Ensure user object is loaded first
843 public function resetPasswordExpiration( $load = true ) {
844 global $wgPasswordExpirationDays;
845 if ( $load ) {
846 $this->load();
848 $newExpire = null;
849 if ( $wgPasswordExpirationDays ) {
850 $newExpire = wfTimestamp(
851 TS_MW,
852 time() + ( $wgPasswordExpirationDays * 24 * 3600 )
855 // Give extensions a chance to force an expiration
856 wfRunHooks( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
857 $this->mPasswordExpires = $newExpire;
861 * Check if the user's password is expired.
862 * TODO: Put this and password length into a PasswordPolicy object
863 * @since 1.23
864 * @return string|bool The expiration type, or false if not expired
865 * hard: A password change is required to login
866 * soft: Allow login, but encourage password change
867 * false: Password is not expired
869 public function getPasswordExpired() {
870 global $wgPasswordExpireGrace;
871 $expired = false;
872 $now = wfTimestamp();
873 $expiration = $this->getPasswordExpireDate();
874 $expUnix = wfTimestamp( TS_UNIX, $expiration );
875 if ( $expiration !== null && $expUnix < $now ) {
876 $expired = ( $expUnix + $wgPasswordExpireGrace < $now ) ? 'hard' : 'soft';
878 return $expired;
882 * Get this user's password expiration date. Since this may be using
883 * the cached User object, we assume that whatever mechanism is setting
884 * the expiration date is also expiring the User cache.
885 * @since 1.23
886 * @return string|bool The datestamp of the expiration, or null if not set
888 public function getPasswordExpireDate() {
889 $this->load();
890 return $this->mPasswordExpires;
894 * Given unvalidated user input, return a canonical username, or false if
895 * the username is invalid.
896 * @param string $name User input
897 * @param string|bool $validate Type of validation to use:
898 * - false No validation
899 * - 'valid' Valid for batch processes
900 * - 'usable' Valid for batch processes and login
901 * - 'creatable' Valid for batch processes, login and account creation
903 * @throws MWException
904 * @return bool|string
906 public static function getCanonicalName( $name, $validate = 'valid' ) {
907 // Force usernames to capital
908 global $wgContLang;
909 $name = $wgContLang->ucfirst( $name );
911 # Reject names containing '#'; these will be cleaned up
912 # with title normalisation, but then it's too late to
913 # check elsewhere
914 if ( strpos( $name, '#' ) !== false ) {
915 return false;
918 // Clean up name according to title rules,
919 // but only when validation is requested (bug 12654)
920 $t = ( $validate !== false ) ?
921 Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
922 // Check for invalid titles
923 if ( is_null( $t ) ) {
924 return false;
927 // Reject various classes of invalid names
928 global $wgAuth;
929 $name = $wgAuth->getCanonicalName( $t->getText() );
931 switch ( $validate ) {
932 case false:
933 break;
934 case 'valid':
935 if ( !User::isValidUserName( $name ) ) {
936 $name = false;
938 break;
939 case 'usable':
940 if ( !User::isUsableName( $name ) ) {
941 $name = false;
943 break;
944 case 'creatable':
945 if ( !User::isCreatableName( $name ) ) {
946 $name = false;
948 break;
949 default:
950 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__ );
952 return $name;
956 * Count the number of edits of a user
958 * @param int $uid User ID to check
959 * @return int The user's edit count
961 * @deprecated since 1.21 in favour of User::getEditCount
963 public static function edits( $uid ) {
964 wfDeprecated( __METHOD__, '1.21' );
965 $user = self::newFromId( $uid );
966 return $user->getEditCount();
970 * Return a random password.
972 * @return string New random password
974 public static function randomPassword() {
975 global $wgMinimalPasswordLength;
976 // Decide the final password length based on our min password length,
977 // stopping at a minimum of 10 chars.
978 $length = max( 10, $wgMinimalPasswordLength );
979 // Multiply by 1.25 to get the number of hex characters we need
980 $length = $length * 1.25;
981 // Generate random hex chars
982 $hex = MWCryptRand::generateHex( $length );
983 // Convert from base 16 to base 32 to get a proper password like string
984 return wfBaseConvert( $hex, 16, 32 );
988 * Set cached properties to default.
990 * @note This no longer clears uncached lazy-initialised properties;
991 * the constructor does that instead.
993 * @param string|bool $name
995 public function loadDefaults( $name = false ) {
996 wfProfileIn( __METHOD__ );
998 $passwordFactory = self::getPasswordFactory();
1000 $this->mId = 0;
1001 $this->mName = $name;
1002 $this->mRealName = '';
1003 $this->mPassword = $passwordFactory->newFromCiphertext( null );
1004 $this->mNewpassword = $passwordFactory->newFromCiphertext( null );
1005 $this->mNewpassTime = null;
1006 $this->mEmail = '';
1007 $this->mOptionOverrides = null;
1008 $this->mOptionsLoaded = false;
1010 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1011 if ( $loggedOut !== null ) {
1012 $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
1013 } else {
1014 $this->mTouched = '1'; # Allow any pages to be cached
1017 $this->mToken = null; // Don't run cryptographic functions till we need a token
1018 $this->mEmailAuthenticated = null;
1019 $this->mEmailToken = '';
1020 $this->mEmailTokenExpires = null;
1021 $this->mPasswordExpires = null;
1022 $this->resetPasswordExpiration( false );
1023 $this->mRegistration = wfTimestamp( TS_MW );
1024 $this->mGroups = array();
1026 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
1028 wfProfileOut( __METHOD__ );
1032 * Return whether an item has been loaded.
1034 * @param string $item Item to check. Current possibilities:
1035 * - id
1036 * - name
1037 * - realname
1038 * @param string $all 'all' to check if the whole object has been loaded
1039 * or any other string to check if only the item is available (e.g.
1040 * for optimisation)
1041 * @return bool
1043 public function isItemLoaded( $item, $all = 'all' ) {
1044 return ( $this->mLoadedItems === true && $all === 'all' ) ||
1045 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
1049 * Set that an item has been loaded
1051 * @param string $item
1053 protected function setItemLoaded( $item ) {
1054 if ( is_array( $this->mLoadedItems ) ) {
1055 $this->mLoadedItems[$item] = true;
1060 * Load user data from the session or login cookie.
1061 * @return bool True if the user is logged in, false otherwise.
1063 private function loadFromSession() {
1064 $result = null;
1065 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
1066 if ( $result !== null ) {
1067 return $result;
1070 $request = $this->getRequest();
1072 $cookieId = $request->getCookie( 'UserID' );
1073 $sessId = $request->getSessionData( 'wsUserID' );
1075 if ( $cookieId !== null ) {
1076 $sId = intval( $cookieId );
1077 if ( $sessId !== null && $cookieId != $sessId ) {
1078 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1079 cookie user ID ($sId) don't match!" );
1080 return false;
1082 $request->setSessionData( 'wsUserID', $sId );
1083 } elseif ( $sessId !== null && $sessId != 0 ) {
1084 $sId = $sessId;
1085 } else {
1086 return false;
1089 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1090 $sName = $request->getSessionData( 'wsUserName' );
1091 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1092 $sName = $request->getCookie( 'UserName' );
1093 $request->setSessionData( 'wsUserName', $sName );
1094 } else {
1095 return false;
1098 $proposedUser = User::newFromId( $sId );
1099 if ( !$proposedUser->isLoggedIn() ) {
1100 // Not a valid ID
1101 return false;
1104 global $wgBlockDisablesLogin;
1105 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1106 // User blocked and we've disabled blocked user logins
1107 return false;
1110 if ( $request->getSessionData( 'wsToken' ) ) {
1111 $passwordCorrect =
1112 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1113 $from = 'session';
1114 } elseif ( $request->getCookie( 'Token' ) ) {
1115 # Get the token from DB/cache and clean it up to remove garbage padding.
1116 # This deals with historical problems with bugs and the default column value.
1117 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1118 // Make comparison in constant time (bug 61346)
1119 $passwordCorrect = strlen( $token )
1120 && hash_equals( $token, $request->getCookie( 'Token' ) );
1121 $from = 'cookie';
1122 } else {
1123 // No session or persistent login cookie
1124 return false;
1127 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1128 $this->loadFromUserObject( $proposedUser );
1129 $request->setSessionData( 'wsToken', $this->mToken );
1130 wfDebug( "User: logged in from $from\n" );
1131 return true;
1132 } else {
1133 // Invalid credentials
1134 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1135 return false;
1140 * Load user and user_group data from the database.
1141 * $this->mId must be set, this is how the user is identified.
1143 * @param int $flags Supports User::READ_LOCKING
1144 * @return bool True if the user exists, false if the user is anonymous
1146 public function loadFromDatabase( $flags = 0 ) {
1147 // Paranoia
1148 $this->mId = intval( $this->mId );
1150 // Anonymous user
1151 if ( !$this->mId ) {
1152 $this->loadDefaults();
1153 return false;
1156 $dbr = wfGetDB( DB_MASTER );
1157 $s = $dbr->selectRow(
1158 'user',
1159 self::selectFields(),
1160 array( 'user_id' => $this->mId ),
1161 __METHOD__,
1162 ( $flags & self::READ_LOCKING == self::READ_LOCKING )
1163 ? array( 'LOCK IN SHARE MODE' )
1164 : array()
1167 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1169 if ( $s !== false ) {
1170 // Initialise user table data
1171 $this->loadFromRow( $s );
1172 $this->mGroups = null; // deferred
1173 $this->getEditCount(); // revalidation for nulls
1174 return true;
1175 } else {
1176 // Invalid user_id
1177 $this->mId = 0;
1178 $this->loadDefaults();
1179 return false;
1184 * Initialize this object from a row from the user table.
1186 * @param stdClass $row Row from the user table to load.
1187 * @param array $data Further user data to load into the object
1189 * user_groups Array with groups out of the user_groups table
1190 * user_properties Array with properties out of the user_properties table
1192 public function loadFromRow( $row, $data = null ) {
1193 $all = true;
1194 $passwordFactory = self::getPasswordFactory();
1196 $this->mGroups = null; // deferred
1198 if ( isset( $row->user_name ) ) {
1199 $this->mName = $row->user_name;
1200 $this->mFrom = 'name';
1201 $this->setItemLoaded( 'name' );
1202 } else {
1203 $all = false;
1206 if ( isset( $row->user_real_name ) ) {
1207 $this->mRealName = $row->user_real_name;
1208 $this->setItemLoaded( 'realname' );
1209 } else {
1210 $all = false;
1213 if ( isset( $row->user_id ) ) {
1214 $this->mId = intval( $row->user_id );
1215 $this->mFrom = 'id';
1216 $this->setItemLoaded( 'id' );
1217 } else {
1218 $all = false;
1221 if ( isset( $row->user_editcount ) ) {
1222 $this->mEditCount = $row->user_editcount;
1223 } else {
1224 $all = false;
1227 if ( isset( $row->user_password ) ) {
1228 // Check for *really* old password hashes that don't even have a type
1229 // The old hash format was just an md5 hex hash, with no type information
1230 if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password ) ) {
1231 $row->user_password = ":A:{$this->mId}:{$row->user_password}";
1234 try {
1235 $this->mPassword = $passwordFactory->newFromCiphertext( $row->user_password );
1236 } catch ( PasswordError $e ) {
1237 wfDebug( 'Invalid password hash found in database.' );
1238 $this->mPassword = $passwordFactory->newFromCiphertext( null );
1241 try {
1242 $this->mNewpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword );
1243 } catch ( PasswordError $e ) {
1244 wfDebug( 'Invalid password hash found in database.' );
1245 $this->mNewpassword = $passwordFactory->newFromCiphertext( null );
1248 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
1249 $this->mPasswordExpires = wfTimestampOrNull( TS_MW, $row->user_password_expires );
1252 if ( isset( $row->user_email ) ) {
1253 $this->mEmail = $row->user_email;
1254 $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1255 $this->mToken = $row->user_token;
1256 if ( $this->mToken == '' ) {
1257 $this->mToken = null;
1259 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1260 $this->mEmailToken = $row->user_email_token;
1261 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1262 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1263 } else {
1264 $all = false;
1267 if ( $all ) {
1268 $this->mLoadedItems = true;
1271 if ( is_array( $data ) ) {
1272 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1273 $this->mGroups = $data['user_groups'];
1275 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1276 $this->loadOptions( $data['user_properties'] );
1282 * Load the data for this user object from another user object.
1284 * @param User $user
1286 protected function loadFromUserObject( $user ) {
1287 $user->load();
1288 $user->loadGroups();
1289 $user->loadOptions();
1290 foreach ( self::$mCacheVars as $var ) {
1291 $this->$var = $user->$var;
1296 * Load the groups from the database if they aren't already loaded.
1298 private function loadGroups() {
1299 if ( is_null( $this->mGroups ) ) {
1300 $dbr = wfGetDB( DB_MASTER );
1301 $res = $dbr->select( 'user_groups',
1302 array( 'ug_group' ),
1303 array( 'ug_user' => $this->mId ),
1304 __METHOD__ );
1305 $this->mGroups = array();
1306 foreach ( $res as $row ) {
1307 $this->mGroups[] = $row->ug_group;
1313 * Load the user's password hashes from the database
1315 * This is usually called in a scenario where the actual User object was
1316 * loaded from the cache, and then password comparison needs to be performed.
1317 * Password hashes are not stored in memcached.
1319 * @since 1.24
1321 private function loadPasswords() {
1322 if ( $this->getId() !== 0 && ( $this->mPassword === null || $this->mNewpassword === null ) ) {
1323 $this->loadFromRow( wfGetDB( DB_MASTER )->selectRow(
1324 'user',
1325 array( 'user_password', 'user_newpassword', 'user_newpass_time', 'user_password_expires' ),
1326 array( 'user_id' => $this->getId() ),
1327 __METHOD__
1328 ) );
1333 * Add the user to the group if he/she meets given criteria.
1335 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1336 * possible to remove manually via Special:UserRights. In such case it
1337 * will not be re-added automatically. The user will also not lose the
1338 * group if they no longer meet the criteria.
1340 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1342 * @return array Array of groups the user has been promoted to.
1344 * @see $wgAutopromoteOnce
1346 public function addAutopromoteOnceGroups( $event ) {
1347 global $wgAutopromoteOnceLogInRC, $wgAuth;
1349 $toPromote = array();
1350 if ( $this->getId() ) {
1351 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1352 if ( count( $toPromote ) ) {
1353 $oldGroups = $this->getGroups(); // previous groups
1355 foreach ( $toPromote as $group ) {
1356 $this->addGroup( $group );
1358 // update groups in external authentication database
1359 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1361 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1363 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1364 $logEntry->setPerformer( $this );
1365 $logEntry->setTarget( $this->getUserPage() );
1366 $logEntry->setParameters( array(
1367 '4::oldgroups' => $oldGroups,
1368 '5::newgroups' => $newGroups,
1369 ) );
1370 $logid = $logEntry->insert();
1371 if ( $wgAutopromoteOnceLogInRC ) {
1372 $logEntry->publish( $logid );
1376 return $toPromote;
1380 * Clear various cached data stored in this object. The cache of the user table
1381 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1383 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1384 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1386 public function clearInstanceCache( $reloadFrom = false ) {
1387 $this->mNewtalk = -1;
1388 $this->mDatePreference = null;
1389 $this->mBlockedby = -1; # Unset
1390 $this->mHash = false;
1391 $this->mRights = null;
1392 $this->mEffectiveGroups = null;
1393 $this->mImplicitGroups = null;
1394 $this->mGroups = null;
1395 $this->mOptions = null;
1396 $this->mOptionsLoaded = false;
1397 $this->mEditCount = null;
1399 if ( $reloadFrom ) {
1400 $this->mLoadedItems = array();
1401 $this->mFrom = $reloadFrom;
1406 * Combine the language default options with any site-specific options
1407 * and add the default language variants.
1409 * @return array Array of String options
1411 public static function getDefaultOptions() {
1412 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1414 static $defOpt = null;
1415 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1416 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1417 // mid-request and see that change reflected in the return value of this function.
1418 // Which is insane and would never happen during normal MW operation
1419 return $defOpt;
1422 $defOpt = $wgDefaultUserOptions;
1423 // Default language setting
1424 $defOpt['language'] = $wgContLang->getCode();
1425 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
1426 $defOpt[$langCode == $wgContLang->getCode() ? 'variant' : "variant-$langCode"] = $langCode;
1428 foreach ( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1429 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1431 $defOpt['skin'] = Skin::normalizeKey( $wgDefaultSkin );
1433 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1435 return $defOpt;
1439 * Get a given default option value.
1441 * @param string $opt Name of option to retrieve
1442 * @return string Default option value
1444 public static function getDefaultOption( $opt ) {
1445 $defOpts = self::getDefaultOptions();
1446 if ( isset( $defOpts[$opt] ) ) {
1447 return $defOpts[$opt];
1448 } else {
1449 return null;
1454 * Get blocking information
1455 * @param bool $bFromSlave Whether to check the slave database first.
1456 * To improve performance, non-critical checks are done against slaves.
1457 * Check when actually saving should be done against master.
1459 private function getBlockedStatus( $bFromSlave = true ) {
1460 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1462 if ( -1 != $this->mBlockedby ) {
1463 return;
1466 wfProfileIn( __METHOD__ );
1467 wfDebug( __METHOD__ . ": checking...\n" );
1469 // Initialize data...
1470 // Otherwise something ends up stomping on $this->mBlockedby when
1471 // things get lazy-loaded later, causing false positive block hits
1472 // due to -1 !== 0. Probably session-related... Nothing should be
1473 // overwriting mBlockedby, surely?
1474 $this->load();
1476 # We only need to worry about passing the IP address to the Block generator if the
1477 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1478 # know which IP address they're actually coming from
1479 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1480 $ip = $this->getRequest()->getIP();
1481 } else {
1482 $ip = null;
1485 // User/IP blocking
1486 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1488 // Proxy blocking
1489 if ( !$block instanceof Block && $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1490 && !in_array( $ip, $wgProxyWhitelist )
1492 // Local list
1493 if ( self::isLocallyBlockedProxy( $ip ) ) {
1494 $block = new Block;
1495 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1496 $block->mReason = wfMessage( 'proxyblockreason' )->text();
1497 $block->setTarget( $ip );
1498 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1499 $block = new Block;
1500 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1501 $block->mReason = wfMessage( 'sorbsreason' )->text();
1502 $block->setTarget( $ip );
1506 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1507 if ( !$block instanceof Block
1508 && $wgApplyIpBlocksToXff
1509 && $ip !== null
1510 && !$this->isAllowed( 'proxyunbannable' )
1511 && !in_array( $ip, $wgProxyWhitelist )
1513 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1514 $xff = array_map( 'trim', explode( ',', $xff ) );
1515 $xff = array_diff( $xff, array( $ip ) );
1516 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1517 $block = Block::chooseBlock( $xffblocks, $xff );
1518 if ( $block instanceof Block ) {
1519 # Mangle the reason to alert the user that the block
1520 # originated from matching the X-Forwarded-For header.
1521 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->text();
1525 if ( $block instanceof Block ) {
1526 wfDebug( __METHOD__ . ": Found block.\n" );
1527 $this->mBlock = $block;
1528 $this->mBlockedby = $block->getByName();
1529 $this->mBlockreason = $block->mReason;
1530 $this->mHideName = $block->mHideName;
1531 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1532 } else {
1533 $this->mBlockedby = '';
1534 $this->mHideName = 0;
1535 $this->mAllowUsertalk = false;
1538 // Extensions
1539 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1541 wfProfileOut( __METHOD__ );
1545 * Whether the given IP is in a DNS blacklist.
1547 * @param string $ip IP to check
1548 * @param bool $checkWhitelist Whether to check the whitelist first
1549 * @return bool True if blacklisted.
1551 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1552 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1554 if ( !$wgEnableDnsBlacklist ) {
1555 return false;
1558 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1559 return false;
1562 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1566 * Whether the given IP is in a given DNS blacklist.
1568 * @param string $ip IP to check
1569 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1570 * @return bool True if blacklisted.
1572 public function inDnsBlacklist( $ip, $bases ) {
1573 wfProfileIn( __METHOD__ );
1575 $found = false;
1576 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1577 if ( IP::isIPv4( $ip ) ) {
1578 // Reverse IP, bug 21255
1579 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1581 foreach ( (array)$bases as $base ) {
1582 // Make hostname
1583 // If we have an access key, use that too (ProjectHoneypot, etc.)
1584 if ( is_array( $base ) ) {
1585 if ( count( $base ) >= 2 ) {
1586 // Access key is 1, base URL is 0
1587 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1588 } else {
1589 $host = "$ipReversed.{$base[0]}";
1591 } else {
1592 $host = "$ipReversed.$base";
1595 // Send query
1596 $ipList = gethostbynamel( $host );
1598 if ( $ipList ) {
1599 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1600 $found = true;
1601 break;
1602 } else {
1603 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1608 wfProfileOut( __METHOD__ );
1609 return $found;
1613 * Check if an IP address is in the local proxy list
1615 * @param string $ip
1617 * @return bool
1619 public static function isLocallyBlockedProxy( $ip ) {
1620 global $wgProxyList;
1622 if ( !$wgProxyList ) {
1623 return false;
1625 wfProfileIn( __METHOD__ );
1627 if ( !is_array( $wgProxyList ) ) {
1628 // Load from the specified file
1629 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1632 if ( !is_array( $wgProxyList ) ) {
1633 $ret = false;
1634 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1635 $ret = true;
1636 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1637 // Old-style flipped proxy list
1638 $ret = true;
1639 } else {
1640 $ret = false;
1642 wfProfileOut( __METHOD__ );
1643 return $ret;
1647 * Is this user subject to rate limiting?
1649 * @return bool True if rate limited
1651 public function isPingLimitable() {
1652 global $wgRateLimitsExcludedIPs;
1653 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1654 // No other good way currently to disable rate limits
1655 // for specific IPs. :P
1656 // But this is a crappy hack and should die.
1657 return false;
1659 return !$this->isAllowed( 'noratelimit' );
1663 * Primitive rate limits: enforce maximum actions per time period
1664 * to put a brake on flooding.
1666 * The method generates both a generic profiling point and a per action one
1667 * (suffix being "-$action".
1669 * @note When using a shared cache like memcached, IP-address
1670 * last-hit counters will be shared across wikis.
1672 * @param string $action Action to enforce; 'edit' if unspecified
1673 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1674 * @return bool True if a rate limiter was tripped
1676 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1677 // Call the 'PingLimiter' hook
1678 $result = false;
1679 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1680 return $result;
1683 global $wgRateLimits;
1684 if ( !isset( $wgRateLimits[$action] ) ) {
1685 return false;
1688 // Some groups shouldn't trigger the ping limiter, ever
1689 if ( !$this->isPingLimitable() ) {
1690 return false;
1693 global $wgMemc;
1694 wfProfileIn( __METHOD__ );
1695 wfProfileIn( __METHOD__ . '-' . $action );
1697 $limits = $wgRateLimits[$action];
1698 $keys = array();
1699 $id = $this->getId();
1700 $userLimit = false;
1702 if ( isset( $limits['anon'] ) && $id == 0 ) {
1703 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1706 if ( isset( $limits['user'] ) && $id != 0 ) {
1707 $userLimit = $limits['user'];
1709 if ( $this->isNewbie() ) {
1710 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1711 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1713 if ( isset( $limits['ip'] ) ) {
1714 $ip = $this->getRequest()->getIP();
1715 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1717 if ( isset( $limits['subnet'] ) ) {
1718 $ip = $this->getRequest()->getIP();
1719 $matches = array();
1720 $subnet = false;
1721 if ( IP::isIPv6( $ip ) ) {
1722 $parts = IP::parseRange( "$ip/64" );
1723 $subnet = $parts[0];
1724 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1725 // IPv4
1726 $subnet = $matches[1];
1728 if ( $subnet !== false ) {
1729 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1733 // Check for group-specific permissions
1734 // If more than one group applies, use the group with the highest limit
1735 foreach ( $this->getGroups() as $group ) {
1736 if ( isset( $limits[$group] ) ) {
1737 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1738 $userLimit = $limits[$group];
1742 // Set the user limit key
1743 if ( $userLimit !== false ) {
1744 list( $max, $period ) = $userLimit;
1745 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
1746 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1749 $triggered = false;
1750 foreach ( $keys as $key => $limit ) {
1751 list( $max, $period ) = $limit;
1752 $summary = "(limit $max in {$period}s)";
1753 $count = $wgMemc->get( $key );
1754 // Already pinged?
1755 if ( $count ) {
1756 if ( $count >= $max ) {
1757 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1758 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1759 $triggered = true;
1760 } else {
1761 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1763 } else {
1764 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1765 if ( $incrBy > 0 ) {
1766 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1769 if ( $incrBy > 0 ) {
1770 $wgMemc->incr( $key, $incrBy );
1774 wfProfileOut( __METHOD__ . '-' . $action );
1775 wfProfileOut( __METHOD__ );
1776 return $triggered;
1780 * Check if user is blocked
1782 * @param bool $bFromSlave Whether to check the slave database instead of
1783 * the master. Hacked from false due to horrible probs on site.
1784 * @return bool True if blocked, false otherwise
1786 public function isBlocked( $bFromSlave = true ) {
1787 return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
1791 * Get the block affecting the user, or null if the user is not blocked
1793 * @param bool $bFromSlave Whether to check the slave database instead of the master
1794 * @return Block|null
1796 public function getBlock( $bFromSlave = true ) {
1797 $this->getBlockedStatus( $bFromSlave );
1798 return $this->mBlock instanceof Block ? $this->mBlock : null;
1802 * Check if user is blocked from editing a particular article
1804 * @param Title $title Title to check
1805 * @param bool $bFromSlave Whether to check the slave database instead of the master
1806 * @return bool
1808 public function isBlockedFrom( $title, $bFromSlave = false ) {
1809 global $wgBlockAllowsUTEdit;
1810 wfProfileIn( __METHOD__ );
1812 $blocked = $this->isBlocked( $bFromSlave );
1813 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1814 // If a user's name is suppressed, they cannot make edits anywhere
1815 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName()
1816 && $title->getNamespace() == NS_USER_TALK ) {
1817 $blocked = false;
1818 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1821 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1823 wfProfileOut( __METHOD__ );
1824 return $blocked;
1828 * If user is blocked, return the name of the user who placed the block
1829 * @return string Name of blocker
1831 public function blockedBy() {
1832 $this->getBlockedStatus();
1833 return $this->mBlockedby;
1837 * If user is blocked, return the specified reason for the block
1838 * @return string Blocking reason
1840 public function blockedFor() {
1841 $this->getBlockedStatus();
1842 return $this->mBlockreason;
1846 * If user is blocked, return the ID for the block
1847 * @return int Block ID
1849 public function getBlockId() {
1850 $this->getBlockedStatus();
1851 return ( $this->mBlock ? $this->mBlock->getId() : false );
1855 * Check if user is blocked on all wikis.
1856 * Do not use for actual edit permission checks!
1857 * This is intended for quick UI checks.
1859 * @param string $ip IP address, uses current client if none given
1860 * @return bool True if blocked, false otherwise
1862 public function isBlockedGlobally( $ip = '' ) {
1863 if ( $this->mBlockedGlobally !== null ) {
1864 return $this->mBlockedGlobally;
1866 // User is already an IP?
1867 if ( IP::isIPAddress( $this->getName() ) ) {
1868 $ip = $this->getName();
1869 } elseif ( !$ip ) {
1870 $ip = $this->getRequest()->getIP();
1872 $blocked = false;
1873 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1874 $this->mBlockedGlobally = (bool)$blocked;
1875 return $this->mBlockedGlobally;
1879 * Check if user account is locked
1881 * @return bool True if locked, false otherwise
1883 public function isLocked() {
1884 if ( $this->mLocked !== null ) {
1885 return $this->mLocked;
1887 global $wgAuth;
1888 StubObject::unstub( $wgAuth );
1889 $authUser = $wgAuth->getUserInstance( $this );
1890 $this->mLocked = (bool)$authUser->isLocked();
1891 return $this->mLocked;
1895 * Check if user account is hidden
1897 * @return bool True if hidden, false otherwise
1899 public function isHidden() {
1900 if ( $this->mHideName !== null ) {
1901 return $this->mHideName;
1903 $this->getBlockedStatus();
1904 if ( !$this->mHideName ) {
1905 global $wgAuth;
1906 StubObject::unstub( $wgAuth );
1907 $authUser = $wgAuth->getUserInstance( $this );
1908 $this->mHideName = (bool)$authUser->isHidden();
1910 return $this->mHideName;
1914 * Get the user's ID.
1915 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1917 public function getId() {
1918 if ( $this->mId === null && $this->mName !== null && User::isIP( $this->mName ) ) {
1919 // Special case, we know the user is anonymous
1920 return 0;
1921 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1922 // Don't load if this was initialized from an ID
1923 $this->load();
1925 return $this->mId;
1929 * Set the user and reload all fields according to a given ID
1930 * @param int $v User ID to reload
1932 public function setId( $v ) {
1933 $this->mId = $v;
1934 $this->clearInstanceCache( 'id' );
1938 * Get the user name, or the IP of an anonymous user
1939 * @return string User's name or IP address
1941 public function getName() {
1942 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1943 // Special case optimisation
1944 return $this->mName;
1945 } else {
1946 $this->load();
1947 if ( $this->mName === false ) {
1948 // Clean up IPs
1949 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
1951 return $this->mName;
1956 * Set the user name.
1958 * This does not reload fields from the database according to the given
1959 * name. Rather, it is used to create a temporary "nonexistent user" for
1960 * later addition to the database. It can also be used to set the IP
1961 * address for an anonymous user to something other than the current
1962 * remote IP.
1964 * @note User::newFromName() has roughly the same function, when the named user
1965 * does not exist.
1966 * @param string $str New user name to set
1968 public function setName( $str ) {
1969 $this->load();
1970 $this->mName = $str;
1974 * Get the user's name escaped by underscores.
1975 * @return string Username escaped by underscores.
1977 public function getTitleKey() {
1978 return str_replace( ' ', '_', $this->getName() );
1982 * Check if the user has new messages.
1983 * @return bool True if the user has new messages
1985 public function getNewtalk() {
1986 $this->load();
1988 // Load the newtalk status if it is unloaded (mNewtalk=-1)
1989 if ( $this->mNewtalk === -1 ) {
1990 $this->mNewtalk = false; # reset talk page status
1992 // Check memcached separately for anons, who have no
1993 // entire User object stored in there.
1994 if ( !$this->mId ) {
1995 global $wgDisableAnonTalk;
1996 if ( $wgDisableAnonTalk ) {
1997 // Anon newtalk disabled by configuration.
1998 $this->mNewtalk = false;
1999 } else {
2000 global $wgMemc;
2001 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
2002 $newtalk = $wgMemc->get( $key );
2003 if ( strval( $newtalk ) !== '' ) {
2004 $this->mNewtalk = (bool)$newtalk;
2005 } else {
2006 // Since we are caching this, make sure it is up to date by getting it
2007 // from the master
2008 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
2009 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
2012 } else {
2013 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
2017 return (bool)$this->mNewtalk;
2021 * Return the data needed to construct links for new talk page message
2022 * alerts. If there are new messages, this will return an associative array
2023 * with the following data:
2024 * wiki: The database name of the wiki
2025 * link: Root-relative link to the user's talk page
2026 * rev: The last talk page revision that the user has seen or null. This
2027 * is useful for building diff links.
2028 * If there are no new messages, it returns an empty array.
2029 * @note This function was designed to accomodate multiple talk pages, but
2030 * currently only returns a single link and revision.
2031 * @return array
2033 public function getNewMessageLinks() {
2034 $talks = array();
2035 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2036 return $talks;
2037 } elseif ( !$this->getNewtalk() ) {
2038 return array();
2040 $utp = $this->getTalkPage();
2041 $dbr = wfGetDB( DB_SLAVE );
2042 // Get the "last viewed rev" timestamp from the oldest message notification
2043 $timestamp = $dbr->selectField( 'user_newtalk',
2044 'MIN(user_last_timestamp)',
2045 $this->isAnon() ? array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2046 __METHOD__ );
2047 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2048 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2052 * Get the revision ID for the last talk page revision viewed by the talk
2053 * page owner.
2054 * @return int|null Revision ID or null
2056 public function getNewMessageRevisionId() {
2057 $newMessageRevisionId = null;
2058 $newMessageLinks = $this->getNewMessageLinks();
2059 if ( $newMessageLinks ) {
2060 // Note: getNewMessageLinks() never returns more than a single link
2061 // and it is always for the same wiki, but we double-check here in
2062 // case that changes some time in the future.
2063 if ( count( $newMessageLinks ) === 1
2064 && $newMessageLinks[0]['wiki'] === wfWikiID()
2065 && $newMessageLinks[0]['rev']
2067 $newMessageRevision = $newMessageLinks[0]['rev'];
2068 $newMessageRevisionId = $newMessageRevision->getId();
2071 return $newMessageRevisionId;
2075 * Internal uncached check for new messages
2077 * @see getNewtalk()
2078 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2079 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2080 * @param bool $fromMaster True to fetch from the master, false for a slave
2081 * @return bool True if the user has new messages
2083 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
2084 if ( $fromMaster ) {
2085 $db = wfGetDB( DB_MASTER );
2086 } else {
2087 $db = wfGetDB( DB_SLAVE );
2089 $ok = $db->selectField( 'user_newtalk', $field,
2090 array( $field => $id ), __METHOD__ );
2091 return $ok !== false;
2095 * Add or update the new messages flag
2096 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2097 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2098 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2099 * @return bool True if successful, false otherwise
2101 protected function updateNewtalk( $field, $id, $curRev = null ) {
2102 // Get timestamp of the talk page revision prior to the current one
2103 $prevRev = $curRev ? $curRev->getPrevious() : false;
2104 $ts = $prevRev ? $prevRev->getTimestamp() : null;
2105 // Mark the user as having new messages since this revision
2106 $dbw = wfGetDB( DB_MASTER );
2107 $dbw->insert( 'user_newtalk',
2108 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2109 __METHOD__,
2110 'IGNORE' );
2111 if ( $dbw->affectedRows() ) {
2112 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
2113 return true;
2114 } else {
2115 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
2116 return false;
2121 * Clear the new messages flag for the given user
2122 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2123 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2124 * @return bool True if successful, false otherwise
2126 protected function deleteNewtalk( $field, $id ) {
2127 $dbw = wfGetDB( DB_MASTER );
2128 $dbw->delete( 'user_newtalk',
2129 array( $field => $id ),
2130 __METHOD__ );
2131 if ( $dbw->affectedRows() ) {
2132 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
2133 return true;
2134 } else {
2135 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
2136 return false;
2141 * Update the 'You have new messages!' status.
2142 * @param bool $val Whether the user has new messages
2143 * @param Revision $curRev New, as yet unseen revision of the user talk
2144 * page. Ignored if null or !$val.
2146 public function setNewtalk( $val, $curRev = null ) {
2147 if ( wfReadOnly() ) {
2148 return;
2151 $this->load();
2152 $this->mNewtalk = $val;
2154 if ( $this->isAnon() ) {
2155 $field = 'user_ip';
2156 $id = $this->getName();
2157 } else {
2158 $field = 'user_id';
2159 $id = $this->getId();
2161 global $wgMemc;
2163 if ( $val ) {
2164 $changed = $this->updateNewtalk( $field, $id, $curRev );
2165 } else {
2166 $changed = $this->deleteNewtalk( $field, $id );
2169 if ( $this->isAnon() ) {
2170 // Anons have a separate memcached space, since
2171 // user records aren't kept for them.
2172 $key = wfMemcKey( 'newtalk', 'ip', $id );
2173 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
2175 if ( $changed ) {
2176 $this->invalidateCache();
2181 * Generate a current or new-future timestamp to be stored in the
2182 * user_touched field when we update things.
2183 * @return string Timestamp in TS_MW format
2185 private static function newTouchedTimestamp() {
2186 global $wgClockSkewFudge;
2187 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
2191 * Clear user data from memcached.
2192 * Use after applying fun updates to the database; caller's
2193 * responsibility to update user_touched if appropriate.
2195 * Called implicitly from invalidateCache() and saveSettings().
2197 public function clearSharedCache() {
2198 $this->load();
2199 if ( $this->mId ) {
2200 global $wgMemc;
2201 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
2206 * Immediately touch the user data cache for this account.
2207 * Updates user_touched field, and removes account data from memcached
2208 * for reload on the next hit.
2210 public function invalidateCache() {
2211 if ( wfReadOnly() ) {
2212 return;
2214 $this->load();
2215 if ( $this->mId ) {
2216 $this->mTouched = self::newTouchedTimestamp();
2218 $dbw = wfGetDB( DB_MASTER );
2219 $userid = $this->mId;
2220 $touched = $this->mTouched;
2221 $method = __METHOD__;
2222 $dbw->onTransactionIdle( function () use ( $dbw, $userid, $touched, $method ) {
2223 // Prevent contention slams by checking user_touched first
2224 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2225 $needsPurge = $dbw->selectField( 'user', '1',
2226 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2227 if ( $needsPurge ) {
2228 $dbw->update( 'user',
2229 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2230 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2231 $method
2234 } );
2235 $this->clearSharedCache();
2240 * Validate the cache for this account.
2241 * @param string $timestamp A timestamp in TS_MW format
2242 * @return bool
2244 public function validateCache( $timestamp ) {
2245 $this->load();
2246 return ( $timestamp >= $this->mTouched );
2250 * Get the user touched timestamp
2251 * @return string Timestamp
2253 public function getTouched() {
2254 $this->load();
2255 return $this->mTouched;
2259 * @return Password
2260 * @since 1.24
2262 public function getPassword() {
2263 $this->loadPasswords();
2265 return $this->mPassword;
2269 * @return Password
2270 * @since 1.24
2272 public function getTemporaryPassword() {
2273 $this->loadPasswords();
2275 return $this->mNewpassword;
2279 * Set the password and reset the random token.
2280 * Calls through to authentication plugin if necessary;
2281 * will have no effect if the auth plugin refuses to
2282 * pass the change through or if the legal password
2283 * checks fail.
2285 * As a special case, setting the password to null
2286 * wipes it, so the account cannot be logged in until
2287 * a new password is set, for instance via e-mail.
2289 * @param string $str New password to set
2290 * @throws PasswordError On failure
2292 * @return bool
2294 public function setPassword( $str ) {
2295 global $wgAuth;
2297 $this->loadPasswords();
2299 if ( $str !== null ) {
2300 if ( !$wgAuth->allowPasswordChange() ) {
2301 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2304 if ( !$this->isValidPassword( $str ) ) {
2305 global $wgMinimalPasswordLength;
2306 $valid = $this->getPasswordValidity( $str );
2307 if ( is_array( $valid ) ) {
2308 $message = array_shift( $valid );
2309 $params = $valid;
2310 } else {
2311 $message = $valid;
2312 $params = array( $wgMinimalPasswordLength );
2314 throw new PasswordError( wfMessage( $message, $params )->text() );
2318 if ( !$wgAuth->setPassword( $this, $str ) ) {
2319 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2322 $this->setInternalPassword( $str );
2324 return true;
2328 * Set the password and reset the random token unconditionally.
2330 * @param string|null $str New password to set or null to set an invalid
2331 * password hash meaning that the user will not be able to log in
2332 * through the web interface.
2334 public function setInternalPassword( $str ) {
2335 $this->setToken();
2337 $passwordFactory = self::getPasswordFactory();
2338 if ( $str === null ) {
2339 $this->mPassword = $passwordFactory->newFromCiphertext( null );
2340 } else {
2341 $this->mPassword = $passwordFactory->newFromPlaintext( $str );
2344 $this->mNewpassword = $passwordFactory->newFromCiphertext( null );
2345 $this->mNewpassTime = null;
2349 * Get the user's current token.
2350 * @param bool $forceCreation Force the generation of a new token if the
2351 * user doesn't have one (default=true for backwards compatibility).
2352 * @return string Token
2354 public function getToken( $forceCreation = true ) {
2355 $this->load();
2356 if ( !$this->mToken && $forceCreation ) {
2357 $this->setToken();
2359 return $this->mToken;
2363 * Set the random token (used for persistent authentication)
2364 * Called from loadDefaults() among other places.
2366 * @param string|bool $token If specified, set the token to this value
2368 public function setToken( $token = false ) {
2369 $this->load();
2370 if ( !$token ) {
2371 $this->mToken = MWCryptRand::generateHex( self::TOKEN_LENGTH );
2372 } else {
2373 $this->mToken = $token;
2378 * Set the password for a password reminder or new account email
2380 * @param string $str New password to set or null to set an invalid
2381 * password hash meaning that the user will not be able to use it
2382 * @param bool $throttle If true, reset the throttle timestamp to the present
2384 public function setNewpassword( $str, $throttle = true ) {
2385 $this->loadPasswords();
2387 if ( $str === null ) {
2388 $this->mNewpassword = '';
2389 $this->mNewpassTime = null;
2390 } else {
2391 $this->mNewpassword = self::getPasswordFactory()->newFromPlaintext( $str );
2392 if ( $throttle ) {
2393 $this->mNewpassTime = wfTimestampNow();
2399 * Has password reminder email been sent within the last
2400 * $wgPasswordReminderResendTime hours?
2401 * @return bool
2403 public function isPasswordReminderThrottled() {
2404 global $wgPasswordReminderResendTime;
2405 $this->load();
2406 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
2407 return false;
2409 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
2410 return time() < $expiry;
2414 * Get the user's e-mail address
2415 * @return string User's email address
2417 public function getEmail() {
2418 $this->load();
2419 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
2420 return $this->mEmail;
2424 * Get the timestamp of the user's e-mail authentication
2425 * @return string TS_MW timestamp
2427 public function getEmailAuthenticationTimestamp() {
2428 $this->load();
2429 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2430 return $this->mEmailAuthenticated;
2434 * Set the user's e-mail address
2435 * @param string $str New e-mail address
2437 public function setEmail( $str ) {
2438 $this->load();
2439 if ( $str == $this->mEmail ) {
2440 return;
2442 $this->invalidateEmail();
2443 $this->mEmail = $str;
2444 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
2448 * Set the user's e-mail address and a confirmation mail if needed.
2450 * @since 1.20
2451 * @param string $str New e-mail address
2452 * @return Status
2454 public function setEmailWithConfirmation( $str ) {
2455 global $wgEnableEmail, $wgEmailAuthentication;
2457 if ( !$wgEnableEmail ) {
2458 return Status::newFatal( 'emaildisabled' );
2461 $oldaddr = $this->getEmail();
2462 if ( $str === $oldaddr ) {
2463 return Status::newGood( true );
2466 $this->setEmail( $str );
2468 if ( $str !== '' && $wgEmailAuthentication ) {
2469 // Send a confirmation request to the new address if needed
2470 $type = $oldaddr != '' ? 'changed' : 'set';
2471 $result = $this->sendConfirmationMail( $type );
2472 if ( $result->isGood() ) {
2473 // Say the the caller that a confirmation mail has been sent
2474 $result->value = 'eauth';
2476 } else {
2477 $result = Status::newGood( true );
2480 return $result;
2484 * Get the user's real name
2485 * @return string User's real name
2487 public function getRealName() {
2488 if ( !$this->isItemLoaded( 'realname' ) ) {
2489 $this->load();
2492 return $this->mRealName;
2496 * Set the user's real name
2497 * @param string $str New real name
2499 public function setRealName( $str ) {
2500 $this->load();
2501 $this->mRealName = $str;
2505 * Get the user's current setting for a given option.
2507 * @param string $oname The option to check
2508 * @param string $defaultOverride A default value returned if the option does not exist
2509 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2510 * @return string User's current value for the option
2511 * @see getBoolOption()
2512 * @see getIntOption()
2514 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2515 global $wgHiddenPrefs;
2516 $this->loadOptions();
2518 # We want 'disabled' preferences to always behave as the default value for
2519 # users, even if they have set the option explicitly in their settings (ie they
2520 # set it, and then it was disabled removing their ability to change it). But
2521 # we don't want to erase the preferences in the database in case the preference
2522 # is re-enabled again. So don't touch $mOptions, just override the returned value
2523 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2524 return self::getDefaultOption( $oname );
2527 if ( array_key_exists( $oname, $this->mOptions ) ) {
2528 return $this->mOptions[$oname];
2529 } else {
2530 return $defaultOverride;
2535 * Get all user's options
2537 * @return array
2539 public function getOptions() {
2540 global $wgHiddenPrefs;
2541 $this->loadOptions();
2542 $options = $this->mOptions;
2544 # We want 'disabled' preferences to always behave as the default value for
2545 # users, even if they have set the option explicitly in their settings (ie they
2546 # set it, and then it was disabled removing their ability to change it). But
2547 # we don't want to erase the preferences in the database in case the preference
2548 # is re-enabled again. So don't touch $mOptions, just override the returned value
2549 foreach ( $wgHiddenPrefs as $pref ) {
2550 $default = self::getDefaultOption( $pref );
2551 if ( $default !== null ) {
2552 $options[$pref] = $default;
2556 return $options;
2560 * Get the user's current setting for a given option, as a boolean value.
2562 * @param string $oname The option to check
2563 * @return bool User's current value for the option
2564 * @see getOption()
2566 public function getBoolOption( $oname ) {
2567 return (bool)$this->getOption( $oname );
2571 * Get the user's current setting for a given option, as an integer value.
2573 * @param string $oname The option to check
2574 * @param int $defaultOverride A default value returned if the option does not exist
2575 * @return int User's current value for the option
2576 * @see getOption()
2578 public function getIntOption( $oname, $defaultOverride = 0 ) {
2579 $val = $this->getOption( $oname );
2580 if ( $val == '' ) {
2581 $val = $defaultOverride;
2583 return intval( $val );
2587 * Set the given option for a user.
2589 * You need to call saveSettings() to actually write to the database.
2591 * @param string $oname The option to set
2592 * @param mixed $val New value to set
2594 public function setOption( $oname, $val ) {
2595 $this->loadOptions();
2597 // Explicitly NULL values should refer to defaults
2598 if ( is_null( $val ) ) {
2599 $val = self::getDefaultOption( $oname );
2602 $this->mOptions[$oname] = $val;
2606 * Get a token stored in the preferences (like the watchlist one),
2607 * resetting it if it's empty (and saving changes).
2609 * @param string $oname The option name to retrieve the token from
2610 * @return string|bool User's current value for the option, or false if this option is disabled.
2611 * @see resetTokenFromOption()
2612 * @see getOption()
2614 public function getTokenFromOption( $oname ) {
2615 global $wgHiddenPrefs;
2616 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2617 return false;
2620 $token = $this->getOption( $oname );
2621 if ( !$token ) {
2622 $token = $this->resetTokenFromOption( $oname );
2623 $this->saveSettings();
2625 return $token;
2629 * Reset a token stored in the preferences (like the watchlist one).
2630 * *Does not* save user's preferences (similarly to setOption()).
2632 * @param string $oname The option name to reset the token in
2633 * @return string|bool New token value, or false if this option is disabled.
2634 * @see getTokenFromOption()
2635 * @see setOption()
2637 public function resetTokenFromOption( $oname ) {
2638 global $wgHiddenPrefs;
2639 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2640 return false;
2643 $token = MWCryptRand::generateHex( 40 );
2644 $this->setOption( $oname, $token );
2645 return $token;
2649 * Return a list of the types of user options currently returned by
2650 * User::getOptionKinds().
2652 * Currently, the option kinds are:
2653 * - 'registered' - preferences which are registered in core MediaWiki or
2654 * by extensions using the UserGetDefaultOptions hook.
2655 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2656 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2657 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2658 * be used by user scripts.
2659 * - 'special' - "preferences" that are not accessible via User::getOptions
2660 * or User::setOptions.
2661 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2662 * These are usually legacy options, removed in newer versions.
2664 * The API (and possibly others) use this function to determine the possible
2665 * option types for validation purposes, so make sure to update this when a
2666 * new option kind is added.
2668 * @see User::getOptionKinds
2669 * @return array Option kinds
2671 public static function listOptionKinds() {
2672 return array(
2673 'registered',
2674 'registered-multiselect',
2675 'registered-checkmatrix',
2676 'userjs',
2677 'special',
2678 'unused'
2683 * Return an associative array mapping preferences keys to the kind of a preference they're
2684 * used for. Different kinds are handled differently when setting or reading preferences.
2686 * See User::listOptionKinds for the list of valid option types that can be provided.
2688 * @see User::listOptionKinds
2689 * @param IContextSource $context
2690 * @param array $options Assoc. array with options keys to check as keys.
2691 * Defaults to $this->mOptions.
2692 * @return array The key => kind mapping data
2694 public function getOptionKinds( IContextSource $context, $options = null ) {
2695 $this->loadOptions();
2696 if ( $options === null ) {
2697 $options = $this->mOptions;
2700 $prefs = Preferences::getPreferences( $this, $context );
2701 $mapping = array();
2703 // Pull out the "special" options, so they don't get converted as
2704 // multiselect or checkmatrix.
2705 $specialOptions = array_fill_keys( Preferences::getSaveBlacklist(), true );
2706 foreach ( $specialOptions as $name => $value ) {
2707 unset( $prefs[$name] );
2710 // Multiselect and checkmatrix options are stored in the database with
2711 // one key per option, each having a boolean value. Extract those keys.
2712 $multiselectOptions = array();
2713 foreach ( $prefs as $name => $info ) {
2714 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2715 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2716 $opts = HTMLFormField::flattenOptions( $info['options'] );
2717 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2719 foreach ( $opts as $value ) {
2720 $multiselectOptions["$prefix$value"] = true;
2723 unset( $prefs[$name] );
2726 $checkmatrixOptions = array();
2727 foreach ( $prefs as $name => $info ) {
2728 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2729 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2730 $columns = HTMLFormField::flattenOptions( $info['columns'] );
2731 $rows = HTMLFormField::flattenOptions( $info['rows'] );
2732 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2734 foreach ( $columns as $column ) {
2735 foreach ( $rows as $row ) {
2736 $checkmatrixOptions["$prefix$column-$row"] = true;
2740 unset( $prefs[$name] );
2744 // $value is ignored
2745 foreach ( $options as $key => $value ) {
2746 if ( isset( $prefs[$key] ) ) {
2747 $mapping[$key] = 'registered';
2748 } elseif ( isset( $multiselectOptions[$key] ) ) {
2749 $mapping[$key] = 'registered-multiselect';
2750 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2751 $mapping[$key] = 'registered-checkmatrix';
2752 } elseif ( isset( $specialOptions[$key] ) ) {
2753 $mapping[$key] = 'special';
2754 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2755 $mapping[$key] = 'userjs';
2756 } else {
2757 $mapping[$key] = 'unused';
2761 return $mapping;
2765 * Reset certain (or all) options to the site defaults
2767 * The optional parameter determines which kinds of preferences will be reset.
2768 * Supported values are everything that can be reported by getOptionKinds()
2769 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2771 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2772 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2773 * for backwards-compatibility.
2774 * @param IContextSource|null $context Context source used when $resetKinds
2775 * does not contain 'all', passed to getOptionKinds().
2776 * Defaults to RequestContext::getMain() when null.
2778 public function resetOptions(
2779 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2780 IContextSource $context = null
2782 $this->load();
2783 $defaultOptions = self::getDefaultOptions();
2785 if ( !is_array( $resetKinds ) ) {
2786 $resetKinds = array( $resetKinds );
2789 if ( in_array( 'all', $resetKinds ) ) {
2790 $newOptions = $defaultOptions;
2791 } else {
2792 if ( $context === null ) {
2793 $context = RequestContext::getMain();
2796 $optionKinds = $this->getOptionKinds( $context );
2797 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
2798 $newOptions = array();
2800 // Use default values for the options that should be deleted, and
2801 // copy old values for the ones that shouldn't.
2802 foreach ( $this->mOptions as $key => $value ) {
2803 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2804 if ( array_key_exists( $key, $defaultOptions ) ) {
2805 $newOptions[$key] = $defaultOptions[$key];
2807 } else {
2808 $newOptions[$key] = $value;
2813 wfRunHooks( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions, $resetKinds ) );
2815 $this->mOptions = $newOptions;
2816 $this->mOptionsLoaded = true;
2820 * Get the user's preferred date format.
2821 * @return string User's preferred date format
2823 public function getDatePreference() {
2824 // Important migration for old data rows
2825 if ( is_null( $this->mDatePreference ) ) {
2826 global $wgLang;
2827 $value = $this->getOption( 'date' );
2828 $map = $wgLang->getDatePreferenceMigrationMap();
2829 if ( isset( $map[$value] ) ) {
2830 $value = $map[$value];
2832 $this->mDatePreference = $value;
2834 return $this->mDatePreference;
2838 * Determine based on the wiki configuration and the user's options,
2839 * whether this user must be over HTTPS no matter what.
2841 * @return bool
2843 public function requiresHTTPS() {
2844 global $wgSecureLogin;
2845 if ( !$wgSecureLogin ) {
2846 return false;
2847 } else {
2848 $https = $this->getBoolOption( 'prefershttps' );
2849 wfRunHooks( 'UserRequiresHTTPS', array( $this, &$https ) );
2850 if ( $https ) {
2851 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2853 return $https;
2858 * Get the user preferred stub threshold
2860 * @return int
2862 public function getStubThreshold() {
2863 global $wgMaxArticleSize; # Maximum article size, in Kb
2864 $threshold = $this->getIntOption( 'stubthreshold' );
2865 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2866 // If they have set an impossible value, disable the preference
2867 // so we can use the parser cache again.
2868 $threshold = 0;
2870 return $threshold;
2874 * Get the permissions this user has.
2875 * @return array Array of String permission names
2877 public function getRights() {
2878 if ( is_null( $this->mRights ) ) {
2879 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2880 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
2881 // Force reindexation of rights when a hook has unset one of them
2882 $this->mRights = array_values( array_unique( $this->mRights ) );
2884 return $this->mRights;
2888 * Get the list of explicit group memberships this user has.
2889 * The implicit * and user groups are not included.
2890 * @return array Array of String internal group names
2892 public function getGroups() {
2893 $this->load();
2894 $this->loadGroups();
2895 return $this->mGroups;
2899 * Get the list of implicit group memberships this user has.
2900 * This includes all explicit groups, plus 'user' if logged in,
2901 * '*' for all accounts, and autopromoted groups
2902 * @param bool $recache Whether to avoid the cache
2903 * @return array Array of String internal group names
2905 public function getEffectiveGroups( $recache = false ) {
2906 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
2907 wfProfileIn( __METHOD__ );
2908 $this->mEffectiveGroups = array_unique( array_merge(
2909 $this->getGroups(), // explicit groups
2910 $this->getAutomaticGroups( $recache ) // implicit groups
2911 ) );
2912 // Hook for additional groups
2913 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
2914 // Force reindexation of groups when a hook has unset one of them
2915 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
2916 wfProfileOut( __METHOD__ );
2918 return $this->mEffectiveGroups;
2922 * Get the list of implicit group memberships this user has.
2923 * This includes 'user' if logged in, '*' for all accounts,
2924 * and autopromoted groups
2925 * @param bool $recache Whether to avoid the cache
2926 * @return array Array of String internal group names
2928 public function getAutomaticGroups( $recache = false ) {
2929 if ( $recache || is_null( $this->mImplicitGroups ) ) {
2930 wfProfileIn( __METHOD__ );
2931 $this->mImplicitGroups = array( '*' );
2932 if ( $this->getId() ) {
2933 $this->mImplicitGroups[] = 'user';
2935 $this->mImplicitGroups = array_unique( array_merge(
2936 $this->mImplicitGroups,
2937 Autopromote::getAutopromoteGroups( $this )
2938 ) );
2940 if ( $recache ) {
2941 // Assure data consistency with rights/groups,
2942 // as getEffectiveGroups() depends on this function
2943 $this->mEffectiveGroups = null;
2945 wfProfileOut( __METHOD__ );
2947 return $this->mImplicitGroups;
2951 * Returns the groups the user has belonged to.
2953 * The user may still belong to the returned groups. Compare with getGroups().
2955 * The function will not return groups the user had belonged to before MW 1.17
2957 * @return array Names of the groups the user has belonged to.
2959 public function getFormerGroups() {
2960 if ( is_null( $this->mFormerGroups ) ) {
2961 $dbr = wfGetDB( DB_MASTER );
2962 $res = $dbr->select( 'user_former_groups',
2963 array( 'ufg_group' ),
2964 array( 'ufg_user' => $this->mId ),
2965 __METHOD__ );
2966 $this->mFormerGroups = array();
2967 foreach ( $res as $row ) {
2968 $this->mFormerGroups[] = $row->ufg_group;
2971 return $this->mFormerGroups;
2975 * Get the user's edit count.
2976 * @return int|null Null for anonymous users
2978 public function getEditCount() {
2979 if ( !$this->getId() ) {
2980 return null;
2983 if ( $this->mEditCount === null ) {
2984 /* Populate the count, if it has not been populated yet */
2985 wfProfileIn( __METHOD__ );
2986 $dbr = wfGetDB( DB_SLAVE );
2987 // check if the user_editcount field has been initialized
2988 $count = $dbr->selectField(
2989 'user', 'user_editcount',
2990 array( 'user_id' => $this->mId ),
2991 __METHOD__
2994 if ( $count === null ) {
2995 // it has not been initialized. do so.
2996 $count = $this->initEditCount();
2998 $this->mEditCount = $count;
2999 wfProfileOut( __METHOD__ );
3001 return (int)$this->mEditCount;
3005 * Add the user to the given group.
3006 * This takes immediate effect.
3007 * @param string $group Name of the group to add
3009 public function addGroup( $group ) {
3010 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
3011 $dbw = wfGetDB( DB_MASTER );
3012 if ( $this->getId() ) {
3013 $dbw->insert( 'user_groups',
3014 array(
3015 'ug_user' => $this->getID(),
3016 'ug_group' => $group,
3018 __METHOD__,
3019 array( 'IGNORE' ) );
3022 $this->loadGroups();
3023 $this->mGroups[] = $group;
3024 // In case loadGroups was not called before, we now have the right twice.
3025 // Get rid of the duplicate.
3026 $this->mGroups = array_unique( $this->mGroups );
3028 // Refresh the groups caches, and clear the rights cache so it will be
3029 // refreshed on the next call to $this->getRights().
3030 $this->getEffectiveGroups( true );
3031 $this->mRights = null;
3033 $this->invalidateCache();
3037 * Remove the user from the given group.
3038 * This takes immediate effect.
3039 * @param string $group Name of the group to remove
3041 public function removeGroup( $group ) {
3042 $this->load();
3043 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3044 $dbw = wfGetDB( DB_MASTER );
3045 $dbw->delete( 'user_groups',
3046 array(
3047 'ug_user' => $this->getID(),
3048 'ug_group' => $group,
3049 ), __METHOD__ );
3050 // Remember that the user was in this group
3051 $dbw->insert( 'user_former_groups',
3052 array(
3053 'ufg_user' => $this->getID(),
3054 'ufg_group' => $group,
3056 __METHOD__,
3057 array( 'IGNORE' ) );
3059 $this->loadGroups();
3060 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
3062 // Refresh the groups caches, and clear the rights cache so it will be
3063 // refreshed on the next call to $this->getRights().
3064 $this->getEffectiveGroups( true );
3065 $this->mRights = null;
3067 $this->invalidateCache();
3071 * Get whether the user is logged in
3072 * @return bool
3074 public function isLoggedIn() {
3075 return $this->getID() != 0;
3079 * Get whether the user is anonymous
3080 * @return bool
3082 public function isAnon() {
3083 return !$this->isLoggedIn();
3087 * Check if user is allowed to access a feature / make an action
3089 * @param string $permissions,... Permissions to test
3090 * @return bool True if user is allowed to perform *any* of the given actions
3092 public function isAllowedAny( /*...*/ ) {
3093 $permissions = func_get_args();
3094 foreach ( $permissions as $permission ) {
3095 if ( $this->isAllowed( $permission ) ) {
3096 return true;
3099 return false;
3104 * @param string $permissions,... Permissions to test
3105 * @return bool True if the user is allowed to perform *all* of the given actions
3107 public function isAllowedAll( /*...*/ ) {
3108 $permissions = func_get_args();
3109 foreach ( $permissions as $permission ) {
3110 if ( !$this->isAllowed( $permission ) ) {
3111 return false;
3114 return true;
3118 * Internal mechanics of testing a permission
3119 * @param string $action
3120 * @return bool
3122 public function isAllowed( $action = '' ) {
3123 if ( $action === '' ) {
3124 return true; // In the spirit of DWIM
3126 // Patrolling may not be enabled
3127 if ( $action === 'patrol' || $action === 'autopatrol' ) {
3128 global $wgUseRCPatrol, $wgUseNPPatrol;
3129 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3130 return false;
3133 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3134 // by misconfiguration: 0 == 'foo'
3135 return in_array( $action, $this->getRights(), true );
3139 * Check whether to enable recent changes patrol features for this user
3140 * @return bool True or false
3142 public function useRCPatrol() {
3143 global $wgUseRCPatrol;
3144 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3148 * Check whether to enable new pages patrol features for this user
3149 * @return bool True or false
3151 public function useNPPatrol() {
3152 global $wgUseRCPatrol, $wgUseNPPatrol;
3153 return (
3154 ( $wgUseRCPatrol || $wgUseNPPatrol )
3155 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3160 * Get the WebRequest object to use with this object
3162 * @return WebRequest
3164 public function getRequest() {
3165 if ( $this->mRequest ) {
3166 return $this->mRequest;
3167 } else {
3168 global $wgRequest;
3169 return $wgRequest;
3174 * Get the current skin, loading it if required
3175 * @return Skin The current skin
3176 * @todo FIXME: Need to check the old failback system [AV]
3177 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3179 public function getSkin() {
3180 wfDeprecated( __METHOD__, '1.18' );
3181 return RequestContext::getMain()->getSkin();
3185 * Get a WatchedItem for this user and $title.
3187 * @since 1.22 $checkRights parameter added
3188 * @param Title $title
3189 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3190 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3191 * @return WatchedItem
3193 public function getWatchedItem( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3194 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3196 if ( isset( $this->mWatchedItems[$key] ) ) {
3197 return $this->mWatchedItems[$key];
3200 if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
3201 $this->mWatchedItems = array();
3204 $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title, $checkRights );
3205 return $this->mWatchedItems[$key];
3209 * Check the watched status of an article.
3210 * @since 1.22 $checkRights parameter added
3211 * @param Title $title Title of the article to look at
3212 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3213 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3214 * @return bool
3216 public function isWatched( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3217 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3221 * Watch an article.
3222 * @since 1.22 $checkRights parameter added
3223 * @param Title $title Title of the article to look at
3224 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3225 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3227 public function addWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3228 $this->getWatchedItem( $title, $checkRights )->addWatch();
3229 $this->invalidateCache();
3233 * Stop watching an article.
3234 * @since 1.22 $checkRights parameter added
3235 * @param Title $title Title of the article to look at
3236 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3237 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3239 public function removeWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3240 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3241 $this->invalidateCache();
3245 * Clear the user's notification timestamp for the given title.
3246 * If e-notif e-mails are on, they will receive notification mails on
3247 * the next change of the page if it's watched etc.
3248 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3249 * @param Title $title Title of the article to look at
3250 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3252 public function clearNotification( &$title, $oldid = 0 ) {
3253 global $wgUseEnotif, $wgShowUpdatedMarker;
3255 // Do nothing if the database is locked to writes
3256 if ( wfReadOnly() ) {
3257 return;
3260 // Do nothing if not allowed to edit the watchlist
3261 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3262 return;
3265 // If we're working on user's talk page, we should update the talk page message indicator
3266 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3267 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3268 return;
3271 $nextid = $oldid ? $title->getNextRevisionID( $oldid ) : null;
3273 if ( !$oldid || !$nextid ) {
3274 // If we're looking at the latest revision, we should definitely clear it
3275 $this->setNewtalk( false );
3276 } else {
3277 // Otherwise we should update its revision, if it's present
3278 if ( $this->getNewtalk() ) {
3279 // Naturally the other one won't clear by itself
3280 $this->setNewtalk( false );
3281 $this->setNewtalk( true, Revision::newFromId( $nextid ) );
3286 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3287 return;
3290 if ( $this->isAnon() ) {
3291 // Nothing else to do...
3292 return;
3295 // Only update the timestamp if the page is being watched.
3296 // The query to find out if it is watched is cached both in memcached and per-invocation,
3297 // and when it does have to be executed, it can be on a slave
3298 // If this is the user's newtalk page, we always update the timestamp
3299 $force = '';
3300 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3301 $force = 'force';
3304 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3308 * Resets all of the given user's page-change notification timestamps.
3309 * If e-notif e-mails are on, they will receive notification mails on
3310 * the next change of any watched page.
3311 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3313 public function clearAllNotifications() {
3314 if ( wfReadOnly() ) {
3315 return;
3318 // Do nothing if not allowed to edit the watchlist
3319 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3320 return;
3323 global $wgUseEnotif, $wgShowUpdatedMarker;
3324 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3325 $this->setNewtalk( false );
3326 return;
3328 $id = $this->getId();
3329 if ( $id != 0 ) {
3330 $dbw = wfGetDB( DB_MASTER );
3331 $dbw->update( 'watchlist',
3332 array( /* SET */ 'wl_notificationtimestamp' => null ),
3333 array( /* WHERE */ 'wl_user' => $id ),
3334 __METHOD__
3336 // We also need to clear here the "you have new message" notification for the own user_talk page;
3337 // it's cleared one page view later in WikiPage::doViewUpdates().
3342 * Set a cookie on the user's client. Wrapper for
3343 * WebResponse::setCookie
3344 * @param string $name Name of the cookie to set
3345 * @param string $value Value to set
3346 * @param int $exp Expiration time, as a UNIX time value;
3347 * if 0 or not specified, use the default $wgCookieExpiration
3348 * @param bool $secure
3349 * true: Force setting the secure attribute when setting the cookie
3350 * false: Force NOT setting the secure attribute when setting the cookie
3351 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3352 * @param array $params Array of options sent passed to WebResponse::setcookie()
3354 protected function setCookie( $name, $value, $exp = 0, $secure = null, $params = array() ) {
3355 $params['secure'] = $secure;
3356 $this->getRequest()->response()->setcookie( $name, $value, $exp, $params );
3360 * Clear a cookie on the user's client
3361 * @param string $name Name of the cookie to clear
3362 * @param bool $secure
3363 * true: Force setting the secure attribute when setting the cookie
3364 * false: Force NOT setting the secure attribute when setting the cookie
3365 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3366 * @param array $params Array of options sent passed to WebResponse::setcookie()
3368 protected function clearCookie( $name, $secure = null, $params = array() ) {
3369 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3373 * Set the default cookies for this session on the user's client.
3375 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3376 * is passed.
3377 * @param bool $secure Whether to force secure/insecure cookies or use default
3378 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3380 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3381 if ( $request === null ) {
3382 $request = $this->getRequest();
3385 $this->load();
3386 if ( 0 == $this->mId ) {
3387 return;
3389 if ( !$this->mToken ) {
3390 // When token is empty or NULL generate a new one and then save it to the database
3391 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3392 // Simply by setting every cell in the user_token column to NULL and letting them be
3393 // regenerated as users log back into the wiki.
3394 $this->setToken();
3395 $this->saveSettings();
3397 $session = array(
3398 'wsUserID' => $this->mId,
3399 'wsToken' => $this->mToken,
3400 'wsUserName' => $this->getName()
3402 $cookies = array(
3403 'UserID' => $this->mId,
3404 'UserName' => $this->getName(),
3406 if ( $rememberMe ) {
3407 $cookies['Token'] = $this->mToken;
3408 } else {
3409 $cookies['Token'] = false;
3412 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3414 foreach ( $session as $name => $value ) {
3415 $request->setSessionData( $name, $value );
3417 foreach ( $cookies as $name => $value ) {
3418 if ( $value === false ) {
3419 $this->clearCookie( $name );
3420 } else {
3421 $this->setCookie( $name, $value, 0, $secure );
3426 * If wpStickHTTPS was selected, also set an insecure cookie that
3427 * will cause the site to redirect the user to HTTPS, if they access
3428 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3429 * as the one set by centralauth (bug 53538). Also set it to session, or
3430 * standard time setting, based on if rememberme was set.
3432 if ( $request->getCheck( 'wpStickHTTPS' ) || $this->requiresHTTPS() ) {
3433 $this->setCookie(
3434 'forceHTTPS',
3435 'true',
3436 $rememberMe ? 0 : null,
3437 false,
3438 array( 'prefix' => '' ) // no prefix
3444 * Log this user out.
3446 public function logout() {
3447 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3448 $this->doLogout();
3453 * Clear the user's cookies and session, and reset the instance cache.
3454 * @see logout()
3456 public function doLogout() {
3457 $this->clearInstanceCache( 'defaults' );
3459 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3461 $this->clearCookie( 'UserID' );
3462 $this->clearCookie( 'Token' );
3463 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3465 // Remember when user logged out, to prevent seeing cached pages
3466 $this->setCookie( 'LoggedOut', time(), time() + 86400 );
3470 * Save this user's settings into the database.
3471 * @todo Only rarely do all these fields need to be set!
3473 public function saveSettings() {
3474 global $wgAuth;
3476 $this->load();
3477 $this->loadPasswords();
3478 if ( wfReadOnly() ) {
3479 return;
3481 if ( 0 == $this->mId ) {
3482 return;
3485 $this->mTouched = self::newTouchedTimestamp();
3486 if ( !$wgAuth->allowSetLocalPassword() ) {
3487 $this->mPassword = self::getPasswordFactory()->newFromCiphertext( null );
3490 $dbw = wfGetDB( DB_MASTER );
3491 $dbw->update( 'user',
3492 array( /* SET */
3493 'user_name' => $this->mName,
3494 'user_password' => $this->mPassword->toString(),
3495 'user_newpassword' => $this->mNewpassword->toString(),
3496 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3497 'user_real_name' => $this->mRealName,
3498 'user_email' => $this->mEmail,
3499 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3500 'user_touched' => $dbw->timestamp( $this->mTouched ),
3501 'user_token' => strval( $this->mToken ),
3502 'user_email_token' => $this->mEmailToken,
3503 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3504 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires ),
3505 ), array( /* WHERE */
3506 'user_id' => $this->mId
3507 ), __METHOD__
3510 $this->saveOptions();
3512 wfRunHooks( 'UserSaveSettings', array( $this ) );
3513 $this->clearSharedCache();
3514 $this->getUserPage()->invalidateCache();
3518 * If only this user's username is known, and it exists, return the user ID.
3519 * @return int
3521 public function idForName() {
3522 $s = trim( $this->getName() );
3523 if ( $s === '' ) {
3524 return 0;
3527 $dbr = wfGetDB( DB_SLAVE );
3528 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
3529 if ( $id === false ) {
3530 $id = 0;
3532 return $id;
3536 * Add a user to the database, return the user object
3538 * @param string $name Username to add
3539 * @param array $params Array of Strings Non-default parameters to save to
3540 * the database as user_* fields:
3541 * - password: The user's password hash. Password logins will be disabled
3542 * if this is omitted.
3543 * - newpassword: Hash for a temporary password that has been mailed to
3544 * the user.
3545 * - email: The user's email address.
3546 * - email_authenticated: The email authentication timestamp.
3547 * - real_name: The user's real name.
3548 * - options: An associative array of non-default options.
3549 * - token: Random authentication token. Do not set.
3550 * - registration: Registration timestamp. Do not set.
3552 * @return User|null User object, or null if the username already exists.
3554 public static function createNew( $name, $params = array() ) {
3555 $user = new User;
3556 $user->load();
3557 $user->loadPasswords();
3558 $user->setToken(); // init token
3559 if ( isset( $params['options'] ) ) {
3560 $user->mOptions = $params['options'] + (array)$user->mOptions;
3561 unset( $params['options'] );
3563 $dbw = wfGetDB( DB_MASTER );
3564 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3566 $fields = array(
3567 'user_id' => $seqVal,
3568 'user_name' => $name,
3569 'user_password' => $user->mPassword->toString(),
3570 'user_newpassword' => $user->mNewpassword->toString(),
3571 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
3572 'user_email' => $user->mEmail,
3573 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3574 'user_real_name' => $user->mRealName,
3575 'user_token' => strval( $user->mToken ),
3576 'user_registration' => $dbw->timestamp( $user->mRegistration ),
3577 'user_editcount' => 0,
3578 'user_touched' => $dbw->timestamp( self::newTouchedTimestamp() ),
3580 foreach ( $params as $name => $value ) {
3581 $fields["user_$name"] = $value;
3583 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
3584 if ( $dbw->affectedRows() ) {
3585 $newUser = User::newFromId( $dbw->insertId() );
3586 } else {
3587 $newUser = null;
3589 return $newUser;
3593 * Add this existing user object to the database. If the user already
3594 * exists, a fatal status object is returned, and the user object is
3595 * initialised with the data from the database.
3597 * Previously, this function generated a DB error due to a key conflict
3598 * if the user already existed. Many extension callers use this function
3599 * in code along the lines of:
3601 * $user = User::newFromName( $name );
3602 * if ( !$user->isLoggedIn() ) {
3603 * $user->addToDatabase();
3605 * // do something with $user...
3607 * However, this was vulnerable to a race condition (bug 16020). By
3608 * initialising the user object if the user exists, we aim to support this
3609 * calling sequence as far as possible.
3611 * Note that if the user exists, this function will acquire a write lock,
3612 * so it is still advisable to make the call conditional on isLoggedIn(),
3613 * and to commit the transaction after calling.
3615 * @throws MWException
3616 * @return Status
3618 public function addToDatabase() {
3619 $this->load();
3620 $this->loadPasswords();
3621 if ( !$this->mToken ) {
3622 $this->setToken(); // init token
3625 $this->mTouched = self::newTouchedTimestamp();
3627 $dbw = wfGetDB( DB_MASTER );
3628 $inWrite = $dbw->writesOrCallbacksPending();
3629 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3630 $dbw->insert( 'user',
3631 array(
3632 'user_id' => $seqVal,
3633 'user_name' => $this->mName,
3634 'user_password' => $this->mPassword->toString(),
3635 'user_newpassword' => $this->mNewpassword->toString(),
3636 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3637 'user_email' => $this->mEmail,
3638 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3639 'user_real_name' => $this->mRealName,
3640 'user_token' => strval( $this->mToken ),
3641 'user_registration' => $dbw->timestamp( $this->mRegistration ),
3642 'user_editcount' => 0,
3643 'user_touched' => $dbw->timestamp( $this->mTouched ),
3644 ), __METHOD__,
3645 array( 'IGNORE' )
3647 if ( !$dbw->affectedRows() ) {
3648 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3649 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3650 if ( $inWrite ) {
3651 // Can't commit due to pending writes that may need atomicity.
3652 // This may cause some lock contention unlike the case below.
3653 $options = array( 'LOCK IN SHARE MODE' );
3654 $flags = self::READ_LOCKING;
3655 } else {
3656 // Often, this case happens early in views before any writes when
3657 // using CentralAuth. It's should be OK to commit and break the snapshot.
3658 $dbw->commit( __METHOD__, 'flush' );
3659 $options = array();
3660 $flags = 0;
3662 $this->mId = $dbw->selectField( 'user', 'user_id',
3663 array( 'user_name' => $this->mName ), __METHOD__, $options );
3664 $loaded = false;
3665 if ( $this->mId ) {
3666 if ( $this->loadFromDatabase( $flags ) ) {
3667 $loaded = true;
3670 if ( !$loaded ) {
3671 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
3672 "to insert user '{$this->mName}' row, but it was not present in select!" );
3674 return Status::newFatal( 'userexists' );
3676 $this->mId = $dbw->insertId();
3678 // Clear instance cache other than user table data, which is already accurate
3679 $this->clearInstanceCache();
3681 $this->saveOptions();
3682 return Status::newGood();
3686 * If this user is logged-in and blocked,
3687 * block any IP address they've successfully logged in from.
3688 * @return bool A block was spread
3690 public function spreadAnyEditBlock() {
3691 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3692 return $this->spreadBlock();
3694 return false;
3698 * If this (non-anonymous) user is blocked,
3699 * block the IP address they've successfully logged in from.
3700 * @return bool A block was spread
3702 protected function spreadBlock() {
3703 wfDebug( __METHOD__ . "()\n" );
3704 $this->load();
3705 if ( $this->mId == 0 ) {
3706 return false;
3709 $userblock = Block::newFromTarget( $this->getName() );
3710 if ( !$userblock ) {
3711 return false;
3714 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3718 * Get whether the user is explicitly blocked from account creation.
3719 * @return bool|Block
3721 public function isBlockedFromCreateAccount() {
3722 $this->getBlockedStatus();
3723 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
3724 return $this->mBlock;
3727 # bug 13611: if the IP address the user is trying to create an account from is
3728 # blocked with createaccount disabled, prevent new account creation there even
3729 # when the user is logged in
3730 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3731 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
3733 return $this->mBlockedFromCreateAccount instanceof Block
3734 && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
3735 ? $this->mBlockedFromCreateAccount
3736 : false;
3740 * Get whether the user is blocked from using Special:Emailuser.
3741 * @return bool
3743 public function isBlockedFromEmailuser() {
3744 $this->getBlockedStatus();
3745 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
3749 * Get whether the user is allowed to create an account.
3750 * @return bool
3752 public function isAllowedToCreateAccount() {
3753 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3757 * Get this user's personal page title.
3759 * @return Title User's personal page title
3761 public function getUserPage() {
3762 return Title::makeTitle( NS_USER, $this->getName() );
3766 * Get this user's talk page title.
3768 * @return Title User's talk page title
3770 public function getTalkPage() {
3771 $title = $this->getUserPage();
3772 return $title->getTalkPage();
3776 * Determine whether the user is a newbie. Newbies are either
3777 * anonymous IPs, or the most recently created accounts.
3778 * @return bool
3780 public function isNewbie() {
3781 return !$this->isAllowed( 'autoconfirmed' );
3785 * Check to see if the given clear-text password is one of the accepted passwords
3786 * @param string $password User password
3787 * @return bool True if the given password is correct, otherwise False
3789 public function checkPassword( $password ) {
3790 global $wgAuth, $wgLegacyEncoding;
3791 $this->loadPasswords();
3793 // Certain authentication plugins do NOT want to save
3794 // domain passwords in a mysql database, so we should
3795 // check this (in case $wgAuth->strict() is false).
3797 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3798 return true;
3799 } elseif ( $wgAuth->strict() ) {
3800 // Auth plugin doesn't allow local authentication
3801 return false;
3802 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3803 // Auth plugin doesn't allow local authentication for this user name
3804 return false;
3807 $passwordFactory = self::getPasswordFactory();
3808 if ( !$this->mPassword->equals( $password ) ) {
3809 if ( $wgLegacyEncoding ) {
3810 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3811 // Check for this with iconv
3812 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3813 if ( $cp1252Password === $password || !$this->mPassword->equals( $cp1252Password ) ) {
3814 return false;
3816 } else {
3817 return false;
3821 if ( $passwordFactory->needsUpdate( $this->mPassword ) ) {
3822 $this->mPassword = $passwordFactory->newFromPlaintext( $password );
3823 $this->saveSettings();
3826 return true;
3830 * Check if the given clear-text password matches the temporary password
3831 * sent by e-mail for password reset operations.
3833 * @param string $plaintext
3835 * @return bool True if matches, false otherwise
3837 public function checkTemporaryPassword( $plaintext ) {
3838 global $wgNewPasswordExpiry;
3840 $this->load();
3841 $this->loadPasswords();
3842 if ( $this->mNewpassword->equals( $plaintext ) ) {
3843 if ( is_null( $this->mNewpassTime ) ) {
3844 return true;
3846 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
3847 return ( time() < $expiry );
3848 } else {
3849 return false;
3854 * Alias for getEditToken.
3855 * @deprecated since 1.19, use getEditToken instead.
3857 * @param string|array $salt Array of Strings Optional function-specific data for hashing
3858 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3859 * @return string The new edit token
3861 public function editToken( $salt = '', $request = null ) {
3862 wfDeprecated( __METHOD__, '1.19' );
3863 return $this->getEditToken( $salt, $request );
3867 * Initialize (if necessary) and return a session token value
3868 * which can be used in edit forms to show that the user's
3869 * login credentials aren't being hijacked with a foreign form
3870 * submission.
3872 * @since 1.19
3874 * @param string|array $salt Array of Strings Optional function-specific data for hashing
3875 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3876 * @return string The new edit token
3878 public function getEditToken( $salt = '', $request = null ) {
3879 if ( $request == null ) {
3880 $request = $this->getRequest();
3883 if ( $this->isAnon() ) {
3884 return self::EDIT_TOKEN_SUFFIX;
3885 } else {
3886 $token = $request->getSessionData( 'wsEditToken' );
3887 if ( $token === null ) {
3888 $token = MWCryptRand::generateHex( 32 );
3889 $request->setSessionData( 'wsEditToken', $token );
3891 if ( is_array( $salt ) ) {
3892 $salt = implode( '|', $salt );
3894 return md5( $token . $salt ) . self::EDIT_TOKEN_SUFFIX;
3899 * Generate a looking random token for various uses.
3901 * @return string The new random token
3902 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
3903 * wfRandomString for pseudo-randomness.
3905 public static function generateToken() {
3906 return MWCryptRand::generateHex( 32 );
3910 * Check given value against the token value stored in the session.
3911 * A match should confirm that the form was submitted from the
3912 * user's own login session, not a form submission from a third-party
3913 * site.
3915 * @param string $val Input value to compare
3916 * @param string $salt Optional function-specific data for hashing
3917 * @param WebRequest|null $request Object to use or null to use $wgRequest
3918 * @return bool Whether the token matches
3920 public function matchEditToken( $val, $salt = '', $request = null ) {
3921 $sessionToken = $this->getEditToken( $salt, $request );
3922 if ( $val != $sessionToken ) {
3923 wfDebug( "User::matchEditToken: broken session data\n" );
3926 return $val == $sessionToken;
3930 * Check given value against the token value stored in the session,
3931 * ignoring the suffix.
3933 * @param string $val Input value to compare
3934 * @param string $salt Optional function-specific data for hashing
3935 * @param WebRequest|null $request Object to use or null to use $wgRequest
3936 * @return bool Whether the token matches
3938 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3939 $sessionToken = $this->getEditToken( $salt, $request );
3940 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3944 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3945 * mail to the user's given address.
3947 * @param string $type Message to send, either "created", "changed" or "set"
3948 * @return Status
3950 public function sendConfirmationMail( $type = 'created' ) {
3951 global $wgLang;
3952 $expiration = null; // gets passed-by-ref and defined in next line.
3953 $token = $this->confirmationToken( $expiration );
3954 $url = $this->confirmationTokenUrl( $token );
3955 $invalidateURL = $this->invalidationTokenUrl( $token );
3956 $this->saveSettings();
3958 if ( $type == 'created' || $type === false ) {
3959 $message = 'confirmemail_body';
3960 } elseif ( $type === true ) {
3961 $message = 'confirmemail_body_changed';
3962 } else {
3963 // Messages: confirmemail_body_changed, confirmemail_body_set
3964 $message = 'confirmemail_body_' . $type;
3967 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3968 wfMessage( $message,
3969 $this->getRequest()->getIP(),
3970 $this->getName(),
3971 $url,
3972 $wgLang->timeanddate( $expiration, false ),
3973 $invalidateURL,
3974 $wgLang->date( $expiration, false ),
3975 $wgLang->time( $expiration, false ) )->text() );
3979 * Send an e-mail to this user's account. Does not check for
3980 * confirmed status or validity.
3982 * @param string $subject Message subject
3983 * @param string $body Message body
3984 * @param string $from Optional From address; if unspecified, default
3985 * $wgPasswordSender will be used.
3986 * @param string $replyto Reply-To address
3987 * @return Status
3989 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3990 if ( is_null( $from ) ) {
3991 global $wgPasswordSender;
3992 $sender = new MailAddress( $wgPasswordSender,
3993 wfMessage( 'emailsender' )->inContentLanguage()->text() );
3994 } else {
3995 $sender = new MailAddress( $from );
3998 $to = new MailAddress( $this );
3999 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
4003 * Generate, store, and return a new e-mail confirmation code.
4004 * A hash (unsalted, since it's used as a key) is stored.
4006 * @note Call saveSettings() after calling this function to commit
4007 * this change to the database.
4009 * @param string &$expiration Accepts the expiration time
4010 * @return string New token
4012 protected function confirmationToken( &$expiration ) {
4013 global $wgUserEmailConfirmationTokenExpiry;
4014 $now = time();
4015 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
4016 $expiration = wfTimestamp( TS_MW, $expires );
4017 $this->load();
4018 $token = MWCryptRand::generateHex( 32 );
4019 $hash = md5( $token );
4020 $this->mEmailToken = $hash;
4021 $this->mEmailTokenExpires = $expiration;
4022 return $token;
4026 * Return a URL the user can use to confirm their email address.
4027 * @param string $token Accepts the email confirmation token
4028 * @return string New token URL
4030 protected function confirmationTokenUrl( $token ) {
4031 return $this->getTokenUrl( 'ConfirmEmail', $token );
4035 * Return a URL the user can use to invalidate their email address.
4036 * @param string $token Accepts the email confirmation token
4037 * @return string New token URL
4039 protected function invalidationTokenUrl( $token ) {
4040 return $this->getTokenUrl( 'InvalidateEmail', $token );
4044 * Internal function to format the e-mail validation/invalidation URLs.
4045 * This uses a quickie hack to use the
4046 * hardcoded English names of the Special: pages, for ASCII safety.
4048 * @note Since these URLs get dropped directly into emails, using the
4049 * short English names avoids insanely long URL-encoded links, which
4050 * also sometimes can get corrupted in some browsers/mailers
4051 * (bug 6957 with Gmail and Internet Explorer).
4053 * @param string $page Special page
4054 * @param string $token Token
4055 * @return string Formatted URL
4057 protected function getTokenUrl( $page, $token ) {
4058 // Hack to bypass localization of 'Special:'
4059 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
4060 return $title->getCanonicalURL();
4064 * Mark the e-mail address confirmed.
4066 * @note Call saveSettings() after calling this function to commit the change.
4068 * @return bool
4070 public function confirmEmail() {
4071 // Check if it's already confirmed, so we don't touch the database
4072 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4073 if ( !$this->isEmailConfirmed() ) {
4074 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4075 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
4077 return true;
4081 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4082 * address if it was already confirmed.
4084 * @note Call saveSettings() after calling this function to commit the change.
4085 * @return bool Returns true
4087 public function invalidateEmail() {
4088 $this->load();
4089 $this->mEmailToken = null;
4090 $this->mEmailTokenExpires = null;
4091 $this->setEmailAuthenticationTimestamp( null );
4092 $this->mEmail = '';
4093 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
4094 return true;
4098 * Set the e-mail authentication timestamp.
4099 * @param string $timestamp TS_MW timestamp
4101 public function setEmailAuthenticationTimestamp( $timestamp ) {
4102 $this->load();
4103 $this->mEmailAuthenticated = $timestamp;
4104 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
4108 * Is this user allowed to send e-mails within limits of current
4109 * site configuration?
4110 * @return bool
4112 public function canSendEmail() {
4113 global $wgEnableEmail, $wgEnableUserEmail;
4114 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4115 return false;
4117 $canSend = $this->isEmailConfirmed();
4118 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
4119 return $canSend;
4123 * Is this user allowed to receive e-mails within limits of current
4124 * site configuration?
4125 * @return bool
4127 public function canReceiveEmail() {
4128 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4132 * Is this user's e-mail address valid-looking and confirmed within
4133 * limits of the current site configuration?
4135 * @note If $wgEmailAuthentication is on, this may require the user to have
4136 * confirmed their address by returning a code or using a password
4137 * sent to the address from the wiki.
4139 * @return bool
4141 public function isEmailConfirmed() {
4142 global $wgEmailAuthentication;
4143 $this->load();
4144 $confirmed = true;
4145 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4146 if ( $this->isAnon() ) {
4147 return false;
4149 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4150 return false;
4152 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4153 return false;
4155 return true;
4156 } else {
4157 return $confirmed;
4162 * Check whether there is an outstanding request for e-mail confirmation.
4163 * @return bool
4165 public function isEmailConfirmationPending() {
4166 global $wgEmailAuthentication;
4167 return $wgEmailAuthentication &&
4168 !$this->isEmailConfirmed() &&
4169 $this->mEmailToken &&
4170 $this->mEmailTokenExpires > wfTimestamp();
4174 * Get the timestamp of account creation.
4176 * @return string|bool|null Timestamp of account creation, false for
4177 * non-existent/anonymous user accounts, or null if existing account
4178 * but information is not in database.
4180 public function getRegistration() {
4181 if ( $this->isAnon() ) {
4182 return false;
4184 $this->load();
4185 return $this->mRegistration;
4189 * Get the timestamp of the first edit
4191 * @return string|bool Timestamp of first edit, or false for
4192 * non-existent/anonymous user accounts.
4194 public function getFirstEditTimestamp() {
4195 if ( $this->getId() == 0 ) {
4196 return false; // anons
4198 $dbr = wfGetDB( DB_SLAVE );
4199 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4200 array( 'rev_user' => $this->getId() ),
4201 __METHOD__,
4202 array( 'ORDER BY' => 'rev_timestamp ASC' )
4204 if ( !$time ) {
4205 return false; // no edits
4207 return wfTimestamp( TS_MW, $time );
4211 * Get the permissions associated with a given list of groups
4213 * @param array $groups Array of Strings List of internal group names
4214 * @return array Array of Strings List of permission key names for given groups combined
4216 public static function getGroupPermissions( $groups ) {
4217 global $wgGroupPermissions, $wgRevokePermissions;
4218 $rights = array();
4219 // grant every granted permission first
4220 foreach ( $groups as $group ) {
4221 if ( isset( $wgGroupPermissions[$group] ) ) {
4222 $rights = array_merge( $rights,
4223 // array_filter removes empty items
4224 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4227 // now revoke the revoked permissions
4228 foreach ( $groups as $group ) {
4229 if ( isset( $wgRevokePermissions[$group] ) ) {
4230 $rights = array_diff( $rights,
4231 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4234 return array_unique( $rights );
4238 * Get all the groups who have a given permission
4240 * @param string $role Role to check
4241 * @return array Array of Strings List of internal group names with the given permission
4243 public static function getGroupsWithPermission( $role ) {
4244 global $wgGroupPermissions;
4245 $allowedGroups = array();
4246 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4247 if ( self::groupHasPermission( $group, $role ) ) {
4248 $allowedGroups[] = $group;
4251 return $allowedGroups;
4255 * Check, if the given group has the given permission
4257 * If you're wanting to check whether all users have a permission, use
4258 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4259 * from anyone.
4261 * @since 1.21
4262 * @param string $group Group to check
4263 * @param string $role Role to check
4264 * @return bool
4266 public static function groupHasPermission( $group, $role ) {
4267 global $wgGroupPermissions, $wgRevokePermissions;
4268 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4269 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4273 * Check if all users have the given permission
4275 * @since 1.22
4276 * @param string $right Right to check
4277 * @return bool
4279 public static function isEveryoneAllowed( $right ) {
4280 global $wgGroupPermissions, $wgRevokePermissions;
4281 static $cache = array();
4283 // Use the cached results, except in unit tests which rely on
4284 // being able change the permission mid-request
4285 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4286 return $cache[$right];
4289 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
4290 $cache[$right] = false;
4291 return false;
4294 // If it's revoked anywhere, then everyone doesn't have it
4295 foreach ( $wgRevokePermissions as $rights ) {
4296 if ( isset( $rights[$right] ) && $rights[$right] ) {
4297 $cache[$right] = false;
4298 return false;
4302 // Allow extensions (e.g. OAuth) to say false
4303 if ( !wfRunHooks( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4304 $cache[$right] = false;
4305 return false;
4308 $cache[$right] = true;
4309 return true;
4313 * Get the localized descriptive name for a group, if it exists
4315 * @param string $group Internal group name
4316 * @return string Localized descriptive group name
4318 public static function getGroupName( $group ) {
4319 $msg = wfMessage( "group-$group" );
4320 return $msg->isBlank() ? $group : $msg->text();
4324 * Get the localized descriptive name for a member of a group, if it exists
4326 * @param string $group Internal group name
4327 * @param string $username Username for gender (since 1.19)
4328 * @return string Localized name for group member
4330 public static function getGroupMember( $group, $username = '#' ) {
4331 $msg = wfMessage( "group-$group-member", $username );
4332 return $msg->isBlank() ? $group : $msg->text();
4336 * Return the set of defined explicit groups.
4337 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4338 * are not included, as they are defined automatically, not in the database.
4339 * @return array Array of internal group names
4341 public static function getAllGroups() {
4342 global $wgGroupPermissions, $wgRevokePermissions;
4343 return array_diff(
4344 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4345 self::getImplicitGroups()
4350 * Get a list of all available permissions.
4351 * @return array Array of permission names
4353 public static function getAllRights() {
4354 if ( self::$mAllRights === false ) {
4355 global $wgAvailableRights;
4356 if ( count( $wgAvailableRights ) ) {
4357 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
4358 } else {
4359 self::$mAllRights = self::$mCoreRights;
4361 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
4363 return self::$mAllRights;
4367 * Get a list of implicit groups
4368 * @return array Array of Strings Array of internal group names
4370 public static function getImplicitGroups() {
4371 global $wgImplicitGroups;
4373 $groups = $wgImplicitGroups;
4374 # Deprecated, use $wgImplictGroups instead
4375 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) );
4377 return $groups;
4381 * Get the title of a page describing a particular group
4383 * @param string $group Internal group name
4384 * @return Title|bool Title of the page if it exists, false otherwise
4386 public static function getGroupPage( $group ) {
4387 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4388 if ( $msg->exists() ) {
4389 $title = Title::newFromText( $msg->text() );
4390 if ( is_object( $title ) ) {
4391 return $title;
4394 return false;
4398 * Create a link to the group in HTML, if available;
4399 * else return the group name.
4401 * @param string $group Internal name of the group
4402 * @param string $text The text of the link
4403 * @return string HTML link to the group
4405 public static function makeGroupLinkHTML( $group, $text = '' ) {
4406 if ( $text == '' ) {
4407 $text = self::getGroupName( $group );
4409 $title = self::getGroupPage( $group );
4410 if ( $title ) {
4411 return Linker::link( $title, htmlspecialchars( $text ) );
4412 } else {
4413 return $text;
4418 * Create a link to the group in Wikitext, if available;
4419 * else return the group name.
4421 * @param string $group Internal name of the group
4422 * @param string $text The text of the link
4423 * @return string Wikilink to the group
4425 public static function makeGroupLinkWiki( $group, $text = '' ) {
4426 if ( $text == '' ) {
4427 $text = self::getGroupName( $group );
4429 $title = self::getGroupPage( $group );
4430 if ( $title ) {
4431 $page = $title->getPrefixedText();
4432 return "[[$page|$text]]";
4433 } else {
4434 return $text;
4439 * Returns an array of the groups that a particular group can add/remove.
4441 * @param string $group The group to check for whether it can add/remove
4442 * @return array Array( 'add' => array( addablegroups ),
4443 * 'remove' => array( removablegroups ),
4444 * 'add-self' => array( addablegroups to self),
4445 * 'remove-self' => array( removable groups from self) )
4447 public static function changeableByGroup( $group ) {
4448 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4450 $groups = array(
4451 'add' => array(),
4452 'remove' => array(),
4453 'add-self' => array(),
4454 'remove-self' => array()
4457 if ( empty( $wgAddGroups[$group] ) ) {
4458 // Don't add anything to $groups
4459 } elseif ( $wgAddGroups[$group] === true ) {
4460 // You get everything
4461 $groups['add'] = self::getAllGroups();
4462 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4463 $groups['add'] = $wgAddGroups[$group];
4466 // Same thing for remove
4467 if ( empty( $wgRemoveGroups[$group] ) ) {
4468 } elseif ( $wgRemoveGroups[$group] === true ) {
4469 $groups['remove'] = self::getAllGroups();
4470 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4471 $groups['remove'] = $wgRemoveGroups[$group];
4474 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4475 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4476 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4477 if ( is_int( $key ) ) {
4478 $wgGroupsAddToSelf['user'][] = $value;
4483 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4484 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4485 if ( is_int( $key ) ) {
4486 $wgGroupsRemoveFromSelf['user'][] = $value;
4491 // Now figure out what groups the user can add to him/herself
4492 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4493 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4494 // No idea WHY this would be used, but it's there
4495 $groups['add-self'] = User::getAllGroups();
4496 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4497 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4500 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4501 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4502 $groups['remove-self'] = User::getAllGroups();
4503 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4504 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4507 return $groups;
4511 * Returns an array of groups that this user can add and remove
4512 * @return array Array( 'add' => array( addablegroups ),
4513 * 'remove' => array( removablegroups ),
4514 * 'add-self' => array( addablegroups to self),
4515 * 'remove-self' => array( removable groups from self) )
4517 public function changeableGroups() {
4518 if ( $this->isAllowed( 'userrights' ) ) {
4519 // This group gives the right to modify everything (reverse-
4520 // compatibility with old "userrights lets you change
4521 // everything")
4522 // Using array_merge to make the groups reindexed
4523 $all = array_merge( User::getAllGroups() );
4524 return array(
4525 'add' => $all,
4526 'remove' => $all,
4527 'add-self' => array(),
4528 'remove-self' => array()
4532 // Okay, it's not so simple, we will have to go through the arrays
4533 $groups = array(
4534 'add' => array(),
4535 'remove' => array(),
4536 'add-self' => array(),
4537 'remove-self' => array()
4539 $addergroups = $this->getEffectiveGroups();
4541 foreach ( $addergroups as $addergroup ) {
4542 $groups = array_merge_recursive(
4543 $groups, $this->changeableByGroup( $addergroup )
4545 $groups['add'] = array_unique( $groups['add'] );
4546 $groups['remove'] = array_unique( $groups['remove'] );
4547 $groups['add-self'] = array_unique( $groups['add-self'] );
4548 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4550 return $groups;
4554 * Increment the user's edit-count field.
4555 * Will have no effect for anonymous users.
4557 public function incEditCount() {
4558 if ( !$this->isAnon() ) {
4559 $dbw = wfGetDB( DB_MASTER );
4560 $dbw->update(
4561 'user',
4562 array( 'user_editcount=user_editcount+1' ),
4563 array( 'user_id' => $this->getId() ),
4564 __METHOD__
4567 // Lazy initialization check...
4568 if ( $dbw->affectedRows() == 0 ) {
4569 // Now here's a goddamn hack...
4570 $dbr = wfGetDB( DB_SLAVE );
4571 if ( $dbr !== $dbw ) {
4572 // If we actually have a slave server, the count is
4573 // at least one behind because the current transaction
4574 // has not been committed and replicated.
4575 $this->initEditCount( 1 );
4576 } else {
4577 // But if DB_SLAVE is selecting the master, then the
4578 // count we just read includes the revision that was
4579 // just added in the working transaction.
4580 $this->initEditCount();
4584 // edit count in user cache too
4585 $this->invalidateCache();
4589 * Initialize user_editcount from data out of the revision table
4591 * @param int $add Edits to add to the count from the revision table
4592 * @return int Number of edits
4594 protected function initEditCount( $add = 0 ) {
4595 // Pull from a slave to be less cruel to servers
4596 // Accuracy isn't the point anyway here
4597 $dbr = wfGetDB( DB_SLAVE );
4598 $count = (int)$dbr->selectField(
4599 'revision',
4600 'COUNT(rev_user)',
4601 array( 'rev_user' => $this->getId() ),
4602 __METHOD__
4604 $count = $count + $add;
4606 $dbw = wfGetDB( DB_MASTER );
4607 $dbw->update(
4608 'user',
4609 array( 'user_editcount' => $count ),
4610 array( 'user_id' => $this->getId() ),
4611 __METHOD__
4614 return $count;
4618 * Get the description of a given right
4620 * @param string $right Right to query
4621 * @return string Localized description of the right
4623 public static function getRightDescription( $right ) {
4624 $key = "right-$right";
4625 $msg = wfMessage( $key );
4626 return $msg->isBlank() ? $right : $msg->text();
4630 * Make a new-style password hash
4632 * @param string $password Plain-text password
4633 * @param bool|string $salt Optional salt, may be random or the user ID.
4634 * If unspecified or false, will generate one automatically
4635 * @return string Password hash
4636 * @deprecated since 1.24, use Password class
4638 public static function crypt( $password, $salt = false ) {
4639 wfDeprecated( __METHOD__, '1.24' );
4640 $hash = self::getPasswordFactory()->newFromPlaintext( $password );
4641 return $hash->toString();
4645 * Compare a password hash with a plain-text password. Requires the user
4646 * ID if there's a chance that the hash is an old-style hash.
4648 * @param string $hash Password hash
4649 * @param string $password Plain-text password to compare
4650 * @param string|bool $userId User ID for old-style password salt
4652 * @return bool
4653 * @deprecated since 1.24, use Password class
4655 public static function comparePasswords( $hash, $password, $userId = false ) {
4656 wfDeprecated( __METHOD__, '1.24' );
4658 // Check for *really* old password hashes that don't even have a type
4659 // The old hash format was just an md5 hex hash, with no type information
4660 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4661 global $wgPasswordSalt;
4662 if ( $wgPasswordSalt ) {
4663 $password = ":B:{$userId}:{$hash}";
4664 } else {
4665 $password = ":A:{$hash}";
4669 $hash = self::getPasswordFactory()->newFromCiphertext( $hash );
4670 return $hash->equals( $password );
4674 * Add a newuser log entry for this user.
4675 * Before 1.19 the return value was always true.
4677 * @param string|bool $action Account creation type.
4678 * - String, one of the following values:
4679 * - 'create' for an anonymous user creating an account for himself.
4680 * This will force the action's performer to be the created user itself,
4681 * no matter the value of $wgUser
4682 * - 'create2' for a logged in user creating an account for someone else
4683 * - 'byemail' when the created user will receive its password by e-mail
4684 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4685 * - Boolean means whether the account was created by e-mail (deprecated):
4686 * - true will be converted to 'byemail'
4687 * - false will be converted to 'create' if this object is the same as
4688 * $wgUser and to 'create2' otherwise
4690 * @param string $reason User supplied reason
4692 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4694 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4695 global $wgUser, $wgNewUserLog;
4696 if ( empty( $wgNewUserLog ) ) {
4697 return true; // disabled
4700 if ( $action === true ) {
4701 $action = 'byemail';
4702 } elseif ( $action === false ) {
4703 if ( $this->getName() == $wgUser->getName() ) {
4704 $action = 'create';
4705 } else {
4706 $action = 'create2';
4710 if ( $action === 'create' || $action === 'autocreate' ) {
4711 $performer = $this;
4712 } else {
4713 $performer = $wgUser;
4716 $logEntry = new ManualLogEntry( 'newusers', $action );
4717 $logEntry->setPerformer( $performer );
4718 $logEntry->setTarget( $this->getUserPage() );
4719 $logEntry->setComment( $reason );
4720 $logEntry->setParameters( array(
4721 '4::userid' => $this->getId(),
4722 ) );
4723 $logid = $logEntry->insert();
4725 if ( $action !== 'autocreate' ) {
4726 $logEntry->publish( $logid );
4729 return (int)$logid;
4733 * Add an autocreate newuser log entry for this user
4734 * Used by things like CentralAuth and perhaps other authplugins.
4735 * Consider calling addNewUserLogEntry() directly instead.
4737 * @return bool
4739 public function addNewUserLogEntryAutoCreate() {
4740 $this->addNewUserLogEntry( 'autocreate' );
4742 return true;
4746 * Load the user options either from cache, the database or an array
4748 * @param array $data Rows for the current user out of the user_properties table
4750 protected function loadOptions( $data = null ) {
4751 global $wgContLang;
4753 $this->load();
4755 if ( $this->mOptionsLoaded ) {
4756 return;
4759 $this->mOptions = self::getDefaultOptions();
4761 if ( !$this->getId() ) {
4762 // For unlogged-in users, load language/variant options from request.
4763 // There's no need to do it for logged-in users: they can set preferences,
4764 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4765 // so don't override user's choice (especially when the user chooses site default).
4766 $variant = $wgContLang->getDefaultVariant();
4767 $this->mOptions['variant'] = $variant;
4768 $this->mOptions['language'] = $variant;
4769 $this->mOptionsLoaded = true;
4770 return;
4773 // Maybe load from the object
4774 if ( !is_null( $this->mOptionOverrides ) ) {
4775 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4776 foreach ( $this->mOptionOverrides as $key => $value ) {
4777 $this->mOptions[$key] = $value;
4779 } else {
4780 if ( !is_array( $data ) ) {
4781 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4782 // Load from database
4783 $dbr = wfGetDB( DB_SLAVE );
4785 $res = $dbr->select(
4786 'user_properties',
4787 array( 'up_property', 'up_value' ),
4788 array( 'up_user' => $this->getId() ),
4789 __METHOD__
4792 $this->mOptionOverrides = array();
4793 $data = array();
4794 foreach ( $res as $row ) {
4795 $data[$row->up_property] = $row->up_value;
4798 foreach ( $data as $property => $value ) {
4799 $this->mOptionOverrides[$property] = $value;
4800 $this->mOptions[$property] = $value;
4804 $this->mOptionsLoaded = true;
4806 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
4810 * Saves the non-default options for this user, as previously set e.g. via
4811 * setOption(), in the database's "user_properties" (preferences) table.
4812 * Usually used via saveSettings().
4814 protected function saveOptions() {
4815 $this->loadOptions();
4817 // Not using getOptions(), to keep hidden preferences in database
4818 $saveOptions = $this->mOptions;
4820 // Allow hooks to abort, for instance to save to a global profile.
4821 // Reset options to default state before saving.
4822 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4823 return;
4826 $userId = $this->getId();
4828 $insert_rows = array(); // all the new preference rows
4829 foreach ( $saveOptions as $key => $value ) {
4830 // Don't bother storing default values
4831 $defaultOption = self::getDefaultOption( $key );
4832 if ( ( $defaultOption === null && $value !== false && $value !== null )
4833 || $value != $defaultOption
4835 $insert_rows[] = array(
4836 'up_user' => $userId,
4837 'up_property' => $key,
4838 'up_value' => $value,
4843 $dbw = wfGetDB( DB_MASTER );
4845 $res = $dbw->select( 'user_properties',
4846 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__ );
4848 // Find prior rows that need to be removed or updated. These rows will
4849 // all be deleted (the later so that INSERT IGNORE applies the new values).
4850 $keysDelete = array();
4851 foreach ( $res as $row ) {
4852 if ( !isset( $saveOptions[$row->up_property] )
4853 || strcmp( $saveOptions[$row->up_property], $row->up_value ) != 0
4855 $keysDelete[] = $row->up_property;
4859 if ( count( $keysDelete ) ) {
4860 // Do the DELETE by PRIMARY KEY for prior rows.
4861 // In the past a very large portion of calls to this function are for setting
4862 // 'rememberpassword' for new accounts (a preference that has since been removed).
4863 // Doing a blanket per-user DELETE for new accounts with no rows in the table
4864 // caused gap locks on [max user ID,+infinity) which caused high contention since
4865 // updates would pile up on each other as they are for higher (newer) user IDs.
4866 // It might not be necessary these days, but it shouldn't hurt either.
4867 $dbw->delete( 'user_properties',
4868 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__ );
4870 // Insert the new preference rows
4871 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, array( 'IGNORE' ) );
4875 * Lazily instantiate and return a factory object for making passwords
4877 * @return PasswordFactory
4879 public static function getPasswordFactory() {
4880 if ( self::$mPasswordFactory === null ) {
4881 self::$mPasswordFactory = new PasswordFactory();
4882 self::$mPasswordFactory->init( RequestContext::getMain()->getConfig() );
4885 return self::$mPasswordFactory;
4889 * Provide an array of HTML5 attributes to put on an input element
4890 * intended for the user to enter a new password. This may include
4891 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4893 * Do *not* use this when asking the user to enter his current password!
4894 * Regardless of configuration, users may have invalid passwords for whatever
4895 * reason (e.g., they were set before requirements were tightened up).
4896 * Only use it when asking for a new password, like on account creation or
4897 * ResetPass.
4899 * Obviously, you still need to do server-side checking.
4901 * NOTE: A combination of bugs in various browsers means that this function
4902 * actually just returns array() unconditionally at the moment. May as
4903 * well keep it around for when the browser bugs get fixed, though.
4905 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4907 * @return array Array of HTML attributes suitable for feeding to
4908 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4909 * That will get confused by the boolean attribute syntax used.)
4911 public static function passwordChangeInputAttribs() {
4912 global $wgMinimalPasswordLength;
4914 if ( $wgMinimalPasswordLength == 0 ) {
4915 return array();
4918 # Note that the pattern requirement will always be satisfied if the
4919 # input is empty, so we need required in all cases.
4921 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4922 # if e-mail confirmation is being used. Since HTML5 input validation
4923 # is b0rked anyway in some browsers, just return nothing. When it's
4924 # re-enabled, fix this code to not output required for e-mail
4925 # registration.
4926 #$ret = array( 'required' );
4927 $ret = array();
4929 # We can't actually do this right now, because Opera 9.6 will print out
4930 # the entered password visibly in its error message! When other
4931 # browsers add support for this attribute, or Opera fixes its support,
4932 # we can add support with a version check to avoid doing this on Opera
4933 # versions where it will be a problem. Reported to Opera as
4934 # DSK-262266, but they don't have a public bug tracker for us to follow.
4936 if ( $wgMinimalPasswordLength > 1 ) {
4937 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4938 $ret['title'] = wfMessage( 'passwordtooshort' )
4939 ->numParams( $wgMinimalPasswordLength )->text();
4943 return $ret;
4947 * Return the list of user fields that should be selected to create
4948 * a new user object.
4949 * @return array
4951 public static function selectFields() {
4952 return array(
4953 'user_id',
4954 'user_name',
4955 'user_real_name',
4956 'user_email',
4957 'user_touched',
4958 'user_token',
4959 'user_email_authenticated',
4960 'user_email_token',
4961 'user_email_token_expires',
4962 'user_registration',
4963 'user_editcount',
4968 * Factory function for fatal permission-denied errors
4970 * @since 1.22
4971 * @param string $permission User right required
4972 * @return Status
4974 static function newFatalPermissionDeniedStatus( $permission ) {
4975 global $wgLang;
4977 $groups = array_map(
4978 array( 'User', 'makeGroupLinkWiki' ),
4979 User::getGroupsWithPermission( $permission )
4982 if ( $groups ) {
4983 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
4984 } else {
4985 return Status::newFatal( 'badaccess-group0' );