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