Support offsets in prefix searching
[mediawiki.git] / includes / User.php
blob5348020089bcc84ba4d96a73097f85595d899e4c
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 'editcontentmodel',
116 'editinterface',
117 'editprotected',
118 'editmyoptions',
119 'editmyprivateinfo',
120 'editmyusercss',
121 'editmyuserjs',
122 'editmywatchlist',
123 'editsemiprotected',
124 'editusercssjs', #deprecated
125 'editusercss',
126 'edituserjs',
127 'hideuser',
128 'import',
129 'importupload',
130 'ipblock-exempt',
131 'markbotedits',
132 'mergehistory',
133 'minoredit',
134 'move',
135 'movefile',
136 'move-categorypages',
137 'move-rootuserpages',
138 'move-subpages',
139 'nominornewtalk',
140 'noratelimit',
141 'override-export-depth',
142 'pagelang',
143 'passwordreset',
144 'patrol',
145 'patrolmarks',
146 'protect',
147 'proxyunbannable',
148 'purge',
149 'read',
150 'reupload',
151 'reupload-own',
152 'reupload-shared',
153 'rollback',
154 'sendemail',
155 'siteadmin',
156 'suppressionlog',
157 'suppressredirect',
158 'suppressrevision',
159 'unblockself',
160 'undelete',
161 'unwatchedpages',
162 'upload',
163 'upload_by_url',
164 'userrights',
165 'userrights-interwiki',
166 'viewmyprivateinfo',
167 'viewmywatchlist',
168 'viewsuppressed',
169 'writeapi',
173 * String Cached results of getAllRights()
175 protected static $mAllRights = false;
177 /** @name Cache variables */
178 //@{
179 public $mId;
181 public $mName;
183 public $mRealName;
186 * @todo Make this actually private
187 * @private
189 public $mPassword;
192 * @todo Make this actually private
193 * @private
195 public $mNewpassword;
197 public $mNewpassTime;
199 public $mEmail;
201 public $mTouched;
203 protected $mToken;
205 public $mEmailAuthenticated;
207 protected $mEmailToken;
209 protected $mEmailTokenExpires;
211 protected $mRegistration;
213 protected $mEditCount;
215 public $mGroups;
217 protected $mOptionOverrides;
219 protected $mPasswordExpires;
220 //@}
223 * Bool Whether the cache variables have been loaded.
225 //@{
226 public $mOptionsLoaded;
229 * Array with already loaded items or true if all items have been loaded.
231 protected $mLoadedItems = array();
232 //@}
235 * String Initialization data source if mLoadedItems!==true. May be one of:
236 * - 'defaults' anonymous user initialised from class defaults
237 * - 'name' initialise from mName
238 * - 'id' initialise from mId
239 * - 'session' log in from cookies or session if possible
241 * Use the User::newFrom*() family of functions to set this.
243 public $mFrom;
246 * Lazy-initialized variables, invalidated with clearInstanceCache
248 protected $mNewtalk;
250 protected $mDatePreference;
252 public $mBlockedby;
254 protected $mHash;
256 public $mRights;
258 protected $mBlockreason;
260 protected $mEffectiveGroups;
262 protected $mImplicitGroups;
264 protected $mFormerGroups;
266 protected $mBlockedGlobally;
268 protected $mLocked;
270 public $mHideName;
272 public $mOptions;
275 * @var WebRequest
277 private $mRequest;
279 /** @var Block */
280 public $mBlock;
282 /** @var bool */
283 protected $mAllowUsertalk;
285 /** @var Block */
286 private $mBlockedFromCreateAccount = false;
288 /** @var array */
289 private $mWatchedItems = array();
291 public static $idCacheByName = array();
294 * Lightweight constructor for an anonymous user.
295 * Use the User::newFrom* factory functions for other kinds of users.
297 * @see newFromName()
298 * @see newFromId()
299 * @see newFromConfirmationCode()
300 * @see newFromSession()
301 * @see newFromRow()
303 public function __construct() {
304 $this->clearInstanceCache( 'defaults' );
308 * @return string
310 public function __toString() {
311 return $this->getName();
315 * Load the user table data for this object from the source given by mFrom.
317 public function load() {
318 if ( $this->mLoadedItems === true ) {
319 return;
321 wfProfileIn( __METHOD__ );
323 // Set it now to avoid infinite recursion in accessors
324 $this->mLoadedItems = true;
326 switch ( $this->mFrom ) {
327 case 'defaults':
328 $this->loadDefaults();
329 break;
330 case 'name':
331 $this->mId = self::idFromName( $this->mName );
332 if ( !$this->mId ) {
333 // Nonexistent user placeholder object
334 $this->loadDefaults( $this->mName );
335 } else {
336 $this->loadFromId();
338 break;
339 case 'id':
340 $this->loadFromId();
341 break;
342 case 'session':
343 if ( !$this->loadFromSession() ) {
344 // Loading from session failed. Load defaults.
345 $this->loadDefaults();
347 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
348 break;
349 default:
350 wfProfileOut( __METHOD__ );
351 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
353 wfProfileOut( __METHOD__ );
357 * Load user table data, given mId has already been set.
358 * @return bool False if the ID does not exist, true otherwise
360 public function loadFromId() {
361 if ( $this->mId == 0 ) {
362 $this->loadDefaults();
363 return false;
366 // Try cache
367 $cache = $this->loadFromCache();
368 if ( !$cache ) {
369 wfDebug( "User: cache miss for user {$this->mId}\n" );
370 // Load from DB
371 if ( !$this->loadFromDatabase() ) {
372 // Can't load from ID, user is anonymous
373 return false;
375 $this->saveToCache();
378 $this->mLoadedItems = true;
380 return true;
384 * Load user data from shared cache, given mId has already been set.
386 * @return bool false if the ID does not exist or data is invalid, true otherwise
387 * @since 1.25
389 public function loadFromCache() {
390 global $wgMemc;
392 if ( $this->mId == 0 ) {
393 $this->loadDefaults();
394 return false;
397 $key = wfMemcKey( 'user', 'id', $this->mId );
398 $data = $wgMemc->get( $key );
399 if ( !is_array( $data ) || $data['mVersion'] < self::VERSION ) {
400 // Object is expired
401 return false;
404 wfDebug( "User: got user {$this->mId} from cache\n" );
406 // Restore from cache
407 foreach ( self::$mCacheVars as $name ) {
408 $this->$name = $data[$name];
411 return true;
415 * Save user data to the shared cache
417 public function saveToCache() {
418 $this->load();
419 $this->loadGroups();
420 $this->loadOptions();
421 if ( $this->isAnon() ) {
422 // Anonymous users are uncached
423 return;
425 $data = array();
426 foreach ( self::$mCacheVars as $name ) {
427 $data[$name] = $this->$name;
429 $data['mVersion'] = self::VERSION;
430 $key = wfMemcKey( 'user', 'id', $this->mId );
431 global $wgMemc;
432 $wgMemc->set( $key, $data );
435 /** @name newFrom*() static factory methods */
436 //@{
439 * Static factory method for creation from username.
441 * This is slightly less efficient than newFromId(), so use newFromId() if
442 * you have both an ID and a name handy.
444 * @param string $name Username, validated by Title::newFromText()
445 * @param string|bool $validate Validate username. Takes the same parameters as
446 * User::getCanonicalName(), except that true is accepted as an alias
447 * for 'valid', for BC.
449 * @return User|bool User object, or false if the username is invalid
450 * (e.g. if it contains illegal characters or is an IP address). If the
451 * username is not present in the database, the result will be a user object
452 * with a name, zero user ID and default settings.
454 public static function newFromName( $name, $validate = 'valid' ) {
455 if ( $validate === true ) {
456 $validate = 'valid';
458 $name = self::getCanonicalName( $name, $validate );
459 if ( $name === false ) {
460 return false;
461 } else {
462 // Create unloaded user object
463 $u = new User;
464 $u->mName = $name;
465 $u->mFrom = 'name';
466 $u->setItemLoaded( 'name' );
467 return $u;
472 * Static factory method for creation from a given user ID.
474 * @param int $id Valid user ID
475 * @return User The corresponding User object
477 public static function newFromId( $id ) {
478 $u = new User;
479 $u->mId = $id;
480 $u->mFrom = 'id';
481 $u->setItemLoaded( 'id' );
482 return $u;
486 * Factory method to fetch whichever user has a given email confirmation code.
487 * This code is generated when an account is created or its e-mail address
488 * has changed.
490 * If the code is invalid or has expired, returns NULL.
492 * @param string $code Confirmation code
493 * @return User|null
495 public static function newFromConfirmationCode( $code ) {
496 $dbr = wfGetDB( DB_SLAVE );
497 $id = $dbr->selectField( 'user', 'user_id', array(
498 'user_email_token' => md5( $code ),
499 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
500 ) );
501 if ( $id !== false ) {
502 return User::newFromId( $id );
503 } else {
504 return null;
509 * Create a new user object using data from session or cookies. If the
510 * login credentials are invalid, the result is an anonymous user.
512 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
513 * @return User
515 public static function newFromSession( WebRequest $request = null ) {
516 $user = new User;
517 $user->mFrom = 'session';
518 $user->mRequest = $request;
519 return $user;
523 * Create a new user object from a user row.
524 * The row should have the following fields from the user table in it:
525 * - either user_name or user_id to load further data if needed (or both)
526 * - user_real_name
527 * - all other fields (email, password, etc.)
528 * It is useless to provide the remaining fields if either user_id,
529 * user_name and user_real_name are not provided because the whole row
530 * will be loaded once more from the database when accessing them.
532 * @param stdClass $row A row from the user table
533 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
534 * @return User
536 public static function newFromRow( $row, $data = null ) {
537 $user = new User;
538 $user->loadFromRow( $row, $data );
539 return $user;
542 //@}
545 * Get the username corresponding to a given user ID
546 * @param int $id User ID
547 * @return string|bool The corresponding username
549 public static function whoIs( $id ) {
550 return UserCache::singleton()->getProp( $id, 'name' );
554 * Get the real name of a user given their user ID
556 * @param int $id User ID
557 * @return string|bool The corresponding user's real name
559 public static function whoIsReal( $id ) {
560 return UserCache::singleton()->getProp( $id, 'real_name' );
564 * Get database id given a user name
565 * @param string $name Username
566 * @return int|null The corresponding user's ID, or null if user is nonexistent
568 public static function idFromName( $name ) {
569 $nt = Title::makeTitleSafe( NS_USER, $name );
570 if ( is_null( $nt ) ) {
571 // Illegal name
572 return null;
575 if ( isset( self::$idCacheByName[$name] ) ) {
576 return self::$idCacheByName[$name];
579 $dbr = wfGetDB( DB_SLAVE );
580 $s = $dbr->selectRow(
581 'user',
582 array( 'user_id' ),
583 array( 'user_name' => $nt->getText() ),
584 __METHOD__
587 if ( $s === false ) {
588 $result = null;
589 } else {
590 $result = $s->user_id;
593 self::$idCacheByName[$name] = $result;
595 if ( count( self::$idCacheByName ) > 1000 ) {
596 self::$idCacheByName = array();
599 return $result;
603 * Reset the cache used in idFromName(). For use in tests.
605 public static function resetIdByNameCache() {
606 self::$idCacheByName = array();
610 * Does the string match an anonymous IPv4 address?
612 * This function exists for username validation, in order to reject
613 * usernames which are similar in form to IP addresses. Strings such
614 * as 300.300.300.300 will return true because it looks like an IP
615 * address, despite not being strictly valid.
617 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
618 * address because the usemod software would "cloak" anonymous IP
619 * addresses like this, if we allowed accounts like this to be created
620 * new users could get the old edits of these anonymous users.
622 * @param string $name Name to match
623 * @return bool
625 public static function isIP( $name ) {
626 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
627 || IP::isIPv6( $name );
631 * Is the input a valid username?
633 * Checks if the input is a valid username, we don't want an empty string,
634 * an IP address, anything that contains slashes (would mess up subpages),
635 * is longer than the maximum allowed username size or doesn't begin with
636 * a capital letter.
638 * @param string $name Name to match
639 * @return bool
641 public static function isValidUserName( $name ) {
642 global $wgContLang, $wgMaxNameChars;
644 if ( $name == ''
645 || User::isIP( $name )
646 || strpos( $name, '/' ) !== false
647 || strlen( $name ) > $wgMaxNameChars
648 || $name != $wgContLang->ucfirst( $name )
650 wfDebugLog( 'username', __METHOD__ .
651 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
652 return false;
655 // Ensure that the name can't be misresolved as a different title,
656 // such as with extra namespace keys at the start.
657 $parsed = Title::newFromText( $name );
658 if ( is_null( $parsed )
659 || $parsed->getNamespace()
660 || strcmp( $name, $parsed->getPrefixedText() ) ) {
661 wfDebugLog( 'username', __METHOD__ .
662 ": '$name' invalid due to ambiguous prefixes" );
663 return false;
666 // Check an additional blacklist of troublemaker characters.
667 // Should these be merged into the title char list?
668 $unicodeBlacklist = '/[' .
669 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
670 '\x{00a0}' . # non-breaking space
671 '\x{2000}-\x{200f}' . # various whitespace
672 '\x{2028}-\x{202f}' . # breaks and control chars
673 '\x{3000}' . # ideographic space
674 '\x{e000}-\x{f8ff}' . # private use
675 ']/u';
676 if ( preg_match( $unicodeBlacklist, $name ) ) {
677 wfDebugLog( 'username', __METHOD__ .
678 ": '$name' invalid due to blacklisted characters" );
679 return false;
682 return true;
686 * Usernames which fail to pass this function will be blocked
687 * from user login and new account registrations, but may be used
688 * internally by batch processes.
690 * If an account already exists in this form, login will be blocked
691 * by a failure to pass this function.
693 * @param string $name Name to match
694 * @return bool
696 public static function isUsableName( $name ) {
697 global $wgReservedUsernames;
698 // Must be a valid username, obviously ;)
699 if ( !self::isValidUserName( $name ) ) {
700 return false;
703 static $reservedUsernames = false;
704 if ( !$reservedUsernames ) {
705 $reservedUsernames = $wgReservedUsernames;
706 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
709 // Certain names may be reserved for batch processes.
710 foreach ( $reservedUsernames as $reserved ) {
711 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
712 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
714 if ( $reserved == $name ) {
715 return false;
718 return true;
722 * Usernames which fail to pass this function will be blocked
723 * from new account registrations, but may be used internally
724 * either by batch processes or by user accounts which have
725 * already been created.
727 * Additional blacklisting may be added here rather than in
728 * isValidUserName() to avoid disrupting existing accounts.
730 * @param string $name String to match
731 * @return bool
733 public static function isCreatableName( $name ) {
734 global $wgInvalidUsernameCharacters;
736 // Ensure that the username isn't longer than 235 bytes, so that
737 // (at least for the builtin skins) user javascript and css files
738 // will work. (bug 23080)
739 if ( strlen( $name ) > 235 ) {
740 wfDebugLog( 'username', __METHOD__ .
741 ": '$name' invalid due to length" );
742 return false;
745 // Preg yells if you try to give it an empty string
746 if ( $wgInvalidUsernameCharacters !== '' ) {
747 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
748 wfDebugLog( 'username', __METHOD__ .
749 ": '$name' invalid due to wgInvalidUsernameCharacters" );
750 return false;
754 return self::isUsableName( $name );
758 * Is the input a valid password for this user?
760 * @param string $password Desired password
761 * @return bool
763 public function isValidPassword( $password ) {
764 //simple boolean wrapper for getPasswordValidity
765 return $this->getPasswordValidity( $password ) === true;
770 * Given unvalidated password input, return error message on failure.
772 * @param string $password Desired password
773 * @return bool|string|array True on success, string or array of error message on failure
775 public function getPasswordValidity( $password ) {
776 $result = $this->checkPasswordValidity( $password );
777 if ( $result->isGood() ) {
778 return true;
779 } else {
780 $messages = array();
781 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
782 $messages[] = $error['message'];
784 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
785 $messages[] = $warning['message'];
787 if ( count( $messages ) === 1 ) {
788 return $messages[0];
790 return $messages;
795 * Check if this is a valid password for this user. Status will be good if
796 * the password is valid, or have an array of error messages if not.
798 * @param string $password Desired password
799 * @return Status
800 * @since 1.23
802 public function checkPasswordValidity( $password ) {
803 global $wgMinimalPasswordLength, $wgContLang;
805 static $blockedLogins = array(
806 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
807 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
810 $status = Status::newGood();
812 $result = false; //init $result to false for the internal checks
814 if ( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) ) {
815 $status->error( $result );
816 return $status;
819 if ( $result === false ) {
820 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
821 $status->error( 'passwordtooshort', $wgMinimalPasswordLength );
822 return $status;
823 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName ) ) {
824 $status->error( 'password-name-match' );
825 return $status;
826 } elseif ( isset( $blockedLogins[$this->getName()] )
827 && $password == $blockedLogins[$this->getName()]
829 $status->error( 'password-login-forbidden' );
830 return $status;
831 } else {
832 //it seems weird returning a Good status here, but this is because of the
833 //initialization of $result to false above. If the hook is never run or it
834 //doesn't modify $result, then we will likely get down into this if with
835 //a valid password.
836 return $status;
838 } elseif ( $result === true ) {
839 return $status;
840 } else {
841 $status->error( $result );
842 return $status; //the isValidPassword hook set a string $result and returned true
847 * Expire a user's password
848 * @since 1.23
849 * @param int $ts Optional timestamp to convert, default 0 for the current time
851 public function expirePassword( $ts = 0 ) {
852 $this->loadPasswords();
853 $timestamp = wfTimestamp( TS_MW, $ts );
854 $this->mPasswordExpires = $timestamp;
855 $this->saveSettings();
859 * Clear the password expiration for a user
860 * @since 1.23
861 * @param bool $load Ensure user object is loaded first
863 public function resetPasswordExpiration( $load = true ) {
864 global $wgPasswordExpirationDays;
865 if ( $load ) {
866 $this->load();
868 $newExpire = null;
869 if ( $wgPasswordExpirationDays ) {
870 $newExpire = wfTimestamp(
871 TS_MW,
872 time() + ( $wgPasswordExpirationDays * 24 * 3600 )
875 // Give extensions a chance to force an expiration
876 wfRunHooks( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
877 $this->mPasswordExpires = $newExpire;
881 * Check if the user's password is expired.
882 * TODO: Put this and password length into a PasswordPolicy object
883 * @since 1.23
884 * @return string|bool The expiration type, or false if not expired
885 * hard: A password change is required to login
886 * soft: Allow login, but encourage password change
887 * false: Password is not expired
889 public function getPasswordExpired() {
890 global $wgPasswordExpireGrace;
891 $expired = false;
892 $now = wfTimestamp();
893 $expiration = $this->getPasswordExpireDate();
894 $expUnix = wfTimestamp( TS_UNIX, $expiration );
895 if ( $expiration !== null && $expUnix < $now ) {
896 $expired = ( $expUnix + $wgPasswordExpireGrace < $now ) ? 'hard' : 'soft';
898 return $expired;
902 * Get this user's password expiration date. Since this may be using
903 * the cached User object, we assume that whatever mechanism is setting
904 * the expiration date is also expiring the User cache.
905 * @since 1.23
906 * @return string|bool The datestamp of the expiration, or null if not set
908 public function getPasswordExpireDate() {
909 $this->load();
910 return $this->mPasswordExpires;
914 * Given unvalidated user input, return a canonical username, or false if
915 * the username is invalid.
916 * @param string $name User input
917 * @param string|bool $validate Type of validation to use:
918 * - false No validation
919 * - 'valid' Valid for batch processes
920 * - 'usable' Valid for batch processes and login
921 * - 'creatable' Valid for batch processes, login and account creation
923 * @throws MWException
924 * @return bool|string
926 public static function getCanonicalName( $name, $validate = 'valid' ) {
927 // Force usernames to capital
928 global $wgContLang;
929 $name = $wgContLang->ucfirst( $name );
931 # Reject names containing '#'; these will be cleaned up
932 # with title normalisation, but then it's too late to
933 # check elsewhere
934 if ( strpos( $name, '#' ) !== false ) {
935 return false;
938 // Clean up name according to title rules,
939 // but only when validation is requested (bug 12654)
940 $t = ( $validate !== false ) ?
941 Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
942 // Check for invalid titles
943 if ( is_null( $t ) ) {
944 return false;
947 // Reject various classes of invalid names
948 global $wgAuth;
949 $name = $wgAuth->getCanonicalName( $t->getText() );
951 switch ( $validate ) {
952 case false:
953 break;
954 case 'valid':
955 if ( !User::isValidUserName( $name ) ) {
956 $name = false;
958 break;
959 case 'usable':
960 if ( !User::isUsableName( $name ) ) {
961 $name = false;
963 break;
964 case 'creatable':
965 if ( !User::isCreatableName( $name ) ) {
966 $name = false;
968 break;
969 default:
970 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__ );
972 return $name;
976 * Count the number of edits of a user
978 * @param int $uid User ID to check
979 * @return int The user's edit count
981 * @deprecated since 1.21 in favour of User::getEditCount
983 public static function edits( $uid ) {
984 wfDeprecated( __METHOD__, '1.21' );
985 $user = self::newFromId( $uid );
986 return $user->getEditCount();
990 * Return a random password.
992 * @return string New random password
994 public static function randomPassword() {
995 global $wgMinimalPasswordLength;
996 // Decide the final password length based on our min password length,
997 // stopping at a minimum of 10 chars.
998 $length = max( 10, $wgMinimalPasswordLength );
999 // Multiply by 1.25 to get the number of hex characters we need
1000 $length = $length * 1.25;
1001 // Generate random hex chars
1002 $hex = MWCryptRand::generateHex( $length );
1003 // Convert from base 16 to base 32 to get a proper password like string
1004 return wfBaseConvert( $hex, 16, 32 );
1008 * Set cached properties to default.
1010 * @note This no longer clears uncached lazy-initialised properties;
1011 * the constructor does that instead.
1013 * @param string|bool $name
1015 public function loadDefaults( $name = false ) {
1016 wfProfileIn( __METHOD__ );
1018 $passwordFactory = self::getPasswordFactory();
1020 $this->mId = 0;
1021 $this->mName = $name;
1022 $this->mRealName = '';
1023 $this->mPassword = $passwordFactory->newFromCiphertext( null );
1024 $this->mNewpassword = $passwordFactory->newFromCiphertext( null );
1025 $this->mNewpassTime = null;
1026 $this->mEmail = '';
1027 $this->mOptionOverrides = null;
1028 $this->mOptionsLoaded = false;
1030 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1031 if ( $loggedOut !== null ) {
1032 $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
1033 } else {
1034 $this->mTouched = '1'; # Allow any pages to be cached
1037 $this->mToken = null; // Don't run cryptographic functions till we need a token
1038 $this->mEmailAuthenticated = null;
1039 $this->mEmailToken = '';
1040 $this->mEmailTokenExpires = null;
1041 $this->mPasswordExpires = null;
1042 $this->resetPasswordExpiration( false );
1043 $this->mRegistration = wfTimestamp( TS_MW );
1044 $this->mGroups = array();
1046 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
1048 wfProfileOut( __METHOD__ );
1052 * Return whether an item has been loaded.
1054 * @param string $item Item to check. Current possibilities:
1055 * - id
1056 * - name
1057 * - realname
1058 * @param string $all 'all' to check if the whole object has been loaded
1059 * or any other string to check if only the item is available (e.g.
1060 * for optimisation)
1061 * @return bool
1063 public function isItemLoaded( $item, $all = 'all' ) {
1064 return ( $this->mLoadedItems === true && $all === 'all' ) ||
1065 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
1069 * Set that an item has been loaded
1071 * @param string $item
1073 protected function setItemLoaded( $item ) {
1074 if ( is_array( $this->mLoadedItems ) ) {
1075 $this->mLoadedItems[$item] = true;
1080 * Load user data from the session or login cookie.
1081 * @return bool True if the user is logged in, false otherwise.
1083 private function loadFromSession() {
1084 $result = null;
1085 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
1086 if ( $result !== null ) {
1087 return $result;
1090 $request = $this->getRequest();
1092 $cookieId = $request->getCookie( 'UserID' );
1093 $sessId = $request->getSessionData( 'wsUserID' );
1095 if ( $cookieId !== null ) {
1096 $sId = intval( $cookieId );
1097 if ( $sessId !== null && $cookieId != $sessId ) {
1098 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1099 cookie user ID ($sId) don't match!" );
1100 return false;
1102 $request->setSessionData( 'wsUserID', $sId );
1103 } elseif ( $sessId !== null && $sessId != 0 ) {
1104 $sId = $sessId;
1105 } else {
1106 return false;
1109 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1110 $sName = $request->getSessionData( 'wsUserName' );
1111 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1112 $sName = $request->getCookie( 'UserName' );
1113 $request->setSessionData( 'wsUserName', $sName );
1114 } else {
1115 return false;
1118 $proposedUser = User::newFromId( $sId );
1119 if ( !$proposedUser->isLoggedIn() ) {
1120 // Not a valid ID
1121 return false;
1124 global $wgBlockDisablesLogin;
1125 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1126 // User blocked and we've disabled blocked user logins
1127 return false;
1130 if ( $request->getSessionData( 'wsToken' ) ) {
1131 $passwordCorrect =
1132 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1133 $from = 'session';
1134 } elseif ( $request->getCookie( 'Token' ) ) {
1135 # Get the token from DB/cache and clean it up to remove garbage padding.
1136 # This deals with historical problems with bugs and the default column value.
1137 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1138 // Make comparison in constant time (bug 61346)
1139 $passwordCorrect = strlen( $token )
1140 && hash_equals( $token, $request->getCookie( 'Token' ) );
1141 $from = 'cookie';
1142 } else {
1143 // No session or persistent login cookie
1144 return false;
1147 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1148 $this->loadFromUserObject( $proposedUser );
1149 $request->setSessionData( 'wsToken', $this->mToken );
1150 wfDebug( "User: logged in from $from\n" );
1151 return true;
1152 } else {
1153 // Invalid credentials
1154 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1155 return false;
1160 * Load user and user_group data from the database.
1161 * $this->mId must be set, this is how the user is identified.
1163 * @param int $flags Supports User::READ_LOCKING
1164 * @return bool True if the user exists, false if the user is anonymous
1166 public function loadFromDatabase( $flags = 0 ) {
1167 // Paranoia
1168 $this->mId = intval( $this->mId );
1170 // Anonymous user
1171 if ( !$this->mId ) {
1172 $this->loadDefaults();
1173 return false;
1176 $dbr = wfGetDB( DB_MASTER );
1177 $s = $dbr->selectRow(
1178 'user',
1179 self::selectFields(),
1180 array( 'user_id' => $this->mId ),
1181 __METHOD__,
1182 ( $flags & self::READ_LOCKING == self::READ_LOCKING )
1183 ? array( 'LOCK IN SHARE MODE' )
1184 : array()
1187 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1189 if ( $s !== false ) {
1190 // Initialise user table data
1191 $this->loadFromRow( $s );
1192 $this->mGroups = null; // deferred
1193 $this->getEditCount(); // revalidation for nulls
1194 return true;
1195 } else {
1196 // Invalid user_id
1197 $this->mId = 0;
1198 $this->loadDefaults();
1199 return false;
1204 * Initialize this object from a row from the user table.
1206 * @param stdClass $row Row from the user table to load.
1207 * @param array $data Further user data to load into the object
1209 * user_groups Array with groups out of the user_groups table
1210 * user_properties Array with properties out of the user_properties table
1212 public function loadFromRow( $row, $data = null ) {
1213 $all = true;
1214 $passwordFactory = self::getPasswordFactory();
1216 $this->mGroups = null; // deferred
1218 if ( isset( $row->user_name ) ) {
1219 $this->mName = $row->user_name;
1220 $this->mFrom = 'name';
1221 $this->setItemLoaded( 'name' );
1222 } else {
1223 $all = false;
1226 if ( isset( $row->user_real_name ) ) {
1227 $this->mRealName = $row->user_real_name;
1228 $this->setItemLoaded( 'realname' );
1229 } else {
1230 $all = false;
1233 if ( isset( $row->user_id ) ) {
1234 $this->mId = intval( $row->user_id );
1235 $this->mFrom = 'id';
1236 $this->setItemLoaded( 'id' );
1237 } else {
1238 $all = false;
1241 if ( isset( $row->user_editcount ) ) {
1242 $this->mEditCount = $row->user_editcount;
1243 } else {
1244 $all = false;
1247 if ( isset( $row->user_password ) ) {
1248 // Check for *really* old password hashes that don't even have a type
1249 // The old hash format was just an md5 hex hash, with no type information
1250 if ( preg_match( '/^[0-9a-f]{32}$/', $row->user_password ) ) {
1251 $row->user_password = ":A:{$this->mId}:{$row->user_password}";
1254 try {
1255 $this->mPassword = $passwordFactory->newFromCiphertext( $row->user_password );
1256 } catch ( PasswordError $e ) {
1257 wfDebug( 'Invalid password hash found in database.' );
1258 $this->mPassword = $passwordFactory->newFromCiphertext( null );
1261 try {
1262 $this->mNewpassword = $passwordFactory->newFromCiphertext( $row->user_newpassword );
1263 } catch ( PasswordError $e ) {
1264 wfDebug( 'Invalid password hash found in database.' );
1265 $this->mNewpassword = $passwordFactory->newFromCiphertext( null );
1268 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
1269 $this->mPasswordExpires = wfTimestampOrNull( TS_MW, $row->user_password_expires );
1272 if ( isset( $row->user_email ) ) {
1273 $this->mEmail = $row->user_email;
1274 $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1275 $this->mToken = $row->user_token;
1276 if ( $this->mToken == '' ) {
1277 $this->mToken = null;
1279 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1280 $this->mEmailToken = $row->user_email_token;
1281 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1282 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1283 } else {
1284 $all = false;
1287 if ( $all ) {
1288 $this->mLoadedItems = true;
1291 if ( is_array( $data ) ) {
1292 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1293 $this->mGroups = $data['user_groups'];
1295 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1296 $this->loadOptions( $data['user_properties'] );
1302 * Load the data for this user object from another user object.
1304 * @param User $user
1306 protected function loadFromUserObject( $user ) {
1307 $user->load();
1308 $user->loadGroups();
1309 $user->loadOptions();
1310 foreach ( self::$mCacheVars as $var ) {
1311 $this->$var = $user->$var;
1316 * Load the groups from the database if they aren't already loaded.
1318 private function loadGroups() {
1319 if ( is_null( $this->mGroups ) ) {
1320 $dbr = wfGetDB( DB_MASTER );
1321 $res = $dbr->select( 'user_groups',
1322 array( 'ug_group' ),
1323 array( 'ug_user' => $this->mId ),
1324 __METHOD__ );
1325 $this->mGroups = array();
1326 foreach ( $res as $row ) {
1327 $this->mGroups[] = $row->ug_group;
1333 * Load the user's password hashes from the database
1335 * This is usually called in a scenario where the actual User object was
1336 * loaded from the cache, and then password comparison needs to be performed.
1337 * Password hashes are not stored in memcached.
1339 * @since 1.24
1341 private function loadPasswords() {
1342 if ( $this->getId() !== 0 && ( $this->mPassword === null || $this->mNewpassword === null ) ) {
1343 $this->loadFromRow( wfGetDB( DB_MASTER )->selectRow(
1344 'user',
1345 array( 'user_password', 'user_newpassword', 'user_newpass_time', 'user_password_expires' ),
1346 array( 'user_id' => $this->getId() ),
1347 __METHOD__
1348 ) );
1353 * Add the user to the group if he/she meets given criteria.
1355 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1356 * possible to remove manually via Special:UserRights. In such case it
1357 * will not be re-added automatically. The user will also not lose the
1358 * group if they no longer meet the criteria.
1360 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1362 * @return array Array of groups the user has been promoted to.
1364 * @see $wgAutopromoteOnce
1366 public function addAutopromoteOnceGroups( $event ) {
1367 global $wgAutopromoteOnceLogInRC, $wgAuth;
1369 $toPromote = array();
1370 if ( $this->getId() ) {
1371 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1372 if ( count( $toPromote ) ) {
1373 $oldGroups = $this->getGroups(); // previous groups
1375 foreach ( $toPromote as $group ) {
1376 $this->addGroup( $group );
1378 // update groups in external authentication database
1379 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1381 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1383 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1384 $logEntry->setPerformer( $this );
1385 $logEntry->setTarget( $this->getUserPage() );
1386 $logEntry->setParameters( array(
1387 '4::oldgroups' => $oldGroups,
1388 '5::newgroups' => $newGroups,
1389 ) );
1390 $logid = $logEntry->insert();
1391 if ( $wgAutopromoteOnceLogInRC ) {
1392 $logEntry->publish( $logid );
1396 return $toPromote;
1400 * Clear various cached data stored in this object. The cache of the user table
1401 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1403 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1404 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1406 public function clearInstanceCache( $reloadFrom = false ) {
1407 $this->mNewtalk = -1;
1408 $this->mDatePreference = null;
1409 $this->mBlockedby = -1; # Unset
1410 $this->mHash = false;
1411 $this->mRights = null;
1412 $this->mEffectiveGroups = null;
1413 $this->mImplicitGroups = null;
1414 $this->mGroups = null;
1415 $this->mOptions = null;
1416 $this->mOptionsLoaded = false;
1417 $this->mEditCount = null;
1419 if ( $reloadFrom ) {
1420 $this->mLoadedItems = array();
1421 $this->mFrom = $reloadFrom;
1426 * Combine the language default options with any site-specific options
1427 * and add the default language variants.
1429 * @return array Array of String options
1431 public static function getDefaultOptions() {
1432 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1434 static $defOpt = null;
1435 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1436 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1437 // mid-request and see that change reflected in the return value of this function.
1438 // Which is insane and would never happen during normal MW operation
1439 return $defOpt;
1442 $defOpt = $wgDefaultUserOptions;
1443 // Default language setting
1444 $defOpt['language'] = $wgContLang->getCode();
1445 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
1446 $defOpt[$langCode == $wgContLang->getCode() ? 'variant' : "variant-$langCode"] = $langCode;
1448 foreach ( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1449 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1451 $defOpt['skin'] = Skin::normalizeKey( $wgDefaultSkin );
1453 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1455 return $defOpt;
1459 * Get a given default option value.
1461 * @param string $opt Name of option to retrieve
1462 * @return string Default option value
1464 public static function getDefaultOption( $opt ) {
1465 $defOpts = self::getDefaultOptions();
1466 if ( isset( $defOpts[$opt] ) ) {
1467 return $defOpts[$opt];
1468 } else {
1469 return null;
1474 * Get blocking information
1475 * @param bool $bFromSlave Whether to check the slave database first.
1476 * To improve performance, non-critical checks are done against slaves.
1477 * Check when actually saving should be done against master.
1479 private function getBlockedStatus( $bFromSlave = true ) {
1480 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1482 if ( -1 != $this->mBlockedby ) {
1483 return;
1486 wfProfileIn( __METHOD__ );
1487 wfDebug( __METHOD__ . ": checking...\n" );
1489 // Initialize data...
1490 // Otherwise something ends up stomping on $this->mBlockedby when
1491 // things get lazy-loaded later, causing false positive block hits
1492 // due to -1 !== 0. Probably session-related... Nothing should be
1493 // overwriting mBlockedby, surely?
1494 $this->load();
1496 # We only need to worry about passing the IP address to the Block generator if the
1497 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1498 # know which IP address they're actually coming from
1499 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1500 $ip = $this->getRequest()->getIP();
1501 } else {
1502 $ip = null;
1505 // User/IP blocking
1506 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1508 // Proxy blocking
1509 if ( !$block instanceof Block && $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1510 && !in_array( $ip, $wgProxyWhitelist )
1512 // Local list
1513 if ( self::isLocallyBlockedProxy( $ip ) ) {
1514 $block = new Block;
1515 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1516 $block->mReason = wfMessage( 'proxyblockreason' )->text();
1517 $block->setTarget( $ip );
1518 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1519 $block = new Block;
1520 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1521 $block->mReason = wfMessage( 'sorbsreason' )->text();
1522 $block->setTarget( $ip );
1526 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1527 if ( !$block instanceof Block
1528 && $wgApplyIpBlocksToXff
1529 && $ip !== null
1530 && !$this->isAllowed( 'proxyunbannable' )
1531 && !in_array( $ip, $wgProxyWhitelist )
1533 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1534 $xff = array_map( 'trim', explode( ',', $xff ) );
1535 $xff = array_diff( $xff, array( $ip ) );
1536 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1537 $block = Block::chooseBlock( $xffblocks, $xff );
1538 if ( $block instanceof Block ) {
1539 # Mangle the reason to alert the user that the block
1540 # originated from matching the X-Forwarded-For header.
1541 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->text();
1545 if ( $block instanceof Block ) {
1546 wfDebug( __METHOD__ . ": Found block.\n" );
1547 $this->mBlock = $block;
1548 $this->mBlockedby = $block->getByName();
1549 $this->mBlockreason = $block->mReason;
1550 $this->mHideName = $block->mHideName;
1551 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1552 } else {
1553 $this->mBlockedby = '';
1554 $this->mHideName = 0;
1555 $this->mAllowUsertalk = false;
1558 // Extensions
1559 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1561 wfProfileOut( __METHOD__ );
1565 * Whether the given IP is in a DNS blacklist.
1567 * @param string $ip IP to check
1568 * @param bool $checkWhitelist Whether to check the whitelist first
1569 * @return bool True if blacklisted.
1571 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1572 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1574 if ( !$wgEnableDnsBlacklist ) {
1575 return false;
1578 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1579 return false;
1582 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1586 * Whether the given IP is in a given DNS blacklist.
1588 * @param string $ip IP to check
1589 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1590 * @return bool True if blacklisted.
1592 public function inDnsBlacklist( $ip, $bases ) {
1593 wfProfileIn( __METHOD__ );
1595 $found = false;
1596 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1597 if ( IP::isIPv4( $ip ) ) {
1598 // Reverse IP, bug 21255
1599 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1601 foreach ( (array)$bases as $base ) {
1602 // Make hostname
1603 // If we have an access key, use that too (ProjectHoneypot, etc.)
1604 if ( is_array( $base ) ) {
1605 if ( count( $base ) >= 2 ) {
1606 // Access key is 1, base URL is 0
1607 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1608 } else {
1609 $host = "$ipReversed.{$base[0]}";
1611 } else {
1612 $host = "$ipReversed.$base";
1615 // Send query
1616 $ipList = gethostbynamel( $host );
1618 if ( $ipList ) {
1619 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1620 $found = true;
1621 break;
1622 } else {
1623 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1628 wfProfileOut( __METHOD__ );
1629 return $found;
1633 * Check if an IP address is in the local proxy list
1635 * @param string $ip
1637 * @return bool
1639 public static function isLocallyBlockedProxy( $ip ) {
1640 global $wgProxyList;
1642 if ( !$wgProxyList ) {
1643 return false;
1645 wfProfileIn( __METHOD__ );
1647 if ( !is_array( $wgProxyList ) ) {
1648 // Load from the specified file
1649 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1652 if ( !is_array( $wgProxyList ) ) {
1653 $ret = false;
1654 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1655 $ret = true;
1656 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1657 // Old-style flipped proxy list
1658 $ret = true;
1659 } else {
1660 $ret = false;
1662 wfProfileOut( __METHOD__ );
1663 return $ret;
1667 * Is this user subject to rate limiting?
1669 * @return bool True if rate limited
1671 public function isPingLimitable() {
1672 global $wgRateLimitsExcludedIPs;
1673 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1674 // No other good way currently to disable rate limits
1675 // for specific IPs. :P
1676 // But this is a crappy hack and should die.
1677 return false;
1679 return !$this->isAllowed( 'noratelimit' );
1683 * Primitive rate limits: enforce maximum actions per time period
1684 * to put a brake on flooding.
1686 * The method generates both a generic profiling point and a per action one
1687 * (suffix being "-$action".
1689 * @note When using a shared cache like memcached, IP-address
1690 * last-hit counters will be shared across wikis.
1692 * @param string $action Action to enforce; 'edit' if unspecified
1693 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1694 * @return bool True if a rate limiter was tripped
1696 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1697 // Call the 'PingLimiter' hook
1698 $result = false;
1699 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1700 return $result;
1703 global $wgRateLimits;
1704 if ( !isset( $wgRateLimits[$action] ) ) {
1705 return false;
1708 // Some groups shouldn't trigger the ping limiter, ever
1709 if ( !$this->isPingLimitable() ) {
1710 return false;
1713 global $wgMemc;
1714 wfProfileIn( __METHOD__ );
1715 wfProfileIn( __METHOD__ . '-' . $action );
1717 $limits = $wgRateLimits[$action];
1718 $keys = array();
1719 $id = $this->getId();
1720 $userLimit = false;
1722 if ( isset( $limits['anon'] ) && $id == 0 ) {
1723 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1726 if ( isset( $limits['user'] ) && $id != 0 ) {
1727 $userLimit = $limits['user'];
1729 if ( $this->isNewbie() ) {
1730 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1731 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1733 if ( isset( $limits['ip'] ) ) {
1734 $ip = $this->getRequest()->getIP();
1735 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1737 if ( isset( $limits['subnet'] ) ) {
1738 $ip = $this->getRequest()->getIP();
1739 $matches = array();
1740 $subnet = false;
1741 if ( IP::isIPv6( $ip ) ) {
1742 $parts = IP::parseRange( "$ip/64" );
1743 $subnet = $parts[0];
1744 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1745 // IPv4
1746 $subnet = $matches[1];
1748 if ( $subnet !== false ) {
1749 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1753 // Check for group-specific permissions
1754 // If more than one group applies, use the group with the highest limit
1755 foreach ( $this->getGroups() as $group ) {
1756 if ( isset( $limits[$group] ) ) {
1757 if ( $userLimit === false
1758 || $limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1760 $userLimit = $limits[$group];
1764 // Set the user limit key
1765 if ( $userLimit !== false ) {
1766 list( $max, $period ) = $userLimit;
1767 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
1768 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1771 $triggered = false;
1772 foreach ( $keys as $key => $limit ) {
1773 list( $max, $period ) = $limit;
1774 $summary = "(limit $max in {$period}s)";
1775 $count = $wgMemc->get( $key );
1776 // Already pinged?
1777 if ( $count ) {
1778 if ( $count >= $max ) {
1779 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1780 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1781 $triggered = true;
1782 } else {
1783 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1785 } else {
1786 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1787 if ( $incrBy > 0 ) {
1788 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1791 if ( $incrBy > 0 ) {
1792 $wgMemc->incr( $key, $incrBy );
1796 wfProfileOut( __METHOD__ . '-' . $action );
1797 wfProfileOut( __METHOD__ );
1798 return $triggered;
1802 * Check if user is blocked
1804 * @param bool $bFromSlave Whether to check the slave database instead of
1805 * the master. Hacked from false due to horrible probs on site.
1806 * @return bool True if blocked, false otherwise
1808 public function isBlocked( $bFromSlave = true ) {
1809 return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
1813 * Get the block affecting the user, or null if the user is not blocked
1815 * @param bool $bFromSlave Whether to check the slave database instead of the master
1816 * @return Block|null
1818 public function getBlock( $bFromSlave = true ) {
1819 $this->getBlockedStatus( $bFromSlave );
1820 return $this->mBlock instanceof Block ? $this->mBlock : null;
1824 * Check if user is blocked from editing a particular article
1826 * @param Title $title Title to check
1827 * @param bool $bFromSlave Whether to check the slave database instead of the master
1828 * @return bool
1830 public function isBlockedFrom( $title, $bFromSlave = false ) {
1831 global $wgBlockAllowsUTEdit;
1832 wfProfileIn( __METHOD__ );
1834 $blocked = $this->isBlocked( $bFromSlave );
1835 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1836 // If a user's name is suppressed, they cannot make edits anywhere
1837 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName()
1838 && $title->getNamespace() == NS_USER_TALK ) {
1839 $blocked = false;
1840 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1843 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1845 wfProfileOut( __METHOD__ );
1846 return $blocked;
1850 * If user is blocked, return the name of the user who placed the block
1851 * @return string Name of blocker
1853 public function blockedBy() {
1854 $this->getBlockedStatus();
1855 return $this->mBlockedby;
1859 * If user is blocked, return the specified reason for the block
1860 * @return string Blocking reason
1862 public function blockedFor() {
1863 $this->getBlockedStatus();
1864 return $this->mBlockreason;
1868 * If user is blocked, return the ID for the block
1869 * @return int Block ID
1871 public function getBlockId() {
1872 $this->getBlockedStatus();
1873 return ( $this->mBlock ? $this->mBlock->getId() : false );
1877 * Check if user is blocked on all wikis.
1878 * Do not use for actual edit permission checks!
1879 * This is intended for quick UI checks.
1881 * @param string $ip IP address, uses current client if none given
1882 * @return bool True if blocked, false otherwise
1884 public function isBlockedGlobally( $ip = '' ) {
1885 if ( $this->mBlockedGlobally !== null ) {
1886 return $this->mBlockedGlobally;
1888 // User is already an IP?
1889 if ( IP::isIPAddress( $this->getName() ) ) {
1890 $ip = $this->getName();
1891 } elseif ( !$ip ) {
1892 $ip = $this->getRequest()->getIP();
1894 $blocked = false;
1895 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1896 $this->mBlockedGlobally = (bool)$blocked;
1897 return $this->mBlockedGlobally;
1901 * Check if user account is locked
1903 * @return bool True if locked, false otherwise
1905 public function isLocked() {
1906 if ( $this->mLocked !== null ) {
1907 return $this->mLocked;
1909 global $wgAuth;
1910 $authUser = $wgAuth->getUserInstance( $this );
1911 $this->mLocked = (bool)$authUser->isLocked();
1912 return $this->mLocked;
1916 * Check if user account is hidden
1918 * @return bool True if hidden, false otherwise
1920 public function isHidden() {
1921 if ( $this->mHideName !== null ) {
1922 return $this->mHideName;
1924 $this->getBlockedStatus();
1925 if ( !$this->mHideName ) {
1926 global $wgAuth;
1927 $authUser = $wgAuth->getUserInstance( $this );
1928 $this->mHideName = (bool)$authUser->isHidden();
1930 return $this->mHideName;
1934 * Get the user's ID.
1935 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1937 public function getId() {
1938 if ( $this->mId === null && $this->mName !== null && User::isIP( $this->mName ) ) {
1939 // Special case, we know the user is anonymous
1940 return 0;
1941 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1942 // Don't load if this was initialized from an ID
1943 $this->load();
1945 return $this->mId;
1949 * Set the user and reload all fields according to a given ID
1950 * @param int $v User ID to reload
1952 public function setId( $v ) {
1953 $this->mId = $v;
1954 $this->clearInstanceCache( 'id' );
1958 * Get the user name, or the IP of an anonymous user
1959 * @return string User's name or IP address
1961 public function getName() {
1962 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1963 // Special case optimisation
1964 return $this->mName;
1965 } else {
1966 $this->load();
1967 if ( $this->mName === false ) {
1968 // Clean up IPs
1969 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
1971 return $this->mName;
1976 * Set the user name.
1978 * This does not reload fields from the database according to the given
1979 * name. Rather, it is used to create a temporary "nonexistent user" for
1980 * later addition to the database. It can also be used to set the IP
1981 * address for an anonymous user to something other than the current
1982 * remote IP.
1984 * @note User::newFromName() has roughly the same function, when the named user
1985 * does not exist.
1986 * @param string $str New user name to set
1988 public function setName( $str ) {
1989 $this->load();
1990 $this->mName = $str;
1994 * Get the user's name escaped by underscores.
1995 * @return string Username escaped by underscores.
1997 public function getTitleKey() {
1998 return str_replace( ' ', '_', $this->getName() );
2002 * Check if the user has new messages.
2003 * @return bool True if the user has new messages
2005 public function getNewtalk() {
2006 $this->load();
2008 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2009 if ( $this->mNewtalk === -1 ) {
2010 $this->mNewtalk = false; # reset talk page status
2012 // Check memcached separately for anons, who have no
2013 // entire User object stored in there.
2014 if ( !$this->mId ) {
2015 global $wgDisableAnonTalk;
2016 if ( $wgDisableAnonTalk ) {
2017 // Anon newtalk disabled by configuration.
2018 $this->mNewtalk = false;
2019 } else {
2020 global $wgMemc;
2021 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
2022 $newtalk = $wgMemc->get( $key );
2023 if ( strval( $newtalk ) !== '' ) {
2024 $this->mNewtalk = (bool)$newtalk;
2025 } else {
2026 // Since we are caching this, make sure it is up to date by getting it
2027 // from the master
2028 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
2029 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
2032 } else {
2033 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
2037 return (bool)$this->mNewtalk;
2041 * Return the data needed to construct links for new talk page message
2042 * alerts. If there are new messages, this will return an associative array
2043 * with the following data:
2044 * wiki: The database name of the wiki
2045 * link: Root-relative link to the user's talk page
2046 * rev: The last talk page revision that the user has seen or null. This
2047 * is useful for building diff links.
2048 * If there are no new messages, it returns an empty array.
2049 * @note This function was designed to accomodate multiple talk pages, but
2050 * currently only returns a single link and revision.
2051 * @return array
2053 public function getNewMessageLinks() {
2054 $talks = array();
2055 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2056 return $talks;
2057 } elseif ( !$this->getNewtalk() ) {
2058 return array();
2060 $utp = $this->getTalkPage();
2061 $dbr = wfGetDB( DB_SLAVE );
2062 // Get the "last viewed rev" timestamp from the oldest message notification
2063 $timestamp = $dbr->selectField( 'user_newtalk',
2064 'MIN(user_last_timestamp)',
2065 $this->isAnon() ? array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2066 __METHOD__ );
2067 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2068 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2072 * Get the revision ID for the last talk page revision viewed by the talk
2073 * page owner.
2074 * @return int|null Revision ID or null
2076 public function getNewMessageRevisionId() {
2077 $newMessageRevisionId = null;
2078 $newMessageLinks = $this->getNewMessageLinks();
2079 if ( $newMessageLinks ) {
2080 // Note: getNewMessageLinks() never returns more than a single link
2081 // and it is always for the same wiki, but we double-check here in
2082 // case that changes some time in the future.
2083 if ( count( $newMessageLinks ) === 1
2084 && $newMessageLinks[0]['wiki'] === wfWikiID()
2085 && $newMessageLinks[0]['rev']
2087 $newMessageRevision = $newMessageLinks[0]['rev'];
2088 $newMessageRevisionId = $newMessageRevision->getId();
2091 return $newMessageRevisionId;
2095 * Internal uncached check for new messages
2097 * @see getNewtalk()
2098 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2099 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2100 * @param bool $fromMaster True to fetch from the master, false for a slave
2101 * @return bool True if the user has new messages
2103 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
2104 if ( $fromMaster ) {
2105 $db = wfGetDB( DB_MASTER );
2106 } else {
2107 $db = wfGetDB( DB_SLAVE );
2109 $ok = $db->selectField( 'user_newtalk', $field,
2110 array( $field => $id ), __METHOD__ );
2111 return $ok !== false;
2115 * Add or update the new messages flag
2116 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2117 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2118 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2119 * @return bool True if successful, false otherwise
2121 protected function updateNewtalk( $field, $id, $curRev = null ) {
2122 // Get timestamp of the talk page revision prior to the current one
2123 $prevRev = $curRev ? $curRev->getPrevious() : false;
2124 $ts = $prevRev ? $prevRev->getTimestamp() : null;
2125 // Mark the user as having new messages since this revision
2126 $dbw = wfGetDB( DB_MASTER );
2127 $dbw->insert( 'user_newtalk',
2128 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2129 __METHOD__,
2130 'IGNORE' );
2131 if ( $dbw->affectedRows() ) {
2132 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
2133 return true;
2134 } else {
2135 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
2136 return false;
2141 * Clear the new messages flag for the given user
2142 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2143 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2144 * @return bool True if successful, false otherwise
2146 protected function deleteNewtalk( $field, $id ) {
2147 $dbw = wfGetDB( DB_MASTER );
2148 $dbw->delete( 'user_newtalk',
2149 array( $field => $id ),
2150 __METHOD__ );
2151 if ( $dbw->affectedRows() ) {
2152 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
2153 return true;
2154 } else {
2155 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
2156 return false;
2161 * Update the 'You have new messages!' status.
2162 * @param bool $val Whether the user has new messages
2163 * @param Revision $curRev New, as yet unseen revision of the user talk
2164 * page. Ignored if null or !$val.
2166 public function setNewtalk( $val, $curRev = null ) {
2167 if ( wfReadOnly() ) {
2168 return;
2171 $this->load();
2172 $this->mNewtalk = $val;
2174 if ( $this->isAnon() ) {
2175 $field = 'user_ip';
2176 $id = $this->getName();
2177 } else {
2178 $field = 'user_id';
2179 $id = $this->getId();
2181 global $wgMemc;
2183 if ( $val ) {
2184 $changed = $this->updateNewtalk( $field, $id, $curRev );
2185 } else {
2186 $changed = $this->deleteNewtalk( $field, $id );
2189 if ( $this->isAnon() ) {
2190 // Anons have a separate memcached space, since
2191 // user records aren't kept for them.
2192 $key = wfMemcKey( 'newtalk', 'ip', $id );
2193 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
2195 if ( $changed ) {
2196 $this->invalidateCache();
2201 * Generate a current or new-future timestamp to be stored in the
2202 * user_touched field when we update things.
2203 * @return string Timestamp in TS_MW format
2205 private static function newTouchedTimestamp() {
2206 global $wgClockSkewFudge;
2207 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
2211 * Clear user data from memcached.
2212 * Use after applying fun updates to the database; caller's
2213 * responsibility to update user_touched if appropriate.
2215 * Called implicitly from invalidateCache() and saveSettings().
2217 public function clearSharedCache() {
2218 $this->load();
2219 if ( $this->mId ) {
2220 global $wgMemc;
2221 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
2226 * Immediately touch the user data cache for this account.
2227 * Updates user_touched field, and removes account data from memcached
2228 * for reload on the next hit.
2230 public function invalidateCache() {
2231 if ( wfReadOnly() ) {
2232 return;
2234 $this->load();
2235 if ( $this->mId ) {
2236 $this->mTouched = self::newTouchedTimestamp();
2238 $dbw = wfGetDB( DB_MASTER );
2239 $userid = $this->mId;
2240 $touched = $this->mTouched;
2241 $method = __METHOD__;
2242 $dbw->onTransactionIdle( function () use ( $dbw, $userid, $touched, $method ) {
2243 // Prevent contention slams by checking user_touched first
2244 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2245 $needsPurge = $dbw->selectField( 'user', '1',
2246 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2247 if ( $needsPurge ) {
2248 $dbw->update( 'user',
2249 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2250 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2251 $method
2254 } );
2255 $this->clearSharedCache();
2260 * Validate the cache for this account.
2261 * @param string $timestamp A timestamp in TS_MW format
2262 * @return bool
2264 public function validateCache( $timestamp ) {
2265 $this->load();
2266 return ( $timestamp >= $this->mTouched );
2270 * Get the user touched timestamp
2271 * @return string Timestamp
2273 public function getTouched() {
2274 $this->load();
2275 return $this->mTouched;
2279 * @return Password
2280 * @since 1.24
2282 public function getPassword() {
2283 $this->loadPasswords();
2285 return $this->mPassword;
2289 * @return Password
2290 * @since 1.24
2292 public function getTemporaryPassword() {
2293 $this->loadPasswords();
2295 return $this->mNewpassword;
2299 * Set the password and reset the random token.
2300 * Calls through to authentication plugin if necessary;
2301 * will have no effect if the auth plugin refuses to
2302 * pass the change through or if the legal password
2303 * checks fail.
2305 * As a special case, setting the password to null
2306 * wipes it, so the account cannot be logged in until
2307 * a new password is set, for instance via e-mail.
2309 * @param string $str New password to set
2310 * @throws PasswordError On failure
2312 * @return bool
2314 public function setPassword( $str ) {
2315 global $wgAuth;
2317 $this->loadPasswords();
2319 if ( $str !== null ) {
2320 if ( !$wgAuth->allowPasswordChange() ) {
2321 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2324 if ( !$this->isValidPassword( $str ) ) {
2325 global $wgMinimalPasswordLength;
2326 $valid = $this->getPasswordValidity( $str );
2327 if ( is_array( $valid ) ) {
2328 $message = array_shift( $valid );
2329 $params = $valid;
2330 } else {
2331 $message = $valid;
2332 $params = array( $wgMinimalPasswordLength );
2334 throw new PasswordError( wfMessage( $message, $params )->text() );
2338 if ( !$wgAuth->setPassword( $this, $str ) ) {
2339 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2342 $this->setInternalPassword( $str );
2344 return true;
2348 * Set the password and reset the random token unconditionally.
2350 * @param string|null $str New password to set or null to set an invalid
2351 * password hash meaning that the user will not be able to log in
2352 * through the web interface.
2354 public function setInternalPassword( $str ) {
2355 $this->setToken();
2357 $passwordFactory = self::getPasswordFactory();
2358 $this->mPassword = $passwordFactory->newFromPlaintext( $str );
2360 $this->mNewpassword = $passwordFactory->newFromCiphertext( null );
2361 $this->mNewpassTime = null;
2365 * Get the user's current token.
2366 * @param bool $forceCreation Force the generation of a new token if the
2367 * user doesn't have one (default=true for backwards compatibility).
2368 * @return string Token
2370 public function getToken( $forceCreation = true ) {
2371 $this->load();
2372 if ( !$this->mToken && $forceCreation ) {
2373 $this->setToken();
2375 return $this->mToken;
2379 * Set the random token (used for persistent authentication)
2380 * Called from loadDefaults() among other places.
2382 * @param string|bool $token If specified, set the token to this value
2384 public function setToken( $token = false ) {
2385 $this->load();
2386 if ( !$token ) {
2387 $this->mToken = MWCryptRand::generateHex( self::TOKEN_LENGTH );
2388 } else {
2389 $this->mToken = $token;
2394 * Set the password for a password reminder or new account email
2396 * @param string $str New password to set or null to set an invalid
2397 * password hash meaning that the user will not be able to use it
2398 * @param bool $throttle If true, reset the throttle timestamp to the present
2400 public function setNewpassword( $str, $throttle = true ) {
2401 $this->loadPasswords();
2403 $this->mNewpassword = self::getPasswordFactory()->newFromPlaintext( $str );
2404 if ( $str === null ) {
2405 $this->mNewpassTime = null;
2406 } elseif ( $throttle ) {
2407 $this->mNewpassTime = wfTimestampNow();
2412 * Has password reminder email been sent within the last
2413 * $wgPasswordReminderResendTime hours?
2414 * @return bool
2416 public function isPasswordReminderThrottled() {
2417 global $wgPasswordReminderResendTime;
2418 $this->load();
2419 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
2420 return false;
2422 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
2423 return time() < $expiry;
2427 * Get the user's e-mail address
2428 * @return string User's email address
2430 public function getEmail() {
2431 $this->load();
2432 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
2433 return $this->mEmail;
2437 * Get the timestamp of the user's e-mail authentication
2438 * @return string TS_MW timestamp
2440 public function getEmailAuthenticationTimestamp() {
2441 $this->load();
2442 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2443 return $this->mEmailAuthenticated;
2447 * Set the user's e-mail address
2448 * @param string $str New e-mail address
2450 public function setEmail( $str ) {
2451 $this->load();
2452 if ( $str == $this->mEmail ) {
2453 return;
2455 $this->invalidateEmail();
2456 $this->mEmail = $str;
2457 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
2461 * Set the user's e-mail address and a confirmation mail if needed.
2463 * @since 1.20
2464 * @param string $str New e-mail address
2465 * @return Status
2467 public function setEmailWithConfirmation( $str ) {
2468 global $wgEnableEmail, $wgEmailAuthentication;
2470 if ( !$wgEnableEmail ) {
2471 return Status::newFatal( 'emaildisabled' );
2474 $oldaddr = $this->getEmail();
2475 if ( $str === $oldaddr ) {
2476 return Status::newGood( true );
2479 $this->setEmail( $str );
2481 if ( $str !== '' && $wgEmailAuthentication ) {
2482 // Send a confirmation request to the new address if needed
2483 $type = $oldaddr != '' ? 'changed' : 'set';
2484 $result = $this->sendConfirmationMail( $type );
2485 if ( $result->isGood() ) {
2486 // Say the the caller that a confirmation mail has been sent
2487 $result->value = 'eauth';
2489 } else {
2490 $result = Status::newGood( true );
2493 return $result;
2497 * Get the user's real name
2498 * @return string User's real name
2500 public function getRealName() {
2501 if ( !$this->isItemLoaded( 'realname' ) ) {
2502 $this->load();
2505 return $this->mRealName;
2509 * Set the user's real name
2510 * @param string $str New real name
2512 public function setRealName( $str ) {
2513 $this->load();
2514 $this->mRealName = $str;
2518 * Get the user's current setting for a given option.
2520 * @param string $oname The option to check
2521 * @param string $defaultOverride A default value returned if the option does not exist
2522 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2523 * @return string User's current value for the option
2524 * @see getBoolOption()
2525 * @see getIntOption()
2527 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2528 global $wgHiddenPrefs;
2529 $this->loadOptions();
2531 # We want 'disabled' preferences to always behave as the default value for
2532 # users, even if they have set the option explicitly in their settings (ie they
2533 # set it, and then it was disabled removing their ability to change it). But
2534 # we don't want to erase the preferences in the database in case the preference
2535 # is re-enabled again. So don't touch $mOptions, just override the returned value
2536 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2537 return self::getDefaultOption( $oname );
2540 if ( array_key_exists( $oname, $this->mOptions ) ) {
2541 return $this->mOptions[$oname];
2542 } else {
2543 return $defaultOverride;
2548 * Get all user's options
2550 * @return array
2552 public function getOptions() {
2553 global $wgHiddenPrefs;
2554 $this->loadOptions();
2555 $options = $this->mOptions;
2557 # We want 'disabled' preferences to always behave as the default value for
2558 # users, even if they have set the option explicitly in their settings (ie they
2559 # set it, and then it was disabled removing their ability to change it). But
2560 # we don't want to erase the preferences in the database in case the preference
2561 # is re-enabled again. So don't touch $mOptions, just override the returned value
2562 foreach ( $wgHiddenPrefs as $pref ) {
2563 $default = self::getDefaultOption( $pref );
2564 if ( $default !== null ) {
2565 $options[$pref] = $default;
2569 return $options;
2573 * Get the user's current setting for a given option, as a boolean value.
2575 * @param string $oname The option to check
2576 * @return bool User's current value for the option
2577 * @see getOption()
2579 public function getBoolOption( $oname ) {
2580 return (bool)$this->getOption( $oname );
2584 * Get the user's current setting for a given option, as an integer value.
2586 * @param string $oname The option to check
2587 * @param int $defaultOverride A default value returned if the option does not exist
2588 * @return int User's current value for the option
2589 * @see getOption()
2591 public function getIntOption( $oname, $defaultOverride = 0 ) {
2592 $val = $this->getOption( $oname );
2593 if ( $val == '' ) {
2594 $val = $defaultOverride;
2596 return intval( $val );
2600 * Set the given option for a user.
2602 * You need to call saveSettings() to actually write to the database.
2604 * @param string $oname The option to set
2605 * @param mixed $val New value to set
2607 public function setOption( $oname, $val ) {
2608 $this->loadOptions();
2610 // Explicitly NULL values should refer to defaults
2611 if ( is_null( $val ) ) {
2612 $val = self::getDefaultOption( $oname );
2615 $this->mOptions[$oname] = $val;
2619 * Get a token stored in the preferences (like the watchlist one),
2620 * resetting it if it's empty (and saving changes).
2622 * @param string $oname The option name to retrieve the token from
2623 * @return string|bool User's current value for the option, or false if this option is disabled.
2624 * @see resetTokenFromOption()
2625 * @see getOption()
2627 public function getTokenFromOption( $oname ) {
2628 global $wgHiddenPrefs;
2629 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2630 return false;
2633 $token = $this->getOption( $oname );
2634 if ( !$token ) {
2635 $token = $this->resetTokenFromOption( $oname );
2636 $this->saveSettings();
2638 return $token;
2642 * Reset a token stored in the preferences (like the watchlist one).
2643 * *Does not* save user's preferences (similarly to setOption()).
2645 * @param string $oname The option name to reset the token in
2646 * @return string|bool New token value, or false if this option is disabled.
2647 * @see getTokenFromOption()
2648 * @see setOption()
2650 public function resetTokenFromOption( $oname ) {
2651 global $wgHiddenPrefs;
2652 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2653 return false;
2656 $token = MWCryptRand::generateHex( 40 );
2657 $this->setOption( $oname, $token );
2658 return $token;
2662 * Return a list of the types of user options currently returned by
2663 * User::getOptionKinds().
2665 * Currently, the option kinds are:
2666 * - 'registered' - preferences which are registered in core MediaWiki or
2667 * by extensions using the UserGetDefaultOptions hook.
2668 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2669 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2670 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2671 * be used by user scripts.
2672 * - 'special' - "preferences" that are not accessible via User::getOptions
2673 * or User::setOptions.
2674 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2675 * These are usually legacy options, removed in newer versions.
2677 * The API (and possibly others) use this function to determine the possible
2678 * option types for validation purposes, so make sure to update this when a
2679 * new option kind is added.
2681 * @see User::getOptionKinds
2682 * @return array Option kinds
2684 public static function listOptionKinds() {
2685 return array(
2686 'registered',
2687 'registered-multiselect',
2688 'registered-checkmatrix',
2689 'userjs',
2690 'special',
2691 'unused'
2696 * Return an associative array mapping preferences keys to the kind of a preference they're
2697 * used for. Different kinds are handled differently when setting or reading preferences.
2699 * See User::listOptionKinds for the list of valid option types that can be provided.
2701 * @see User::listOptionKinds
2702 * @param IContextSource $context
2703 * @param array $options Assoc. array with options keys to check as keys.
2704 * Defaults to $this->mOptions.
2705 * @return array The key => kind mapping data
2707 public function getOptionKinds( IContextSource $context, $options = null ) {
2708 $this->loadOptions();
2709 if ( $options === null ) {
2710 $options = $this->mOptions;
2713 $prefs = Preferences::getPreferences( $this, $context );
2714 $mapping = array();
2716 // Pull out the "special" options, so they don't get converted as
2717 // multiselect or checkmatrix.
2718 $specialOptions = array_fill_keys( Preferences::getSaveBlacklist(), true );
2719 foreach ( $specialOptions as $name => $value ) {
2720 unset( $prefs[$name] );
2723 // Multiselect and checkmatrix options are stored in the database with
2724 // one key per option, each having a boolean value. Extract those keys.
2725 $multiselectOptions = array();
2726 foreach ( $prefs as $name => $info ) {
2727 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2728 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2729 $opts = HTMLFormField::flattenOptions( $info['options'] );
2730 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2732 foreach ( $opts as $value ) {
2733 $multiselectOptions["$prefix$value"] = true;
2736 unset( $prefs[$name] );
2739 $checkmatrixOptions = array();
2740 foreach ( $prefs as $name => $info ) {
2741 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2742 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2743 $columns = HTMLFormField::flattenOptions( $info['columns'] );
2744 $rows = HTMLFormField::flattenOptions( $info['rows'] );
2745 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2747 foreach ( $columns as $column ) {
2748 foreach ( $rows as $row ) {
2749 $checkmatrixOptions["$prefix$column-$row"] = true;
2753 unset( $prefs[$name] );
2757 // $value is ignored
2758 foreach ( $options as $key => $value ) {
2759 if ( isset( $prefs[$key] ) ) {
2760 $mapping[$key] = 'registered';
2761 } elseif ( isset( $multiselectOptions[$key] ) ) {
2762 $mapping[$key] = 'registered-multiselect';
2763 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2764 $mapping[$key] = 'registered-checkmatrix';
2765 } elseif ( isset( $specialOptions[$key] ) ) {
2766 $mapping[$key] = 'special';
2767 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2768 $mapping[$key] = 'userjs';
2769 } else {
2770 $mapping[$key] = 'unused';
2774 return $mapping;
2778 * Reset certain (or all) options to the site defaults
2780 * The optional parameter determines which kinds of preferences will be reset.
2781 * Supported values are everything that can be reported by getOptionKinds()
2782 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2784 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2785 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2786 * for backwards-compatibility.
2787 * @param IContextSource|null $context Context source used when $resetKinds
2788 * does not contain 'all', passed to getOptionKinds().
2789 * Defaults to RequestContext::getMain() when null.
2791 public function resetOptions(
2792 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2793 IContextSource $context = null
2795 $this->load();
2796 $defaultOptions = self::getDefaultOptions();
2798 if ( !is_array( $resetKinds ) ) {
2799 $resetKinds = array( $resetKinds );
2802 if ( in_array( 'all', $resetKinds ) ) {
2803 $newOptions = $defaultOptions;
2804 } else {
2805 if ( $context === null ) {
2806 $context = RequestContext::getMain();
2809 $optionKinds = $this->getOptionKinds( $context );
2810 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
2811 $newOptions = array();
2813 // Use default values for the options that should be deleted, and
2814 // copy old values for the ones that shouldn't.
2815 foreach ( $this->mOptions as $key => $value ) {
2816 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2817 if ( array_key_exists( $key, $defaultOptions ) ) {
2818 $newOptions[$key] = $defaultOptions[$key];
2820 } else {
2821 $newOptions[$key] = $value;
2826 wfRunHooks( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions, $resetKinds ) );
2828 $this->mOptions = $newOptions;
2829 $this->mOptionsLoaded = true;
2833 * Get the user's preferred date format.
2834 * @return string User's preferred date format
2836 public function getDatePreference() {
2837 // Important migration for old data rows
2838 if ( is_null( $this->mDatePreference ) ) {
2839 global $wgLang;
2840 $value = $this->getOption( 'date' );
2841 $map = $wgLang->getDatePreferenceMigrationMap();
2842 if ( isset( $map[$value] ) ) {
2843 $value = $map[$value];
2845 $this->mDatePreference = $value;
2847 return $this->mDatePreference;
2851 * Determine based on the wiki configuration and the user's options,
2852 * whether this user must be over HTTPS no matter what.
2854 * @return bool
2856 public function requiresHTTPS() {
2857 global $wgSecureLogin;
2858 if ( !$wgSecureLogin ) {
2859 return false;
2860 } else {
2861 $https = $this->getBoolOption( 'prefershttps' );
2862 wfRunHooks( 'UserRequiresHTTPS', array( $this, &$https ) );
2863 if ( $https ) {
2864 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2866 return $https;
2871 * Get the user preferred stub threshold
2873 * @return int
2875 public function getStubThreshold() {
2876 global $wgMaxArticleSize; # Maximum article size, in Kb
2877 $threshold = $this->getIntOption( 'stubthreshold' );
2878 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2879 // If they have set an impossible value, disable the preference
2880 // so we can use the parser cache again.
2881 $threshold = 0;
2883 return $threshold;
2887 * Get the permissions this user has.
2888 * @return array Array of String permission names
2890 public function getRights() {
2891 if ( is_null( $this->mRights ) ) {
2892 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2893 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
2894 // Force reindexation of rights when a hook has unset one of them
2895 $this->mRights = array_values( array_unique( $this->mRights ) );
2897 return $this->mRights;
2901 * Get the list of explicit group memberships this user has.
2902 * The implicit * and user groups are not included.
2903 * @return array Array of String internal group names
2905 public function getGroups() {
2906 $this->load();
2907 $this->loadGroups();
2908 return $this->mGroups;
2912 * Get the list of implicit group memberships this user has.
2913 * This includes all explicit groups, plus 'user' if logged in,
2914 * '*' for all accounts, and autopromoted groups
2915 * @param bool $recache Whether to avoid the cache
2916 * @return array Array of String internal group names
2918 public function getEffectiveGroups( $recache = false ) {
2919 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
2920 wfProfileIn( __METHOD__ );
2921 $this->mEffectiveGroups = array_unique( array_merge(
2922 $this->getGroups(), // explicit groups
2923 $this->getAutomaticGroups( $recache ) // implicit groups
2924 ) );
2925 // Hook for additional groups
2926 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
2927 // Force reindexation of groups when a hook has unset one of them
2928 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
2929 wfProfileOut( __METHOD__ );
2931 return $this->mEffectiveGroups;
2935 * Get the list of implicit group memberships this user has.
2936 * This includes 'user' if logged in, '*' for all accounts,
2937 * and autopromoted groups
2938 * @param bool $recache Whether to avoid the cache
2939 * @return array Array of String internal group names
2941 public function getAutomaticGroups( $recache = false ) {
2942 if ( $recache || is_null( $this->mImplicitGroups ) ) {
2943 wfProfileIn( __METHOD__ );
2944 $this->mImplicitGroups = array( '*' );
2945 if ( $this->getId() ) {
2946 $this->mImplicitGroups[] = 'user';
2948 $this->mImplicitGroups = array_unique( array_merge(
2949 $this->mImplicitGroups,
2950 Autopromote::getAutopromoteGroups( $this )
2951 ) );
2953 if ( $recache ) {
2954 // Assure data consistency with rights/groups,
2955 // as getEffectiveGroups() depends on this function
2956 $this->mEffectiveGroups = null;
2958 wfProfileOut( __METHOD__ );
2960 return $this->mImplicitGroups;
2964 * Returns the groups the user has belonged to.
2966 * The user may still belong to the returned groups. Compare with getGroups().
2968 * The function will not return groups the user had belonged to before MW 1.17
2970 * @return array Names of the groups the user has belonged to.
2972 public function getFormerGroups() {
2973 if ( is_null( $this->mFormerGroups ) ) {
2974 $dbr = wfGetDB( DB_MASTER );
2975 $res = $dbr->select( 'user_former_groups',
2976 array( 'ufg_group' ),
2977 array( 'ufg_user' => $this->mId ),
2978 __METHOD__ );
2979 $this->mFormerGroups = array();
2980 foreach ( $res as $row ) {
2981 $this->mFormerGroups[] = $row->ufg_group;
2984 return $this->mFormerGroups;
2988 * Get the user's edit count.
2989 * @return int|null Null for anonymous users
2991 public function getEditCount() {
2992 if ( !$this->getId() ) {
2993 return null;
2996 if ( $this->mEditCount === null ) {
2997 /* Populate the count, if it has not been populated yet */
2998 wfProfileIn( __METHOD__ );
2999 $dbr = wfGetDB( DB_SLAVE );
3000 // check if the user_editcount field has been initialized
3001 $count = $dbr->selectField(
3002 'user', 'user_editcount',
3003 array( 'user_id' => $this->mId ),
3004 __METHOD__
3007 if ( $count === null ) {
3008 // it has not been initialized. do so.
3009 $count = $this->initEditCount();
3011 $this->mEditCount = $count;
3012 wfProfileOut( __METHOD__ );
3014 return (int)$this->mEditCount;
3018 * Add the user to the given group.
3019 * This takes immediate effect.
3020 * @param string $group Name of the group to add
3022 public function addGroup( $group ) {
3023 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
3024 $dbw = wfGetDB( DB_MASTER );
3025 if ( $this->getId() ) {
3026 $dbw->insert( 'user_groups',
3027 array(
3028 'ug_user' => $this->getID(),
3029 'ug_group' => $group,
3031 __METHOD__,
3032 array( 'IGNORE' ) );
3035 $this->loadGroups();
3036 $this->mGroups[] = $group;
3037 // In case loadGroups was not called before, we now have the right twice.
3038 // Get rid of the duplicate.
3039 $this->mGroups = array_unique( $this->mGroups );
3041 // Refresh the groups caches, and clear the rights cache so it will be
3042 // refreshed on the next call to $this->getRights().
3043 $this->getEffectiveGroups( true );
3044 $this->mRights = null;
3046 $this->invalidateCache();
3050 * Remove the user from the given group.
3051 * This takes immediate effect.
3052 * @param string $group Name of the group to remove
3054 public function removeGroup( $group ) {
3055 $this->load();
3056 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3057 $dbw = wfGetDB( DB_MASTER );
3058 $dbw->delete( 'user_groups',
3059 array(
3060 'ug_user' => $this->getID(),
3061 'ug_group' => $group,
3062 ), __METHOD__ );
3063 // Remember that the user was in this group
3064 $dbw->insert( 'user_former_groups',
3065 array(
3066 'ufg_user' => $this->getID(),
3067 'ufg_group' => $group,
3069 __METHOD__,
3070 array( 'IGNORE' ) );
3072 $this->loadGroups();
3073 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
3075 // Refresh the groups caches, and clear the rights cache so it will be
3076 // refreshed on the next call to $this->getRights().
3077 $this->getEffectiveGroups( true );
3078 $this->mRights = null;
3080 $this->invalidateCache();
3084 * Get whether the user is logged in
3085 * @return bool
3087 public function isLoggedIn() {
3088 return $this->getID() != 0;
3092 * Get whether the user is anonymous
3093 * @return bool
3095 public function isAnon() {
3096 return !$this->isLoggedIn();
3100 * Check if user is allowed to access a feature / make an action
3102 * @param string $permissions,... Permissions to test
3103 * @return bool True if user is allowed to perform *any* of the given actions
3105 public function isAllowedAny( /*...*/ ) {
3106 $permissions = func_get_args();
3107 foreach ( $permissions as $permission ) {
3108 if ( $this->isAllowed( $permission ) ) {
3109 return true;
3112 return false;
3117 * @param string $permissions,... Permissions to test
3118 * @return bool True if the user is allowed to perform *all* of the given actions
3120 public function isAllowedAll( /*...*/ ) {
3121 $permissions = func_get_args();
3122 foreach ( $permissions as $permission ) {
3123 if ( !$this->isAllowed( $permission ) ) {
3124 return false;
3127 return true;
3131 * Internal mechanics of testing a permission
3132 * @param string $action
3133 * @return bool
3135 public function isAllowed( $action = '' ) {
3136 if ( $action === '' ) {
3137 return true; // In the spirit of DWIM
3139 // Patrolling may not be enabled
3140 if ( $action === 'patrol' || $action === 'autopatrol' ) {
3141 global $wgUseRCPatrol, $wgUseNPPatrol;
3142 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3143 return false;
3146 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3147 // by misconfiguration: 0 == 'foo'
3148 return in_array( $action, $this->getRights(), true );
3152 * Check whether to enable recent changes patrol features for this user
3153 * @return bool True or false
3155 public function useRCPatrol() {
3156 global $wgUseRCPatrol;
3157 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3161 * Check whether to enable new pages patrol features for this user
3162 * @return bool True or false
3164 public function useNPPatrol() {
3165 global $wgUseRCPatrol, $wgUseNPPatrol;
3166 return (
3167 ( $wgUseRCPatrol || $wgUseNPPatrol )
3168 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3173 * Get the WebRequest object to use with this object
3175 * @return WebRequest
3177 public function getRequest() {
3178 if ( $this->mRequest ) {
3179 return $this->mRequest;
3180 } else {
3181 global $wgRequest;
3182 return $wgRequest;
3187 * Get the current skin, loading it if required
3188 * @return Skin The current skin
3189 * @todo FIXME: Need to check the old failback system [AV]
3190 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3192 public function getSkin() {
3193 wfDeprecated( __METHOD__, '1.18' );
3194 return RequestContext::getMain()->getSkin();
3198 * Get a WatchedItem for this user and $title.
3200 * @since 1.22 $checkRights parameter added
3201 * @param Title $title
3202 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3203 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3204 * @return WatchedItem
3206 public function getWatchedItem( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3207 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3209 if ( isset( $this->mWatchedItems[$key] ) ) {
3210 return $this->mWatchedItems[$key];
3213 if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
3214 $this->mWatchedItems = array();
3217 $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title, $checkRights );
3218 return $this->mWatchedItems[$key];
3222 * Check the watched status of an article.
3223 * @since 1.22 $checkRights parameter added
3224 * @param Title $title Title of the article to look at
3225 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3226 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3227 * @return bool
3229 public function isWatched( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3230 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3234 * Watch an article.
3235 * @since 1.22 $checkRights parameter added
3236 * @param Title $title Title of the article to look at
3237 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3238 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3240 public function addWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3241 $this->getWatchedItem( $title, $checkRights )->addWatch();
3242 $this->invalidateCache();
3246 * Stop watching an article.
3247 * @since 1.22 $checkRights parameter added
3248 * @param Title $title Title of the article to look at
3249 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3250 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3252 public function removeWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3253 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3254 $this->invalidateCache();
3258 * Clear the user's notification timestamp for the given title.
3259 * If e-notif e-mails are on, they will receive notification mails on
3260 * the next change of the page if it's watched etc.
3261 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3262 * @param Title $title Title of the article to look at
3263 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3265 public function clearNotification( &$title, $oldid = 0 ) {
3266 global $wgUseEnotif, $wgShowUpdatedMarker;
3268 // Do nothing if the database is locked to writes
3269 if ( wfReadOnly() ) {
3270 return;
3273 // Do nothing if not allowed to edit the watchlist
3274 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3275 return;
3278 // If we're working on user's talk page, we should update the talk page message indicator
3279 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3280 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3281 return;
3284 $nextid = $oldid ? $title->getNextRevisionID( $oldid ) : null;
3286 if ( !$oldid || !$nextid ) {
3287 // If we're looking at the latest revision, we should definitely clear it
3288 $this->setNewtalk( false );
3289 } else {
3290 // Otherwise we should update its revision, if it's present
3291 if ( $this->getNewtalk() ) {
3292 // Naturally the other one won't clear by itself
3293 $this->setNewtalk( false );
3294 $this->setNewtalk( true, Revision::newFromId( $nextid ) );
3299 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3300 return;
3303 if ( $this->isAnon() ) {
3304 // Nothing else to do...
3305 return;
3308 // Only update the timestamp if the page is being watched.
3309 // The query to find out if it is watched is cached both in memcached and per-invocation,
3310 // and when it does have to be executed, it can be on a slave
3311 // If this is the user's newtalk page, we always update the timestamp
3312 $force = '';
3313 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3314 $force = 'force';
3317 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3321 * Resets all of the given user's page-change notification timestamps.
3322 * If e-notif e-mails are on, they will receive notification mails on
3323 * the next change of any watched page.
3324 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3326 public function clearAllNotifications() {
3327 if ( wfReadOnly() ) {
3328 return;
3331 // Do nothing if not allowed to edit the watchlist
3332 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3333 return;
3336 global $wgUseEnotif, $wgShowUpdatedMarker;
3337 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3338 $this->setNewtalk( false );
3339 return;
3341 $id = $this->getId();
3342 if ( $id != 0 ) {
3343 $dbw = wfGetDB( DB_MASTER );
3344 $dbw->update( 'watchlist',
3345 array( /* SET */ 'wl_notificationtimestamp' => null ),
3346 array( /* WHERE */ 'wl_user' => $id ),
3347 __METHOD__
3349 // We also need to clear here the "you have new message" notification for the own user_talk page;
3350 // it's cleared one page view later in WikiPage::doViewUpdates().
3355 * Set a cookie on the user's client. Wrapper for
3356 * WebResponse::setCookie
3357 * @param string $name Name of the cookie to set
3358 * @param string $value Value to set
3359 * @param int $exp Expiration time, as a UNIX time value;
3360 * if 0 or not specified, use the default $wgCookieExpiration
3361 * @param bool $secure
3362 * true: Force setting the secure attribute when setting the cookie
3363 * false: Force NOT setting the secure attribute when setting the cookie
3364 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3365 * @param array $params Array of options sent passed to WebResponse::setcookie()
3367 protected function setCookie( $name, $value, $exp = 0, $secure = null, $params = array() ) {
3368 $params['secure'] = $secure;
3369 $this->getRequest()->response()->setcookie( $name, $value, $exp, $params );
3373 * Clear a cookie on the user's client
3374 * @param string $name Name of the cookie to clear
3375 * @param bool $secure
3376 * true: Force setting the secure attribute when setting the cookie
3377 * false: Force NOT setting the secure attribute when setting the cookie
3378 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3379 * @param array $params Array of options sent passed to WebResponse::setcookie()
3381 protected function clearCookie( $name, $secure = null, $params = array() ) {
3382 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3386 * Set the default cookies for this session on the user's client.
3388 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3389 * is passed.
3390 * @param bool $secure Whether to force secure/insecure cookies or use default
3391 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3393 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3394 if ( $request === null ) {
3395 $request = $this->getRequest();
3398 $this->load();
3399 if ( 0 == $this->mId ) {
3400 return;
3402 if ( !$this->mToken ) {
3403 // When token is empty or NULL generate a new one and then save it to the database
3404 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3405 // Simply by setting every cell in the user_token column to NULL and letting them be
3406 // regenerated as users log back into the wiki.
3407 $this->setToken();
3408 $this->saveSettings();
3410 $session = array(
3411 'wsUserID' => $this->mId,
3412 'wsToken' => $this->mToken,
3413 'wsUserName' => $this->getName()
3415 $cookies = array(
3416 'UserID' => $this->mId,
3417 'UserName' => $this->getName(),
3419 if ( $rememberMe ) {
3420 $cookies['Token'] = $this->mToken;
3421 } else {
3422 $cookies['Token'] = false;
3425 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3427 foreach ( $session as $name => $value ) {
3428 $request->setSessionData( $name, $value );
3430 foreach ( $cookies as $name => $value ) {
3431 if ( $value === false ) {
3432 $this->clearCookie( $name );
3433 } else {
3434 $this->setCookie( $name, $value, 0, $secure );
3439 * If wpStickHTTPS was selected, also set an insecure cookie that
3440 * will cause the site to redirect the user to HTTPS, if they access
3441 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3442 * as the one set by centralauth (bug 53538). Also set it to session, or
3443 * standard time setting, based on if rememberme was set.
3445 if ( $request->getCheck( 'wpStickHTTPS' ) || $this->requiresHTTPS() ) {
3446 $this->setCookie(
3447 'forceHTTPS',
3448 'true',
3449 $rememberMe ? 0 : null,
3450 false,
3451 array( 'prefix' => '' ) // no prefix
3457 * Log this user out.
3459 public function logout() {
3460 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3461 $this->doLogout();
3466 * Clear the user's cookies and session, and reset the instance cache.
3467 * @see logout()
3469 public function doLogout() {
3470 $this->clearInstanceCache( 'defaults' );
3472 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3474 $this->clearCookie( 'UserID' );
3475 $this->clearCookie( 'Token' );
3476 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3478 // Remember when user logged out, to prevent seeing cached pages
3479 $this->setCookie( 'LoggedOut', time(), time() + 86400 );
3483 * Save this user's settings into the database.
3484 * @todo Only rarely do all these fields need to be set!
3486 public function saveSettings() {
3487 global $wgAuth;
3489 $this->load();
3490 $this->loadPasswords();
3491 if ( wfReadOnly() ) {
3492 return;
3494 if ( 0 == $this->mId ) {
3495 return;
3498 $this->mTouched = self::newTouchedTimestamp();
3499 if ( !$wgAuth->allowSetLocalPassword() ) {
3500 $this->mPassword = self::getPasswordFactory()->newFromCiphertext( null );
3503 $dbw = wfGetDB( DB_MASTER );
3504 $dbw->update( 'user',
3505 array( /* SET */
3506 'user_name' => $this->mName,
3507 'user_password' => $this->mPassword->toString(),
3508 'user_newpassword' => $this->mNewpassword->toString(),
3509 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3510 'user_real_name' => $this->mRealName,
3511 'user_email' => $this->mEmail,
3512 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3513 'user_touched' => $dbw->timestamp( $this->mTouched ),
3514 'user_token' => strval( $this->mToken ),
3515 'user_email_token' => $this->mEmailToken,
3516 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3517 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires ),
3518 ), array( /* WHERE */
3519 'user_id' => $this->mId
3520 ), __METHOD__
3523 $this->saveOptions();
3525 wfRunHooks( 'UserSaveSettings', array( $this ) );
3526 $this->clearSharedCache();
3527 $this->getUserPage()->invalidateCache();
3531 * If only this user's username is known, and it exists, return the user ID.
3532 * @return int
3534 public function idForName() {
3535 $s = trim( $this->getName() );
3536 if ( $s === '' ) {
3537 return 0;
3540 $dbr = wfGetDB( DB_SLAVE );
3541 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
3542 if ( $id === false ) {
3543 $id = 0;
3545 return $id;
3549 * Add a user to the database, return the user object
3551 * @param string $name Username to add
3552 * @param array $params Array of Strings Non-default parameters to save to
3553 * the database as user_* fields:
3554 * - password: The user's password hash. Password logins will be disabled
3555 * if this is omitted.
3556 * - newpassword: Hash for a temporary password that has been mailed to
3557 * the user.
3558 * - email: The user's email address.
3559 * - email_authenticated: The email authentication timestamp.
3560 * - real_name: The user's real name.
3561 * - options: An associative array of non-default options.
3562 * - token: Random authentication token. Do not set.
3563 * - registration: Registration timestamp. Do not set.
3565 * @return User|null User object, or null if the username already exists.
3567 public static function createNew( $name, $params = array() ) {
3568 $user = new User;
3569 $user->load();
3570 $user->loadPasswords();
3571 $user->setToken(); // init token
3572 if ( isset( $params['options'] ) ) {
3573 $user->mOptions = $params['options'] + (array)$user->mOptions;
3574 unset( $params['options'] );
3576 $dbw = wfGetDB( DB_MASTER );
3577 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3579 $fields = array(
3580 'user_id' => $seqVal,
3581 'user_name' => $name,
3582 'user_password' => $user->mPassword->toString(),
3583 'user_newpassword' => $user->mNewpassword->toString(),
3584 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
3585 'user_email' => $user->mEmail,
3586 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3587 'user_real_name' => $user->mRealName,
3588 'user_token' => strval( $user->mToken ),
3589 'user_registration' => $dbw->timestamp( $user->mRegistration ),
3590 'user_editcount' => 0,
3591 'user_touched' => $dbw->timestamp( self::newTouchedTimestamp() ),
3593 foreach ( $params as $name => $value ) {
3594 $fields["user_$name"] = $value;
3596 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
3597 if ( $dbw->affectedRows() ) {
3598 $newUser = User::newFromId( $dbw->insertId() );
3599 } else {
3600 $newUser = null;
3602 return $newUser;
3606 * Add this existing user object to the database. If the user already
3607 * exists, a fatal status object is returned, and the user object is
3608 * initialised with the data from the database.
3610 * Previously, this function generated a DB error due to a key conflict
3611 * if the user already existed. Many extension callers use this function
3612 * in code along the lines of:
3614 * $user = User::newFromName( $name );
3615 * if ( !$user->isLoggedIn() ) {
3616 * $user->addToDatabase();
3618 * // do something with $user...
3620 * However, this was vulnerable to a race condition (bug 16020). By
3621 * initialising the user object if the user exists, we aim to support this
3622 * calling sequence as far as possible.
3624 * Note that if the user exists, this function will acquire a write lock,
3625 * so it is still advisable to make the call conditional on isLoggedIn(),
3626 * and to commit the transaction after calling.
3628 * @throws MWException
3629 * @return Status
3631 public function addToDatabase() {
3632 $this->load();
3633 $this->loadPasswords();
3634 if ( !$this->mToken ) {
3635 $this->setToken(); // init token
3638 $this->mTouched = self::newTouchedTimestamp();
3640 $dbw = wfGetDB( DB_MASTER );
3641 $inWrite = $dbw->writesOrCallbacksPending();
3642 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3643 $dbw->insert( 'user',
3644 array(
3645 'user_id' => $seqVal,
3646 'user_name' => $this->mName,
3647 'user_password' => $this->mPassword->toString(),
3648 'user_newpassword' => $this->mNewpassword->toString(),
3649 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3650 'user_email' => $this->mEmail,
3651 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3652 'user_real_name' => $this->mRealName,
3653 'user_token' => strval( $this->mToken ),
3654 'user_registration' => $dbw->timestamp( $this->mRegistration ),
3655 'user_editcount' => 0,
3656 'user_touched' => $dbw->timestamp( $this->mTouched ),
3657 ), __METHOD__,
3658 array( 'IGNORE' )
3660 if ( !$dbw->affectedRows() ) {
3661 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3662 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3663 if ( $inWrite ) {
3664 // Can't commit due to pending writes that may need atomicity.
3665 // This may cause some lock contention unlike the case below.
3666 $options = array( 'LOCK IN SHARE MODE' );
3667 $flags = self::READ_LOCKING;
3668 } else {
3669 // Often, this case happens early in views before any writes when
3670 // using CentralAuth. It's should be OK to commit and break the snapshot.
3671 $dbw->commit( __METHOD__, 'flush' );
3672 $options = array();
3673 $flags = 0;
3675 $this->mId = $dbw->selectField( 'user', 'user_id',
3676 array( 'user_name' => $this->mName ), __METHOD__, $options );
3677 $loaded = false;
3678 if ( $this->mId ) {
3679 if ( $this->loadFromDatabase( $flags ) ) {
3680 $loaded = true;
3683 if ( !$loaded ) {
3684 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
3685 "to insert user '{$this->mName}' row, but it was not present in select!" );
3687 return Status::newFatal( 'userexists' );
3689 $this->mId = $dbw->insertId();
3691 // Clear instance cache other than user table data, which is already accurate
3692 $this->clearInstanceCache();
3694 $this->saveOptions();
3695 return Status::newGood();
3699 * If this user is logged-in and blocked,
3700 * block any IP address they've successfully logged in from.
3701 * @return bool A block was spread
3703 public function spreadAnyEditBlock() {
3704 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3705 return $this->spreadBlock();
3707 return false;
3711 * If this (non-anonymous) user is blocked,
3712 * block the IP address they've successfully logged in from.
3713 * @return bool A block was spread
3715 protected function spreadBlock() {
3716 wfDebug( __METHOD__ . "()\n" );
3717 $this->load();
3718 if ( $this->mId == 0 ) {
3719 return false;
3722 $userblock = Block::newFromTarget( $this->getName() );
3723 if ( !$userblock ) {
3724 return false;
3727 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3731 * Get whether the user is explicitly blocked from account creation.
3732 * @return bool|Block
3734 public function isBlockedFromCreateAccount() {
3735 $this->getBlockedStatus();
3736 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
3737 return $this->mBlock;
3740 # bug 13611: if the IP address the user is trying to create an account from is
3741 # blocked with createaccount disabled, prevent new account creation there even
3742 # when the user is logged in
3743 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3744 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
3746 return $this->mBlockedFromCreateAccount instanceof Block
3747 && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
3748 ? $this->mBlockedFromCreateAccount
3749 : false;
3753 * Get whether the user is blocked from using Special:Emailuser.
3754 * @return bool
3756 public function isBlockedFromEmailuser() {
3757 $this->getBlockedStatus();
3758 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
3762 * Get whether the user is allowed to create an account.
3763 * @return bool
3765 public function isAllowedToCreateAccount() {
3766 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3770 * Get this user's personal page title.
3772 * @return Title User's personal page title
3774 public function getUserPage() {
3775 return Title::makeTitle( NS_USER, $this->getName() );
3779 * Get this user's talk page title.
3781 * @return Title User's talk page title
3783 public function getTalkPage() {
3784 $title = $this->getUserPage();
3785 return $title->getTalkPage();
3789 * Determine whether the user is a newbie. Newbies are either
3790 * anonymous IPs, or the most recently created accounts.
3791 * @return bool
3793 public function isNewbie() {
3794 return !$this->isAllowed( 'autoconfirmed' );
3798 * Check to see if the given clear-text password is one of the accepted passwords
3799 * @param string $password User password
3800 * @return bool True if the given password is correct, otherwise False
3802 public function checkPassword( $password ) {
3803 global $wgAuth, $wgLegacyEncoding;
3805 $section = new ProfileSection( __METHOD__ );
3807 $this->loadPasswords();
3809 // Certain authentication plugins do NOT want to save
3810 // domain passwords in a mysql database, so we should
3811 // check this (in case $wgAuth->strict() is false).
3812 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3813 return true;
3814 } elseif ( $wgAuth->strict() ) {
3815 // Auth plugin doesn't allow local authentication
3816 return false;
3817 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3818 // Auth plugin doesn't allow local authentication for this user name
3819 return false;
3822 if ( !$this->mPassword->equals( $password ) ) {
3823 if ( $wgLegacyEncoding ) {
3824 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3825 // Check for this with iconv
3826 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3827 if ( $cp1252Password === $password || !$this->mPassword->equals( $cp1252Password ) ) {
3828 return false;
3830 } else {
3831 return false;
3835 $passwordFactory = self::getPasswordFactory();
3836 if ( $passwordFactory->needsUpdate( $this->mPassword ) ) {
3837 $this->mPassword = $passwordFactory->newFromPlaintext( $password );
3838 $this->saveSettings();
3841 return true;
3845 * Check if the given clear-text password matches the temporary password
3846 * sent by e-mail for password reset operations.
3848 * @param string $plaintext
3850 * @return bool True if matches, false otherwise
3852 public function checkTemporaryPassword( $plaintext ) {
3853 global $wgNewPasswordExpiry;
3855 $this->load();
3856 $this->loadPasswords();
3857 if ( $this->mNewpassword->equals( $plaintext ) ) {
3858 if ( is_null( $this->mNewpassTime ) ) {
3859 return true;
3861 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
3862 return ( time() < $expiry );
3863 } else {
3864 return false;
3869 * Alias for getEditToken.
3870 * @deprecated since 1.19, use getEditToken instead.
3872 * @param string|array $salt Array of Strings Optional function-specific data for hashing
3873 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3874 * @return string The new edit token
3876 public function editToken( $salt = '', $request = null ) {
3877 wfDeprecated( __METHOD__, '1.19' );
3878 return $this->getEditToken( $salt, $request );
3882 * Internal implementation for self::getEditToken() and
3883 * self::matchEditToken().
3885 * @param string|array $salt
3886 * @param WebRequest $request
3887 * @param string|int $timestamp
3888 * @return string
3890 private function getEditTokenAtTimestamp( $salt, $request, $timestamp ) {
3891 if ( $this->isAnon() ) {
3892 return self::EDIT_TOKEN_SUFFIX;
3893 } else {
3894 $token = $request->getSessionData( 'wsEditToken' );
3895 if ( $token === null ) {
3896 $token = MWCryptRand::generateHex( 32 );
3897 $request->setSessionData( 'wsEditToken', $token );
3899 if ( is_array( $salt ) ) {
3900 $salt = implode( '|', $salt );
3902 return hash_hmac( 'md5', $timestamp . $salt, $token, false ) .
3903 dechex( $timestamp ) .
3904 self::EDIT_TOKEN_SUFFIX;
3909 * Initialize (if necessary) and return a session token value
3910 * which can be used in edit forms to show that the user's
3911 * login credentials aren't being hijacked with a foreign form
3912 * submission.
3914 * @since 1.19
3916 * @param string|array $salt Array of Strings Optional function-specific data for hashing
3917 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3918 * @return string The new edit token
3920 public function getEditToken( $salt = '', $request = null ) {
3921 return $this->getEditTokenAtTimestamp(
3922 $salt, $request ?: $this->getRequest(), wfTimestamp()
3927 * Generate a looking random token for various uses.
3929 * @return string The new random token
3930 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
3931 * wfRandomString for pseudo-randomness.
3933 public static function generateToken() {
3934 return MWCryptRand::generateHex( 32 );
3938 * Check given value against the token value stored in the session.
3939 * A match should confirm that the form was submitted from the
3940 * user's own login session, not a form submission from a third-party
3941 * site.
3943 * @param string $val Input value to compare
3944 * @param string $salt Optional function-specific data for hashing
3945 * @param WebRequest|null $request Object to use or null to use $wgRequest
3946 * @param int $maxage Fail tokens older than this, in seconds
3947 * @return bool Whether the token matches
3949 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
3950 if ( $this->isAnon() ) {
3951 return $val === self::EDIT_TOKEN_SUFFIX;
3954 $suffixLen = strlen( self::EDIT_TOKEN_SUFFIX );
3955 if ( strlen( $val ) <= 32 + $suffixLen ) {
3956 return false;
3959 $timestamp = hexdec( substr( $val, 32, -$suffixLen ) );
3960 if ( $maxage !== null && $timestamp < wfTimestamp() - $maxage ) {
3961 // Expired token
3962 return false;
3965 $sessionToken = $this->getEditTokenAtTimestamp(
3966 $salt, $request ?: $this->getRequest(), $timestamp
3969 if ( $val != $sessionToken ) {
3970 wfDebug( "User::matchEditToken: broken session data\n" );
3973 return hash_equals( $sessionToken, $val );
3977 * Check given value against the token value stored in the session,
3978 * ignoring the suffix.
3980 * @param string $val Input value to compare
3981 * @param string $salt Optional function-specific data for hashing
3982 * @param WebRequest|null $request Object to use or null to use $wgRequest
3983 * @param int $maxage Fail tokens older than this, in seconds
3984 * @return bool Whether the token matches
3986 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
3987 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self::EDIT_TOKEN_SUFFIX;
3988 return $this->matchEditToken( $val, $salt, $request, $maxage );
3992 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3993 * mail to the user's given address.
3995 * @param string $type Message to send, either "created", "changed" or "set"
3996 * @return Status
3998 public function sendConfirmationMail( $type = 'created' ) {
3999 global $wgLang;
4000 $expiration = null; // gets passed-by-ref and defined in next line.
4001 $token = $this->confirmationToken( $expiration );
4002 $url = $this->confirmationTokenUrl( $token );
4003 $invalidateURL = $this->invalidationTokenUrl( $token );
4004 $this->saveSettings();
4006 if ( $type == 'created' || $type === false ) {
4007 $message = 'confirmemail_body';
4008 } elseif ( $type === true ) {
4009 $message = 'confirmemail_body_changed';
4010 } else {
4011 // Messages: confirmemail_body_changed, confirmemail_body_set
4012 $message = 'confirmemail_body_' . $type;
4015 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4016 wfMessage( $message,
4017 $this->getRequest()->getIP(),
4018 $this->getName(),
4019 $url,
4020 $wgLang->timeanddate( $expiration, false ),
4021 $invalidateURL,
4022 $wgLang->date( $expiration, false ),
4023 $wgLang->time( $expiration, false ) )->text() );
4027 * Send an e-mail to this user's account. Does not check for
4028 * confirmed status or validity.
4030 * @param string $subject Message subject
4031 * @param string $body Message body
4032 * @param string $from Optional From address; if unspecified, default
4033 * $wgPasswordSender will be used.
4034 * @param string $replyto Reply-To address
4035 * @return Status
4037 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4038 if ( is_null( $from ) ) {
4039 global $wgPasswordSender;
4040 $sender = new MailAddress( $wgPasswordSender,
4041 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4042 } else {
4043 $sender = MailAddress::newFromUser( $from );
4046 $to = MailAddress::newFromUser( $this );
4047 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
4051 * Generate, store, and return a new e-mail confirmation code.
4052 * A hash (unsalted, since it's used as a key) is stored.
4054 * @note Call saveSettings() after calling this function to commit
4055 * this change to the database.
4057 * @param string &$expiration Accepts the expiration time
4058 * @return string New token
4060 protected function confirmationToken( &$expiration ) {
4061 global $wgUserEmailConfirmationTokenExpiry;
4062 $now = time();
4063 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
4064 $expiration = wfTimestamp( TS_MW, $expires );
4065 $this->load();
4066 $token = MWCryptRand::generateHex( 32 );
4067 $hash = md5( $token );
4068 $this->mEmailToken = $hash;
4069 $this->mEmailTokenExpires = $expiration;
4070 return $token;
4074 * Return a URL the user can use to confirm their email address.
4075 * @param string $token Accepts the email confirmation token
4076 * @return string New token URL
4078 protected function confirmationTokenUrl( $token ) {
4079 return $this->getTokenUrl( 'ConfirmEmail', $token );
4083 * Return a URL the user can use to invalidate their email address.
4084 * @param string $token Accepts the email confirmation token
4085 * @return string New token URL
4087 protected function invalidationTokenUrl( $token ) {
4088 return $this->getTokenUrl( 'InvalidateEmail', $token );
4092 * Internal function to format the e-mail validation/invalidation URLs.
4093 * This uses a quickie hack to use the
4094 * hardcoded English names of the Special: pages, for ASCII safety.
4096 * @note Since these URLs get dropped directly into emails, using the
4097 * short English names avoids insanely long URL-encoded links, which
4098 * also sometimes can get corrupted in some browsers/mailers
4099 * (bug 6957 with Gmail and Internet Explorer).
4101 * @param string $page Special page
4102 * @param string $token Token
4103 * @return string Formatted URL
4105 protected function getTokenUrl( $page, $token ) {
4106 // Hack to bypass localization of 'Special:'
4107 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
4108 return $title->getCanonicalURL();
4112 * Mark the e-mail address confirmed.
4114 * @note Call saveSettings() after calling this function to commit the change.
4116 * @return bool
4118 public function confirmEmail() {
4119 // Check if it's already confirmed, so we don't touch the database
4120 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4121 if ( !$this->isEmailConfirmed() ) {
4122 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4123 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
4125 return true;
4129 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4130 * address if it was already confirmed.
4132 * @note Call saveSettings() after calling this function to commit the change.
4133 * @return bool Returns true
4135 public function invalidateEmail() {
4136 $this->load();
4137 $this->mEmailToken = null;
4138 $this->mEmailTokenExpires = null;
4139 $this->setEmailAuthenticationTimestamp( null );
4140 $this->mEmail = '';
4141 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
4142 return true;
4146 * Set the e-mail authentication timestamp.
4147 * @param string $timestamp TS_MW timestamp
4149 public function setEmailAuthenticationTimestamp( $timestamp ) {
4150 $this->load();
4151 $this->mEmailAuthenticated = $timestamp;
4152 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
4156 * Is this user allowed to send e-mails within limits of current
4157 * site configuration?
4158 * @return bool
4160 public function canSendEmail() {
4161 global $wgEnableEmail, $wgEnableUserEmail;
4162 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4163 return false;
4165 $canSend = $this->isEmailConfirmed();
4166 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
4167 return $canSend;
4171 * Is this user allowed to receive e-mails within limits of current
4172 * site configuration?
4173 * @return bool
4175 public function canReceiveEmail() {
4176 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4180 * Is this user's e-mail address valid-looking and confirmed within
4181 * limits of the current site configuration?
4183 * @note If $wgEmailAuthentication is on, this may require the user to have
4184 * confirmed their address by returning a code or using a password
4185 * sent to the address from the wiki.
4187 * @return bool
4189 public function isEmailConfirmed() {
4190 global $wgEmailAuthentication;
4191 $this->load();
4192 $confirmed = true;
4193 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4194 if ( $this->isAnon() ) {
4195 return false;
4197 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4198 return false;
4200 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4201 return false;
4203 return true;
4204 } else {
4205 return $confirmed;
4210 * Check whether there is an outstanding request for e-mail confirmation.
4211 * @return bool
4213 public function isEmailConfirmationPending() {
4214 global $wgEmailAuthentication;
4215 return $wgEmailAuthentication &&
4216 !$this->isEmailConfirmed() &&
4217 $this->mEmailToken &&
4218 $this->mEmailTokenExpires > wfTimestamp();
4222 * Get the timestamp of account creation.
4224 * @return string|bool|null Timestamp of account creation, false for
4225 * non-existent/anonymous user accounts, or null if existing account
4226 * but information is not in database.
4228 public function getRegistration() {
4229 if ( $this->isAnon() ) {
4230 return false;
4232 $this->load();
4233 return $this->mRegistration;
4237 * Get the timestamp of the first edit
4239 * @return string|bool Timestamp of first edit, or false for
4240 * non-existent/anonymous user accounts.
4242 public function getFirstEditTimestamp() {
4243 if ( $this->getId() == 0 ) {
4244 return false; // anons
4246 $dbr = wfGetDB( DB_SLAVE );
4247 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4248 array( 'rev_user' => $this->getId() ),
4249 __METHOD__,
4250 array( 'ORDER BY' => 'rev_timestamp ASC' )
4252 if ( !$time ) {
4253 return false; // no edits
4255 return wfTimestamp( TS_MW, $time );
4259 * Get the permissions associated with a given list of groups
4261 * @param array $groups Array of Strings List of internal group names
4262 * @return array Array of Strings List of permission key names for given groups combined
4264 public static function getGroupPermissions( $groups ) {
4265 global $wgGroupPermissions, $wgRevokePermissions;
4266 $rights = array();
4267 // grant every granted permission first
4268 foreach ( $groups as $group ) {
4269 if ( isset( $wgGroupPermissions[$group] ) ) {
4270 $rights = array_merge( $rights,
4271 // array_filter removes empty items
4272 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4275 // now revoke the revoked permissions
4276 foreach ( $groups as $group ) {
4277 if ( isset( $wgRevokePermissions[$group] ) ) {
4278 $rights = array_diff( $rights,
4279 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4282 return array_unique( $rights );
4286 * Get all the groups who have a given permission
4288 * @param string $role Role to check
4289 * @return array Array of Strings List of internal group names with the given permission
4291 public static function getGroupsWithPermission( $role ) {
4292 global $wgGroupPermissions;
4293 $allowedGroups = array();
4294 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4295 if ( self::groupHasPermission( $group, $role ) ) {
4296 $allowedGroups[] = $group;
4299 return $allowedGroups;
4303 * Check, if the given group has the given permission
4305 * If you're wanting to check whether all users have a permission, use
4306 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4307 * from anyone.
4309 * @since 1.21
4310 * @param string $group Group to check
4311 * @param string $role Role to check
4312 * @return bool
4314 public static function groupHasPermission( $group, $role ) {
4315 global $wgGroupPermissions, $wgRevokePermissions;
4316 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4317 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4321 * Check if all users have the given permission
4323 * @since 1.22
4324 * @param string $right Right to check
4325 * @return bool
4327 public static function isEveryoneAllowed( $right ) {
4328 global $wgGroupPermissions, $wgRevokePermissions;
4329 static $cache = array();
4331 // Use the cached results, except in unit tests which rely on
4332 // being able change the permission mid-request
4333 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4334 return $cache[$right];
4337 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
4338 $cache[$right] = false;
4339 return false;
4342 // If it's revoked anywhere, then everyone doesn't have it
4343 foreach ( $wgRevokePermissions as $rights ) {
4344 if ( isset( $rights[$right] ) && $rights[$right] ) {
4345 $cache[$right] = false;
4346 return false;
4350 // Allow extensions (e.g. OAuth) to say false
4351 if ( !wfRunHooks( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4352 $cache[$right] = false;
4353 return false;
4356 $cache[$right] = true;
4357 return true;
4361 * Get the localized descriptive name for a group, if it exists
4363 * @param string $group Internal group name
4364 * @return string Localized descriptive group name
4366 public static function getGroupName( $group ) {
4367 $msg = wfMessage( "group-$group" );
4368 return $msg->isBlank() ? $group : $msg->text();
4372 * Get the localized descriptive name for a member of a group, if it exists
4374 * @param string $group Internal group name
4375 * @param string $username Username for gender (since 1.19)
4376 * @return string Localized name for group member
4378 public static function getGroupMember( $group, $username = '#' ) {
4379 $msg = wfMessage( "group-$group-member", $username );
4380 return $msg->isBlank() ? $group : $msg->text();
4384 * Return the set of defined explicit groups.
4385 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4386 * are not included, as they are defined automatically, not in the database.
4387 * @return array Array of internal group names
4389 public static function getAllGroups() {
4390 global $wgGroupPermissions, $wgRevokePermissions;
4391 return array_diff(
4392 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4393 self::getImplicitGroups()
4398 * Get a list of all available permissions.
4399 * @return array Array of permission names
4401 public static function getAllRights() {
4402 if ( self::$mAllRights === false ) {
4403 global $wgAvailableRights;
4404 if ( count( $wgAvailableRights ) ) {
4405 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
4406 } else {
4407 self::$mAllRights = self::$mCoreRights;
4409 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
4411 return self::$mAllRights;
4415 * Get a list of implicit groups
4416 * @return array Array of Strings Array of internal group names
4418 public static function getImplicitGroups() {
4419 global $wgImplicitGroups;
4421 $groups = $wgImplicitGroups;
4422 # Deprecated, use $wgImplicitGroups instead
4423 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4425 return $groups;
4429 * Get the title of a page describing a particular group
4431 * @param string $group Internal group name
4432 * @return Title|bool Title of the page if it exists, false otherwise
4434 public static function getGroupPage( $group ) {
4435 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4436 if ( $msg->exists() ) {
4437 $title = Title::newFromText( $msg->text() );
4438 if ( is_object( $title ) ) {
4439 return $title;
4442 return false;
4446 * Create a link to the group in HTML, if available;
4447 * else return the group name.
4449 * @param string $group Internal name of the group
4450 * @param string $text The text of the link
4451 * @return string HTML link to the group
4453 public static function makeGroupLinkHTML( $group, $text = '' ) {
4454 if ( $text == '' ) {
4455 $text = self::getGroupName( $group );
4457 $title = self::getGroupPage( $group );
4458 if ( $title ) {
4459 return Linker::link( $title, htmlspecialchars( $text ) );
4460 } else {
4461 return $text;
4466 * Create a link to the group in Wikitext, if available;
4467 * else return the group name.
4469 * @param string $group Internal name of the group
4470 * @param string $text The text of the link
4471 * @return string Wikilink to the group
4473 public static function makeGroupLinkWiki( $group, $text = '' ) {
4474 if ( $text == '' ) {
4475 $text = self::getGroupName( $group );
4477 $title = self::getGroupPage( $group );
4478 if ( $title ) {
4479 $page = $title->getFullText();
4480 return "[[$page|$text]]";
4481 } else {
4482 return $text;
4487 * Returns an array of the groups that a particular group can add/remove.
4489 * @param string $group The group to check for whether it can add/remove
4490 * @return array Array( 'add' => array( addablegroups ),
4491 * 'remove' => array( removablegroups ),
4492 * 'add-self' => array( addablegroups to self),
4493 * 'remove-self' => array( removable groups from self) )
4495 public static function changeableByGroup( $group ) {
4496 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4498 $groups = array(
4499 'add' => array(),
4500 'remove' => array(),
4501 'add-self' => array(),
4502 'remove-self' => array()
4505 if ( empty( $wgAddGroups[$group] ) ) {
4506 // Don't add anything to $groups
4507 } elseif ( $wgAddGroups[$group] === true ) {
4508 // You get everything
4509 $groups['add'] = self::getAllGroups();
4510 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4511 $groups['add'] = $wgAddGroups[$group];
4514 // Same thing for remove
4515 if ( empty( $wgRemoveGroups[$group] ) ) {
4516 // Do nothing
4517 } elseif ( $wgRemoveGroups[$group] === true ) {
4518 $groups['remove'] = self::getAllGroups();
4519 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4520 $groups['remove'] = $wgRemoveGroups[$group];
4523 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4524 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4525 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4526 if ( is_int( $key ) ) {
4527 $wgGroupsAddToSelf['user'][] = $value;
4532 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4533 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4534 if ( is_int( $key ) ) {
4535 $wgGroupsRemoveFromSelf['user'][] = $value;
4540 // Now figure out what groups the user can add to him/herself
4541 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4542 // Do nothing
4543 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4544 // No idea WHY this would be used, but it's there
4545 $groups['add-self'] = User::getAllGroups();
4546 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4547 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4550 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4551 // Do nothing
4552 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4553 $groups['remove-self'] = User::getAllGroups();
4554 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4555 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4558 return $groups;
4562 * Returns an array of groups that this user can add and remove
4563 * @return array Array( 'add' => array( addablegroups ),
4564 * 'remove' => array( removablegroups ),
4565 * 'add-self' => array( addablegroups to self),
4566 * 'remove-self' => array( removable groups from self) )
4568 public function changeableGroups() {
4569 if ( $this->isAllowed( 'userrights' ) ) {
4570 // This group gives the right to modify everything (reverse-
4571 // compatibility with old "userrights lets you change
4572 // everything")
4573 // Using array_merge to make the groups reindexed
4574 $all = array_merge( User::getAllGroups() );
4575 return array(
4576 'add' => $all,
4577 'remove' => $all,
4578 'add-self' => array(),
4579 'remove-self' => array()
4583 // Okay, it's not so simple, we will have to go through the arrays
4584 $groups = array(
4585 'add' => array(),
4586 'remove' => array(),
4587 'add-self' => array(),
4588 'remove-self' => array()
4590 $addergroups = $this->getEffectiveGroups();
4592 foreach ( $addergroups as $addergroup ) {
4593 $groups = array_merge_recursive(
4594 $groups, $this->changeableByGroup( $addergroup )
4596 $groups['add'] = array_unique( $groups['add'] );
4597 $groups['remove'] = array_unique( $groups['remove'] );
4598 $groups['add-self'] = array_unique( $groups['add-self'] );
4599 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4601 return $groups;
4605 * Increment the user's edit-count field.
4606 * Will have no effect for anonymous users.
4608 public function incEditCount() {
4609 if ( !$this->isAnon() ) {
4610 $dbw = wfGetDB( DB_MASTER );
4611 $dbw->update(
4612 'user',
4613 array( 'user_editcount=user_editcount+1' ),
4614 array( 'user_id' => $this->getId() ),
4615 __METHOD__
4618 // Lazy initialization check...
4619 if ( $dbw->affectedRows() == 0 ) {
4620 // Now here's a goddamn hack...
4621 $dbr = wfGetDB( DB_SLAVE );
4622 if ( $dbr !== $dbw ) {
4623 // If we actually have a slave server, the count is
4624 // at least one behind because the current transaction
4625 // has not been committed and replicated.
4626 $this->initEditCount( 1 );
4627 } else {
4628 // But if DB_SLAVE is selecting the master, then the
4629 // count we just read includes the revision that was
4630 // just added in the working transaction.
4631 $this->initEditCount();
4635 // edit count in user cache too
4636 $this->invalidateCache();
4640 * Initialize user_editcount from data out of the revision table
4642 * @param int $add Edits to add to the count from the revision table
4643 * @return int Number of edits
4645 protected function initEditCount( $add = 0 ) {
4646 // Pull from a slave to be less cruel to servers
4647 // Accuracy isn't the point anyway here
4648 $dbr = wfGetDB( DB_SLAVE );
4649 $count = (int)$dbr->selectField(
4650 'revision',
4651 'COUNT(rev_user)',
4652 array( 'rev_user' => $this->getId() ),
4653 __METHOD__
4655 $count = $count + $add;
4657 $dbw = wfGetDB( DB_MASTER );
4658 $dbw->update(
4659 'user',
4660 array( 'user_editcount' => $count ),
4661 array( 'user_id' => $this->getId() ),
4662 __METHOD__
4665 return $count;
4669 * Get the description of a given right
4671 * @param string $right Right to query
4672 * @return string Localized description of the right
4674 public static function getRightDescription( $right ) {
4675 $key = "right-$right";
4676 $msg = wfMessage( $key );
4677 return $msg->isBlank() ? $right : $msg->text();
4681 * Make a new-style password hash
4683 * @param string $password Plain-text password
4684 * @param bool|string $salt Optional salt, may be random or the user ID.
4685 * If unspecified or false, will generate one automatically
4686 * @return string Password hash
4687 * @deprecated since 1.24, use Password class
4689 public static function crypt( $password, $salt = false ) {
4690 wfDeprecated( __METHOD__, '1.24' );
4691 $hash = self::getPasswordFactory()->newFromPlaintext( $password );
4692 return $hash->toString();
4696 * Compare a password hash with a plain-text password. Requires the user
4697 * ID if there's a chance that the hash is an old-style hash.
4699 * @param string $hash Password hash
4700 * @param string $password Plain-text password to compare
4701 * @param string|bool $userId User ID for old-style password salt
4703 * @return bool
4704 * @deprecated since 1.24, use Password class
4706 public static function comparePasswords( $hash, $password, $userId = false ) {
4707 wfDeprecated( __METHOD__, '1.24' );
4709 // Check for *really* old password hashes that don't even have a type
4710 // The old hash format was just an md5 hex hash, with no type information
4711 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4712 global $wgPasswordSalt;
4713 if ( $wgPasswordSalt ) {
4714 $password = ":B:{$userId}:{$hash}";
4715 } else {
4716 $password = ":A:{$hash}";
4720 $hash = self::getPasswordFactory()->newFromCiphertext( $hash );
4721 return $hash->equals( $password );
4725 * Add a newuser log entry for this user.
4726 * Before 1.19 the return value was always true.
4728 * @param string|bool $action Account creation type.
4729 * - String, one of the following values:
4730 * - 'create' for an anonymous user creating an account for himself.
4731 * This will force the action's performer to be the created user itself,
4732 * no matter the value of $wgUser
4733 * - 'create2' for a logged in user creating an account for someone else
4734 * - 'byemail' when the created user will receive its password by e-mail
4735 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4736 * - Boolean means whether the account was created by e-mail (deprecated):
4737 * - true will be converted to 'byemail'
4738 * - false will be converted to 'create' if this object is the same as
4739 * $wgUser and to 'create2' otherwise
4741 * @param string $reason User supplied reason
4743 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4745 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4746 global $wgUser, $wgNewUserLog;
4747 if ( empty( $wgNewUserLog ) ) {
4748 return true; // disabled
4751 if ( $action === true ) {
4752 $action = 'byemail';
4753 } elseif ( $action === false ) {
4754 if ( $this->getName() == $wgUser->getName() ) {
4755 $action = 'create';
4756 } else {
4757 $action = 'create2';
4761 if ( $action === 'create' || $action === 'autocreate' ) {
4762 $performer = $this;
4763 } else {
4764 $performer = $wgUser;
4767 $logEntry = new ManualLogEntry( 'newusers', $action );
4768 $logEntry->setPerformer( $performer );
4769 $logEntry->setTarget( $this->getUserPage() );
4770 $logEntry->setComment( $reason );
4771 $logEntry->setParameters( array(
4772 '4::userid' => $this->getId(),
4773 ) );
4774 $logid = $logEntry->insert();
4776 if ( $action !== 'autocreate' ) {
4777 $logEntry->publish( $logid );
4780 return (int)$logid;
4784 * Add an autocreate newuser log entry for this user
4785 * Used by things like CentralAuth and perhaps other authplugins.
4786 * Consider calling addNewUserLogEntry() directly instead.
4788 * @return bool
4790 public function addNewUserLogEntryAutoCreate() {
4791 $this->addNewUserLogEntry( 'autocreate' );
4793 return true;
4797 * Load the user options either from cache, the database or an array
4799 * @param array $data Rows for the current user out of the user_properties table
4801 protected function loadOptions( $data = null ) {
4802 global $wgContLang;
4804 $this->load();
4806 if ( $this->mOptionsLoaded ) {
4807 return;
4810 $this->mOptions = self::getDefaultOptions();
4812 if ( !$this->getId() ) {
4813 // For unlogged-in users, load language/variant options from request.
4814 // There's no need to do it for logged-in users: they can set preferences,
4815 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4816 // so don't override user's choice (especially when the user chooses site default).
4817 $variant = $wgContLang->getDefaultVariant();
4818 $this->mOptions['variant'] = $variant;
4819 $this->mOptions['language'] = $variant;
4820 $this->mOptionsLoaded = true;
4821 return;
4824 // Maybe load from the object
4825 if ( !is_null( $this->mOptionOverrides ) ) {
4826 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4827 foreach ( $this->mOptionOverrides as $key => $value ) {
4828 $this->mOptions[$key] = $value;
4830 } else {
4831 if ( !is_array( $data ) ) {
4832 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4833 // Load from database
4834 $dbr = wfGetDB( DB_SLAVE );
4836 $res = $dbr->select(
4837 'user_properties',
4838 array( 'up_property', 'up_value' ),
4839 array( 'up_user' => $this->getId() ),
4840 __METHOD__
4843 $this->mOptionOverrides = array();
4844 $data = array();
4845 foreach ( $res as $row ) {
4846 $data[$row->up_property] = $row->up_value;
4849 foreach ( $data as $property => $value ) {
4850 $this->mOptionOverrides[$property] = $value;
4851 $this->mOptions[$property] = $value;
4855 $this->mOptionsLoaded = true;
4857 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
4861 * Saves the non-default options for this user, as previously set e.g. via
4862 * setOption(), in the database's "user_properties" (preferences) table.
4863 * Usually used via saveSettings().
4865 protected function saveOptions() {
4866 $this->loadOptions();
4868 // Not using getOptions(), to keep hidden preferences in database
4869 $saveOptions = $this->mOptions;
4871 // Allow hooks to abort, for instance to save to a global profile.
4872 // Reset options to default state before saving.
4873 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4874 return;
4877 $userId = $this->getId();
4879 $insert_rows = array(); // all the new preference rows
4880 foreach ( $saveOptions as $key => $value ) {
4881 // Don't bother storing default values
4882 $defaultOption = self::getDefaultOption( $key );
4883 if ( ( $defaultOption === null && $value !== false && $value !== null )
4884 || $value != $defaultOption
4886 $insert_rows[] = array(
4887 'up_user' => $userId,
4888 'up_property' => $key,
4889 'up_value' => $value,
4894 $dbw = wfGetDB( DB_MASTER );
4896 $res = $dbw->select( 'user_properties',
4897 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__ );
4899 // Find prior rows that need to be removed or updated. These rows will
4900 // all be deleted (the later so that INSERT IGNORE applies the new values).
4901 $keysDelete = array();
4902 foreach ( $res as $row ) {
4903 if ( !isset( $saveOptions[$row->up_property] )
4904 || strcmp( $saveOptions[$row->up_property], $row->up_value ) != 0
4906 $keysDelete[] = $row->up_property;
4910 if ( count( $keysDelete ) ) {
4911 // Do the DELETE by PRIMARY KEY for prior rows.
4912 // In the past a very large portion of calls to this function are for setting
4913 // 'rememberpassword' for new accounts (a preference that has since been removed).
4914 // Doing a blanket per-user DELETE for new accounts with no rows in the table
4915 // caused gap locks on [max user ID,+infinity) which caused high contention since
4916 // updates would pile up on each other as they are for higher (newer) user IDs.
4917 // It might not be necessary these days, but it shouldn't hurt either.
4918 $dbw->delete( 'user_properties',
4919 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__ );
4921 // Insert the new preference rows
4922 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, array( 'IGNORE' ) );
4926 * Lazily instantiate and return a factory object for making passwords
4928 * @return PasswordFactory
4930 public static function getPasswordFactory() {
4931 if ( self::$mPasswordFactory === null ) {
4932 self::$mPasswordFactory = new PasswordFactory();
4933 self::$mPasswordFactory->init( RequestContext::getMain()->getConfig() );
4936 return self::$mPasswordFactory;
4940 * Provide an array of HTML5 attributes to put on an input element
4941 * intended for the user to enter a new password. This may include
4942 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4944 * Do *not* use this when asking the user to enter his current password!
4945 * Regardless of configuration, users may have invalid passwords for whatever
4946 * reason (e.g., they were set before requirements were tightened up).
4947 * Only use it when asking for a new password, like on account creation or
4948 * ResetPass.
4950 * Obviously, you still need to do server-side checking.
4952 * NOTE: A combination of bugs in various browsers means that this function
4953 * actually just returns array() unconditionally at the moment. May as
4954 * well keep it around for when the browser bugs get fixed, though.
4956 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4958 * @return array Array of HTML attributes suitable for feeding to
4959 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4960 * That will get confused by the boolean attribute syntax used.)
4962 public static function passwordChangeInputAttribs() {
4963 global $wgMinimalPasswordLength;
4965 if ( $wgMinimalPasswordLength == 0 ) {
4966 return array();
4969 # Note that the pattern requirement will always be satisfied if the
4970 # input is empty, so we need required in all cases.
4972 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4973 # if e-mail confirmation is being used. Since HTML5 input validation
4974 # is b0rked anyway in some browsers, just return nothing. When it's
4975 # re-enabled, fix this code to not output required for e-mail
4976 # registration.
4977 #$ret = array( 'required' );
4978 $ret = array();
4980 # We can't actually do this right now, because Opera 9.6 will print out
4981 # the entered password visibly in its error message! When other
4982 # browsers add support for this attribute, or Opera fixes its support,
4983 # we can add support with a version check to avoid doing this on Opera
4984 # versions where it will be a problem. Reported to Opera as
4985 # DSK-262266, but they don't have a public bug tracker for us to follow.
4987 if ( $wgMinimalPasswordLength > 1 ) {
4988 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4989 $ret['title'] = wfMessage( 'passwordtooshort' )
4990 ->numParams( $wgMinimalPasswordLength )->text();
4994 return $ret;
4998 * Return the list of user fields that should be selected to create
4999 * a new user object.
5000 * @return array
5002 public static function selectFields() {
5003 return array(
5004 'user_id',
5005 'user_name',
5006 'user_real_name',
5007 'user_email',
5008 'user_touched',
5009 'user_token',
5010 'user_email_authenticated',
5011 'user_email_token',
5012 'user_email_token_expires',
5013 'user_registration',
5014 'user_editcount',
5019 * Factory function for fatal permission-denied errors
5021 * @since 1.22
5022 * @param string $permission User right required
5023 * @return Status
5025 static function newFatalPermissionDeniedStatus( $permission ) {
5026 global $wgLang;
5028 $groups = array_map(
5029 array( 'User', 'makeGroupLinkWiki' ),
5030 User::getGroupsWithPermission( $permission )
5033 if ( $groups ) {
5034 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5035 } else {
5036 return Status::newFatal( 'badaccess-group0' );