Merge "Rename Parser_DiffTest class to ParserDiffTest"
[mediawiki.git] / includes / User.php
blobf2d3d9b18dfd913d5bf7102f32f15527a3f7ee81
1 <?php
2 /**
3 * Implements the User class for the %MediaWiki software.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
23 /**
24 * Int Number of characters in user_token field.
25 * @ingroup Constants
27 define( 'USER_TOKEN_LENGTH', 32 );
29 /**
30 * Int Serialized record version.
31 * @ingroup Constants
33 define( 'MW_USER_VERSION', 9 );
35 /**
36 * String Some punctuation to prevent editing from broken text-mangling proxies.
37 * @ingroup Constants
39 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
41 /**
42 * Thrown by User::setPassword() on error.
43 * @ingroup Exception
45 class PasswordError extends MWException {
46 // NOP
49 /**
50 * The User object encapsulates all of the user-specific settings (user_id,
51 * name, rights, password, email address, options, last login time). Client
52 * classes use the getXXX() functions to access these fields. These functions
53 * do all the work of determining whether the user is logged in,
54 * whether the requested option can be satisfied from cookies or
55 * whether a database query is needed. Most of the settings needed
56 * for rendering normal pages are set in the cookie to minimize use
57 * of the database.
59 class User {
60 /**
61 * Global constants made accessible as class constants so that autoloader
62 * magic can be used.
64 const USER_TOKEN_LENGTH = USER_TOKEN_LENGTH;
65 const MW_USER_VERSION = MW_USER_VERSION;
66 const EDIT_TOKEN_SUFFIX = EDIT_TOKEN_SUFFIX;
68 /**
69 * Maximum items in $mWatchedItems
71 const MAX_WATCHED_ITEMS_CACHE = 100;
73 /**
74 * Array of Strings List of member variables which are saved to the
75 * shared cache (memcached). Any operation which changes the
76 * corresponding database fields must call a cache-clearing function.
77 * @showinitializer
79 protected static $mCacheVars = array(
80 // user table
81 'mId',
82 'mName',
83 'mRealName',
84 'mPassword',
85 'mNewpassword',
86 'mNewpassTime',
87 'mEmail',
88 'mTouched',
89 'mToken',
90 'mEmailAuthenticated',
91 'mEmailToken',
92 'mEmailTokenExpires',
93 'mPasswordExpires',
94 'mRegistration',
95 'mEditCount',
96 // user_groups table
97 'mGroups',
98 // user_properties table
99 'mOptionOverrides',
103 * Array of Strings Core rights.
104 * Each of these should have a corresponding message of the form
105 * "right-$right".
106 * @showinitializer
108 protected static $mCoreRights = array(
109 'apihighlimits',
110 'autoconfirmed',
111 'autopatrol',
112 'bigdelete',
113 'block',
114 'blockemail',
115 'bot',
116 'browsearchive',
117 'createaccount',
118 'createpage',
119 'createtalk',
120 'delete',
121 'deletedhistory',
122 'deletedtext',
123 'deletelogentry',
124 'deleterevision',
125 'edit',
126 'editinterface',
127 'editprotected',
128 'editmyoptions',
129 'editmyprivateinfo',
130 'editmyusercss',
131 'editmyuserjs',
132 'editmywatchlist',
133 'editsemiprotected',
134 'editusercssjs', #deprecated
135 'editusercss',
136 'edituserjs',
137 'hideuser',
138 'import',
139 'importupload',
140 'ipblock-exempt',
141 'markbotedits',
142 'mergehistory',
143 'minoredit',
144 'move',
145 'movefile',
146 'move-categorypages',
147 'move-rootuserpages',
148 'move-subpages',
149 'nominornewtalk',
150 'noratelimit',
151 'override-export-depth',
152 'passwordreset',
153 'patrol',
154 'patrolmarks',
155 'protect',
156 'proxyunbannable',
157 'purge',
158 'read',
159 'reupload',
160 'reupload-own',
161 'reupload-shared',
162 'rollback',
163 'sendemail',
164 'siteadmin',
165 'suppressionlog',
166 'suppressredirect',
167 'suppressrevision',
168 'unblockself',
169 'undelete',
170 'unwatchedpages',
171 'upload',
172 'upload_by_url',
173 'userrights',
174 'userrights-interwiki',
175 'viewmyprivateinfo',
176 'viewmywatchlist',
177 'writeapi',
181 * String Cached results of getAllRights()
183 protected static $mAllRights = false;
185 /** @name Cache variables */
186 //@{
187 public $mId;
189 public $mName;
191 public $mRealName;
193 public $mPassword;
195 public $mNewpassword;
197 public $mNewpassTime;
199 public $mEmail;
201 public $mTouched;
203 protected $mToken;
205 public $mEmailAuthenticated;
207 protected $mEmailToken;
209 protected $mEmailTokenExpires;
211 protected $mRegistration;
213 protected $mEditCount;
215 public $mGroups;
217 protected $mOptionOverrides;
219 protected $mPasswordExpires;
220 //@}
223 * Bool Whether the cache variables have been loaded.
225 //@{
226 public $mOptionsLoaded;
229 * Array with already loaded items or true if all items have been loaded.
231 protected $mLoadedItems = array();
232 //@}
235 * String Initialization data source if mLoadedItems!==true. May be one of:
236 * - 'defaults' anonymous user initialised from class defaults
237 * - 'name' initialise from mName
238 * - 'id' initialise from mId
239 * - 'session' log in from cookies or session if possible
241 * Use the User::newFrom*() family of functions to set this.
243 public $mFrom;
246 * Lazy-initialized variables, invalidated with clearInstanceCache
248 protected $mNewtalk;
250 protected $mDatePreference;
252 public $mBlockedby;
254 protected $mHash;
256 public $mRights;
258 protected $mBlockreason;
260 protected $mEffectiveGroups;
262 protected $mImplicitGroups;
264 protected $mFormerGroups;
266 protected $mBlockedGlobally;
268 protected $mLocked;
270 public $mHideName;
272 public $mOptions;
275 * @var WebRequest
277 private $mRequest;
279 /** @var Block */
280 public $mBlock;
282 /** @var bool */
283 protected $mAllowUsertalk;
285 /** @var Block */
286 private $mBlockedFromCreateAccount = false;
288 /** @var array */
289 private $mWatchedItems = array();
291 public static $idCacheByName = array();
294 * Lightweight constructor for an anonymous user.
295 * Use the User::newFrom* factory functions for other kinds of users.
297 * @see newFromName()
298 * @see newFromId()
299 * @see newFromConfirmationCode()
300 * @see newFromSession()
301 * @see newFromRow()
303 public function __construct() {
304 $this->clearInstanceCache( 'defaults' );
308 * @return string
310 public function __toString() {
311 return $this->getName();
315 * Load the user table data for this object from the source given by mFrom.
317 public function load() {
318 if ( $this->mLoadedItems === true ) {
319 return;
321 wfProfileIn( __METHOD__ );
323 // Set it now to avoid infinite recursion in accessors
324 $this->mLoadedItems = true;
326 switch ( $this->mFrom ) {
327 case 'defaults':
328 $this->loadDefaults();
329 break;
330 case 'name':
331 $this->mId = self::idFromName( $this->mName );
332 if ( !$this->mId ) {
333 // Nonexistent user placeholder object
334 $this->loadDefaults( $this->mName );
335 } else {
336 $this->loadFromId();
338 break;
339 case 'id':
340 $this->loadFromId();
341 break;
342 case 'session':
343 if ( !$this->loadFromSession() ) {
344 // Loading from session failed. Load defaults.
345 $this->loadDefaults();
347 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
348 break;
349 default:
350 wfProfileOut( __METHOD__ );
351 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
353 wfProfileOut( __METHOD__ );
357 * Load user table data, given mId has already been set.
358 * @return bool false if the ID does not exist, true otherwise
360 public function loadFromId() {
361 global $wgMemc;
362 if ( $this->mId == 0 ) {
363 $this->loadDefaults();
364 return false;
367 // Try cache
368 $key = wfMemcKey( 'user', 'id', $this->mId );
369 $data = $wgMemc->get( $key );
370 if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
371 // Object is expired, load from DB
372 $data = false;
375 if ( !$data ) {
376 wfDebug( "User: cache miss for user {$this->mId}\n" );
377 // Load from DB
378 if ( !$this->loadFromDatabase() ) {
379 // Can't load from ID, user is anonymous
380 return false;
382 $this->saveToCache();
383 } else {
384 wfDebug( "User: got user {$this->mId} from cache\n" );
385 // Restore from cache
386 foreach ( self::$mCacheVars as $name ) {
387 $this->$name = $data[$name];
391 $this->mLoadedItems = true;
393 return true;
397 * Save user data to the shared cache
399 public function saveToCache() {
400 $this->load();
401 $this->loadGroups();
402 $this->loadOptions();
403 if ( $this->isAnon() ) {
404 // Anonymous users are uncached
405 return;
407 $data = array();
408 foreach ( self::$mCacheVars as $name ) {
409 $data[$name] = $this->$name;
411 $data['mVersion'] = MW_USER_VERSION;
412 $key = wfMemcKey( 'user', 'id', $this->mId );
413 global $wgMemc;
414 $wgMemc->set( $key, $data );
417 /** @name newFrom*() static factory methods */
418 //@{
421 * Static factory method for creation from username.
423 * This is slightly less efficient than newFromId(), so use newFromId() if
424 * you have both an ID and a name handy.
426 * @param string $name Username, validated by Title::newFromText()
427 * @param string|bool $validate Validate username. Takes the same parameters as
428 * User::getCanonicalName(), except that true is accepted as an alias
429 * for 'valid', for BC.
431 * @return User|bool User object, or false if the username is invalid
432 * (e.g. if it contains illegal characters or is an IP address). If the
433 * username is not present in the database, the result will be a user object
434 * with a name, zero user ID and default settings.
436 public static function newFromName( $name, $validate = 'valid' ) {
437 if ( $validate === true ) {
438 $validate = 'valid';
440 $name = self::getCanonicalName( $name, $validate );
441 if ( $name === false ) {
442 return false;
443 } else {
444 // Create unloaded user object
445 $u = new User;
446 $u->mName = $name;
447 $u->mFrom = 'name';
448 $u->setItemLoaded( 'name' );
449 return $u;
454 * Static factory method for creation from a given user ID.
456 * @param int $id Valid user ID
457 * @return User The corresponding User object
459 public static function newFromId( $id ) {
460 $u = new User;
461 $u->mId = $id;
462 $u->mFrom = 'id';
463 $u->setItemLoaded( 'id' );
464 return $u;
468 * Factory method to fetch whichever user has a given email confirmation code.
469 * This code is generated when an account is created or its e-mail address
470 * has changed.
472 * If the code is invalid or has expired, returns NULL.
474 * @param string $code Confirmation code
475 * @return User|null
477 public static function newFromConfirmationCode( $code ) {
478 $dbr = wfGetDB( DB_SLAVE );
479 $id = $dbr->selectField( 'user', 'user_id', array(
480 'user_email_token' => md5( $code ),
481 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
482 ) );
483 if ( $id !== false ) {
484 return User::newFromId( $id );
485 } else {
486 return null;
491 * Create a new user object using data from session or cookies. If the
492 * login credentials are invalid, the result is an anonymous user.
494 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
495 * @return User
497 public static function newFromSession( WebRequest $request = null ) {
498 $user = new User;
499 $user->mFrom = 'session';
500 $user->mRequest = $request;
501 return $user;
505 * Create a new user object from a user row.
506 * The row should have the following fields from the user table in it:
507 * - either user_name or user_id to load further data if needed (or both)
508 * - user_real_name
509 * - all other fields (email, password, etc.)
510 * It is useless to provide the remaining fields if either user_id,
511 * user_name and user_real_name are not provided because the whole row
512 * will be loaded once more from the database when accessing them.
514 * @param stdClass $row A row from the user table
515 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
516 * @return User
518 public static function newFromRow( $row, $data = null ) {
519 $user = new User;
520 $user->loadFromRow( $row, $data );
521 return $user;
524 //@}
527 * Get the username corresponding to a given user ID
528 * @param int $id User ID
529 * @return string|bool The corresponding username
531 public static function whoIs( $id ) {
532 return UserCache::singleton()->getProp( $id, 'name' );
536 * Get the real name of a user given their user ID
538 * @param int $id User ID
539 * @return string|bool The corresponding user's real name
541 public static function whoIsReal( $id ) {
542 return UserCache::singleton()->getProp( $id, 'real_name' );
546 * Get database id given a user name
547 * @param string $name Username
548 * @return int|null The corresponding user's ID, or null if user is nonexistent
550 public static function idFromName( $name ) {
551 $nt = Title::makeTitleSafe( NS_USER, $name );
552 if ( is_null( $nt ) ) {
553 // Illegal name
554 return null;
557 if ( isset( self::$idCacheByName[$name] ) ) {
558 return self::$idCacheByName[$name];
561 $dbr = wfGetDB( DB_SLAVE );
562 $s = $dbr->selectRow(
563 'user',
564 array( 'user_id' ),
565 array( 'user_name' => $nt->getText() ),
566 __METHOD__
569 if ( $s === false ) {
570 $result = null;
571 } else {
572 $result = $s->user_id;
575 self::$idCacheByName[$name] = $result;
577 if ( count( self::$idCacheByName ) > 1000 ) {
578 self::$idCacheByName = array();
581 return $result;
585 * Reset the cache used in idFromName(). For use in tests.
587 public static function resetIdByNameCache() {
588 self::$idCacheByName = array();
592 * Does the string match an anonymous IPv4 address?
594 * This function exists for username validation, in order to reject
595 * usernames which are similar in form to IP addresses. Strings such
596 * as 300.300.300.300 will return true because it looks like an IP
597 * address, despite not being strictly valid.
599 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
600 * address because the usemod software would "cloak" anonymous IP
601 * addresses like this, if we allowed accounts like this to be created
602 * new users could get the old edits of these anonymous users.
604 * @param string $name Name to match
605 * @return bool
607 public static function isIP( $name ) {
608 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
609 || IP::isIPv6( $name );
613 * Is the input a valid username?
615 * Checks if the input is a valid username, we don't want an empty string,
616 * an IP address, anything that contains slashes (would mess up subpages),
617 * is longer than the maximum allowed username size or doesn't begin with
618 * a capital letter.
620 * @param string $name Name to match
621 * @return bool
623 public static function isValidUserName( $name ) {
624 global $wgContLang, $wgMaxNameChars;
626 if ( $name == ''
627 || User::isIP( $name )
628 || strpos( $name, '/' ) !== false
629 || strlen( $name ) > $wgMaxNameChars
630 || $name != $wgContLang->ucfirst( $name ) ) {
631 wfDebugLog( 'username', __METHOD__ .
632 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
633 return false;
636 // Ensure that the name can't be misresolved as a different title,
637 // such as with extra namespace keys at the start.
638 $parsed = Title::newFromText( $name );
639 if ( is_null( $parsed )
640 || $parsed->getNamespace()
641 || strcmp( $name, $parsed->getPrefixedText() ) ) {
642 wfDebugLog( 'username', __METHOD__ .
643 ": '$name' invalid due to ambiguous prefixes" );
644 return false;
647 // Check an additional blacklist of troublemaker characters.
648 // Should these be merged into the title char list?
649 $unicodeBlacklist = '/[' .
650 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
651 '\x{00a0}' . # non-breaking space
652 '\x{2000}-\x{200f}' . # various whitespace
653 '\x{2028}-\x{202f}' . # breaks and control chars
654 '\x{3000}' . # ideographic space
655 '\x{e000}-\x{f8ff}' . # private use
656 ']/u';
657 if ( preg_match( $unicodeBlacklist, $name ) ) {
658 wfDebugLog( 'username', __METHOD__ .
659 ": '$name' invalid due to blacklisted characters" );
660 return false;
663 return true;
667 * Usernames which fail to pass this function will be blocked
668 * from user login and new account registrations, but may be used
669 * internally by batch processes.
671 * If an account already exists in this form, login will be blocked
672 * by a failure to pass this function.
674 * @param string $name Name to match
675 * @return bool
677 public static function isUsableName( $name ) {
678 global $wgReservedUsernames;
679 // Must be a valid username, obviously ;)
680 if ( !self::isValidUserName( $name ) ) {
681 return false;
684 static $reservedUsernames = false;
685 if ( !$reservedUsernames ) {
686 $reservedUsernames = $wgReservedUsernames;
687 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
690 // Certain names may be reserved for batch processes.
691 foreach ( $reservedUsernames as $reserved ) {
692 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
693 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
695 if ( $reserved == $name ) {
696 return false;
699 return true;
703 * Usernames which fail to pass this function will be blocked
704 * from new account registrations, but may be used internally
705 * either by batch processes or by user accounts which have
706 * already been created.
708 * Additional blacklisting may be added here rather than in
709 * isValidUserName() to avoid disrupting existing accounts.
711 * @param string $name String to match
712 * @return bool
714 public static function isCreatableName( $name ) {
715 global $wgInvalidUsernameCharacters;
717 // Ensure that the username isn't longer than 235 bytes, so that
718 // (at least for the builtin skins) user javascript and css files
719 // will work. (bug 23080)
720 if ( strlen( $name ) > 235 ) {
721 wfDebugLog( 'username', __METHOD__ .
722 ": '$name' invalid due to length" );
723 return false;
726 // Preg yells if you try to give it an empty string
727 if ( $wgInvalidUsernameCharacters !== '' ) {
728 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
729 wfDebugLog( 'username', __METHOD__ .
730 ": '$name' invalid due to wgInvalidUsernameCharacters" );
731 return false;
735 return self::isUsableName( $name );
739 * Is the input a valid password for this user?
741 * @param string $password Desired password
742 * @return bool
744 public function isValidPassword( $password ) {
745 //simple boolean wrapper for getPasswordValidity
746 return $this->getPasswordValidity( $password ) === true;
751 * Given unvalidated password input, return error message on failure.
753 * @param string $password Desired password
754 * @return bool|string|array true on success, string or array of error message on failure
756 public function getPasswordValidity( $password ) {
757 $result = $this->checkPasswordValidity( $password );
758 if ( $result->isGood() ) {
759 return true;
760 } else {
761 $messages = array();
762 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
763 $messages[] = $error['message'];
765 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
766 $messages[] = $warning['message'];
768 if ( count( $messages ) === 1 ) {
769 return $messages[0];
771 return $messages;
776 * Check if this is a valid password for this user. Status will be good if
777 * the password is valid, or have an array of error messages if not.
779 * @param string $password Desired password
780 * @return Status
781 * @since 1.23
783 public function checkPasswordValidity( $password ) {
784 global $wgMinimalPasswordLength, $wgContLang;
786 static $blockedLogins = array(
787 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
788 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
791 $status = Status::newGood();
793 $result = false; //init $result to false for the internal checks
795 if ( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) ) {
796 $status->error( $result );
797 return $status;
800 if ( $result === false ) {
801 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
802 $status->error( 'passwordtooshort', $wgMinimalPasswordLength );
803 return $status;
804 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName ) ) {
805 $status->error( 'password-name-match' );
806 return $status;
807 } elseif ( isset( $blockedLogins[$this->getName()] )
808 && $password == $blockedLogins[$this->getName()]
810 $status->error( 'password-login-forbidden' );
811 return $status;
812 } else {
813 //it seems weird returning a Good status here, but this is because of the
814 //initialization of $result to false above. If the hook is never run or it
815 //doesn't modify $result, then we will likely get down into this if with
816 //a valid password.
817 return $status;
819 } elseif ( $result === true ) {
820 return $status;
821 } else {
822 $status->error( $result );
823 return $status; //the isValidPassword hook set a string $result and returned true
828 * Expire a user's password
829 * @since 1.23
830 * @param int $ts Optional timestamp to convert, default 0 for the current time
832 public function expirePassword( $ts = 0 ) {
833 $this->load();
834 $timestamp = wfTimestamp( TS_MW, $ts );
835 $this->mPasswordExpires = $timestamp;
836 $this->saveSettings();
840 * Clear the password expiration for a user
841 * @since 1.23
842 * @param bool $load Ensure user object is loaded first
844 public function resetPasswordExpiration( $load = true ) {
845 global $wgPasswordExpirationDays;
846 if ( $load ) {
847 $this->load();
849 $newExpire = null;
850 if ( $wgPasswordExpirationDays ) {
851 $newExpire = wfTimestamp(
852 TS_MW,
853 time() + ( $wgPasswordExpirationDays * 24 * 3600 )
856 // Give extensions a chance to force an expiration
857 wfRunHooks( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
858 $this->mPasswordExpires = $newExpire;
862 * Check if the user's password is expired.
863 * TODO: Put this and password length into a PasswordPolicy object
864 * @since 1.23
865 * @return string|bool The expiration type, or false if not expired
866 * hard: A password change is required to login
867 * soft: Allow login, but encourage password change
868 * false: Password is not expired
870 public function getPasswordExpired() {
871 global $wgPasswordExpireGrace;
872 $expired = false;
873 $now = wfTimestamp();
874 $expiration = $this->getPasswordExpireDate();
875 $expUnix = wfTimestamp( TS_UNIX, $expiration );
876 if ( $expiration !== null && $expUnix < $now ) {
877 $expired = ( $expUnix + $wgPasswordExpireGrace < $now ) ? 'hard' : 'soft';
879 return $expired;
883 * Get this user's password expiration date. Since this may be using
884 * the cached User object, we assume that whatever mechanism is setting
885 * the expiration date is also expiring the User cache.
886 * @since 1.23
887 * @return string|bool The datestamp of the expiration, or null if not set
889 public function getPasswordExpireDate() {
890 $this->load();
891 return $this->mPasswordExpires;
895 * Does a string look like an e-mail address?
897 * This validates an email address using an HTML5 specification found at:
898 * http://www.whatwg.org/html/states-of-the-type-attribute.html#valid-e-mail-address
899 * Which as of 2011-01-24 says:
901 * A valid e-mail address is a string that matches the ABNF production
902 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
903 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
904 * 3.5.
906 * This function is an implementation of the specification as requested in
907 * bug 22449.
909 * Client-side forms will use the same standard validation rules via JS or
910 * HTML 5 validation; additional restrictions can be enforced server-side
911 * by extensions via the 'isValidEmailAddr' hook.
913 * Note that this validation doesn't 100% match RFC 2822, but is believed
914 * to be liberal enough for wide use. Some invalid addresses will still
915 * pass validation here.
917 * @param string $addr E-mail address
918 * @return bool
919 * @deprecated since 1.18 call Sanitizer::isValidEmail() directly
921 public static function isValidEmailAddr( $addr ) {
922 wfDeprecated( __METHOD__, '1.18' );
923 return Sanitizer::validateEmail( $addr );
927 * Given unvalidated user input, return a canonical username, or false if
928 * the username is invalid.
929 * @param string $name User input
930 * @param string|bool $validate Type of validation to use:
931 * - false No validation
932 * - 'valid' Valid for batch processes
933 * - 'usable' Valid for batch processes and login
934 * - 'creatable' Valid for batch processes, login and account creation
936 * @throws MWException
937 * @return bool|string
939 public static function getCanonicalName( $name, $validate = 'valid' ) {
940 // Force usernames to capital
941 global $wgContLang;
942 $name = $wgContLang->ucfirst( $name );
944 # Reject names containing '#'; these will be cleaned up
945 # with title normalisation, but then it's too late to
946 # check elsewhere
947 if ( strpos( $name, '#' ) !== false ) {
948 return false;
951 // Clean up name according to title rules
952 $t = ( $validate === 'valid' ) ?
953 Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
954 // Check for invalid titles
955 if ( is_null( $t ) ) {
956 return false;
959 // Reject various classes of invalid names
960 global $wgAuth;
961 $name = $wgAuth->getCanonicalName( $t->getText() );
963 switch ( $validate ) {
964 case false:
965 break;
966 case 'valid':
967 if ( !User::isValidUserName( $name ) ) {
968 $name = false;
970 break;
971 case 'usable':
972 if ( !User::isUsableName( $name ) ) {
973 $name = false;
975 break;
976 case 'creatable':
977 if ( !User::isCreatableName( $name ) ) {
978 $name = false;
980 break;
981 default:
982 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__ );
984 return $name;
988 * Count the number of edits of a user
990 * @param int $uid User ID to check
991 * @return int The user's edit count
993 * @deprecated since 1.21 in favour of User::getEditCount
995 public static function edits( $uid ) {
996 wfDeprecated( __METHOD__, '1.21' );
997 $user = self::newFromId( $uid );
998 return $user->getEditCount();
1002 * Return a random password.
1004 * @return string New random password
1006 public static function randomPassword() {
1007 global $wgMinimalPasswordLength;
1008 // Decide the final password length based on our min password length,
1009 // stopping at a minimum of 10 chars.
1010 $length = max( 10, $wgMinimalPasswordLength );
1011 // Multiply by 1.25 to get the number of hex characters we need
1012 $length = $length * 1.25;
1013 // Generate random hex chars
1014 $hex = MWCryptRand::generateHex( $length );
1015 // Convert from base 16 to base 32 to get a proper password like string
1016 return wfBaseConvert( $hex, 16, 32 );
1020 * Set cached properties to default.
1022 * @note This no longer clears uncached lazy-initialised properties;
1023 * the constructor does that instead.
1025 * @param string|bool $name
1027 public function loadDefaults( $name = false ) {
1028 wfProfileIn( __METHOD__ );
1030 $this->mId = 0;
1031 $this->mName = $name;
1032 $this->mRealName = '';
1033 $this->mPassword = $this->mNewpassword = '';
1034 $this->mNewpassTime = null;
1035 $this->mEmail = '';
1036 $this->mOptionOverrides = null;
1037 $this->mOptionsLoaded = false;
1039 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1040 if ( $loggedOut !== null ) {
1041 $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
1042 } else {
1043 $this->mTouched = '1'; # Allow any pages to be cached
1046 $this->mToken = null; // Don't run cryptographic functions till we need a token
1047 $this->mEmailAuthenticated = null;
1048 $this->mEmailToken = '';
1049 $this->mEmailTokenExpires = null;
1050 $this->mPasswordExpires = null;
1051 $this->resetPasswordExpiration( false );
1052 $this->mRegistration = wfTimestamp( TS_MW );
1053 $this->mGroups = array();
1055 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
1057 wfProfileOut( __METHOD__ );
1061 * Return whether an item has been loaded.
1063 * @param string $item Item to check. Current possibilities:
1064 * - id
1065 * - name
1066 * - realname
1067 * @param string $all 'all' to check if the whole object has been loaded
1068 * or any other string to check if only the item is available (e.g.
1069 * for optimisation)
1070 * @return bool
1072 public function isItemLoaded( $item, $all = 'all' ) {
1073 return ( $this->mLoadedItems === true && $all === 'all' ) ||
1074 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
1078 * Set that an item has been loaded
1080 * @param string $item
1082 protected function setItemLoaded( $item ) {
1083 if ( is_array( $this->mLoadedItems ) ) {
1084 $this->mLoadedItems[$item] = true;
1089 * Load user data from the session or login cookie.
1090 * @return bool True if the user is logged in, false otherwise.
1092 private function loadFromSession() {
1093 $result = null;
1094 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
1095 if ( $result !== null ) {
1096 return $result;
1099 $request = $this->getRequest();
1101 $cookieId = $request->getCookie( 'UserID' );
1102 $sessId = $request->getSessionData( 'wsUserID' );
1104 if ( $cookieId !== null ) {
1105 $sId = intval( $cookieId );
1106 if ( $sessId !== null && $cookieId != $sessId ) {
1107 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1108 cookie user ID ($sId) don't match!" );
1109 return false;
1111 $request->setSessionData( 'wsUserID', $sId );
1112 } elseif ( $sessId !== null && $sessId != 0 ) {
1113 $sId = $sessId;
1114 } else {
1115 return false;
1118 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1119 $sName = $request->getSessionData( 'wsUserName' );
1120 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1121 $sName = $request->getCookie( 'UserName' );
1122 $request->setSessionData( 'wsUserName', $sName );
1123 } else {
1124 return false;
1127 $proposedUser = User::newFromId( $sId );
1128 if ( !$proposedUser->isLoggedIn() ) {
1129 // Not a valid ID
1130 return false;
1133 global $wgBlockDisablesLogin;
1134 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1135 // User blocked and we've disabled blocked user logins
1136 return false;
1139 if ( $request->getSessionData( 'wsToken' ) ) {
1140 $passwordCorrect =
1141 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1142 $from = 'session';
1143 } elseif ( $request->getCookie( 'Token' ) ) {
1144 # Get the token from DB/cache and clean it up to remove garbage padding.
1145 # This deals with historical problems with bugs and the default column value.
1146 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1147 // Make comparison in constant time (bug 61346)
1148 $passwordCorrect = strlen( $token )
1149 && hash_equals( $token, $request->getCookie( 'Token' ) );
1150 $from = 'cookie';
1151 } else {
1152 // No session or persistent login cookie
1153 return false;
1156 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1157 $this->loadFromUserObject( $proposedUser );
1158 $request->setSessionData( 'wsToken', $this->mToken );
1159 wfDebug( "User: logged in from $from\n" );
1160 return true;
1161 } else {
1162 // Invalid credentials
1163 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1164 return false;
1169 * Load user and user_group data from the database.
1170 * $this->mId must be set, this is how the user is identified.
1172 * @return bool True if the user exists, false if the user is anonymous
1174 public function loadFromDatabase() {
1175 // Paranoia
1176 $this->mId = intval( $this->mId );
1178 // Anonymous user
1179 if ( !$this->mId ) {
1180 $this->loadDefaults();
1181 return false;
1184 $dbr = wfGetDB( DB_MASTER );
1185 $s = $dbr->selectRow(
1186 'user',
1187 self::selectFields(),
1188 array( 'user_id' => $this->mId ),
1189 __METHOD__
1192 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1194 if ( $s !== false ) {
1195 // Initialise user table data
1196 $this->loadFromRow( $s );
1197 $this->mGroups = null; // deferred
1198 $this->getEditCount(); // revalidation for nulls
1199 return true;
1200 } else {
1201 // Invalid user_id
1202 $this->mId = 0;
1203 $this->loadDefaults();
1204 return false;
1209 * Initialize this object from a row from the user table.
1211 * @param stdClass $row Row from the user table to load.
1212 * @param array $data Further user data to load into the object
1214 * user_groups Array with groups out of the user_groups table
1215 * user_properties Array with properties out of the user_properties table
1217 public function loadFromRow( $row, $data = null ) {
1218 $all = true;
1220 $this->mGroups = null; // deferred
1222 if ( isset( $row->user_name ) ) {
1223 $this->mName = $row->user_name;
1224 $this->mFrom = 'name';
1225 $this->setItemLoaded( 'name' );
1226 } else {
1227 $all = false;
1230 if ( isset( $row->user_real_name ) ) {
1231 $this->mRealName = $row->user_real_name;
1232 $this->setItemLoaded( 'realname' );
1233 } else {
1234 $all = false;
1237 if ( isset( $row->user_id ) ) {
1238 $this->mId = intval( $row->user_id );
1239 $this->mFrom = 'id';
1240 $this->setItemLoaded( 'id' );
1241 } else {
1242 $all = false;
1245 if ( isset( $row->user_editcount ) ) {
1246 $this->mEditCount = $row->user_editcount;
1247 } else {
1248 $all = false;
1251 if ( isset( $row->user_password ) ) {
1252 $this->mPassword = $row->user_password;
1253 $this->mNewpassword = $row->user_newpassword;
1254 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
1255 $this->mEmail = $row->user_email;
1256 $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1257 $this->mToken = $row->user_token;
1258 if ( $this->mToken == '' ) {
1259 $this->mToken = null;
1261 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1262 $this->mEmailToken = $row->user_email_token;
1263 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1264 $this->mPasswordExpires = wfTimestampOrNull( TS_MW, $row->user_password_expires );
1265 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1266 } else {
1267 $all = false;
1270 if ( $all ) {
1271 $this->mLoadedItems = true;
1274 if ( is_array( $data ) ) {
1275 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1276 $this->mGroups = $data['user_groups'];
1278 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1279 $this->loadOptions( $data['user_properties'] );
1285 * Load the data for this user object from another user object.
1287 * @param User $user
1289 protected function loadFromUserObject( $user ) {
1290 $user->load();
1291 $user->loadGroups();
1292 $user->loadOptions();
1293 foreach ( self::$mCacheVars as $var ) {
1294 $this->$var = $user->$var;
1299 * Load the groups from the database if they aren't already loaded.
1301 private function loadGroups() {
1302 if ( is_null( $this->mGroups ) ) {
1303 $dbr = wfGetDB( DB_MASTER );
1304 $res = $dbr->select( 'user_groups',
1305 array( 'ug_group' ),
1306 array( 'ug_user' => $this->mId ),
1307 __METHOD__ );
1308 $this->mGroups = array();
1309 foreach ( $res as $row ) {
1310 $this->mGroups[] = $row->ug_group;
1316 * Add the user to the group if he/she meets given criteria.
1318 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1319 * possible to remove manually via Special:UserRights. In such case it
1320 * will not be re-added automatically. The user will also not lose the
1321 * group if they no longer meet the criteria.
1323 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1325 * @return array Array of groups the user has been promoted to.
1327 * @see $wgAutopromoteOnce
1329 public function addAutopromoteOnceGroups( $event ) {
1330 global $wgAutopromoteOnceLogInRC, $wgAuth;
1332 $toPromote = array();
1333 if ( $this->getId() ) {
1334 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1335 if ( count( $toPromote ) ) {
1336 $oldGroups = $this->getGroups(); // previous groups
1338 foreach ( $toPromote as $group ) {
1339 $this->addGroup( $group );
1341 // update groups in external authentication database
1342 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1344 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1346 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1347 $logEntry->setPerformer( $this );
1348 $logEntry->setTarget( $this->getUserPage() );
1349 $logEntry->setParameters( array(
1350 '4::oldgroups' => $oldGroups,
1351 '5::newgroups' => $newGroups,
1352 ) );
1353 $logid = $logEntry->insert();
1354 if ( $wgAutopromoteOnceLogInRC ) {
1355 $logEntry->publish( $logid );
1359 return $toPromote;
1363 * Clear various cached data stored in this object. The cache of the user table
1364 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1366 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1367 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1369 public function clearInstanceCache( $reloadFrom = false ) {
1370 $this->mNewtalk = -1;
1371 $this->mDatePreference = null;
1372 $this->mBlockedby = -1; # Unset
1373 $this->mHash = false;
1374 $this->mRights = null;
1375 $this->mEffectiveGroups = null;
1376 $this->mImplicitGroups = null;
1377 $this->mGroups = null;
1378 $this->mOptions = null;
1379 $this->mOptionsLoaded = false;
1380 $this->mEditCount = null;
1382 if ( $reloadFrom ) {
1383 $this->mLoadedItems = array();
1384 $this->mFrom = $reloadFrom;
1389 * Combine the language default options with any site-specific options
1390 * and add the default language variants.
1392 * @return array Array of String options
1394 public static function getDefaultOptions() {
1395 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1397 static $defOpt = null;
1398 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1399 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1400 // mid-request and see that change reflected in the return value of this function.
1401 // Which is insane and would never happen during normal MW operation
1402 return $defOpt;
1405 $defOpt = $wgDefaultUserOptions;
1406 // Default language setting
1407 $defOpt['language'] = $wgContLang->getCode();
1408 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
1409 $defOpt[$langCode == $wgContLang->getCode() ? 'variant' : "variant-$langCode"] = $langCode;
1411 foreach ( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1412 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1414 $defOpt['skin'] = $wgDefaultSkin;
1416 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1418 return $defOpt;
1422 * Get a given default option value.
1424 * @param string $opt Name of option to retrieve
1425 * @return string Default option value
1427 public static function getDefaultOption( $opt ) {
1428 $defOpts = self::getDefaultOptions();
1429 if ( isset( $defOpts[$opt] ) ) {
1430 return $defOpts[$opt];
1431 } else {
1432 return null;
1437 * Get blocking information
1438 * @param bool $bFromSlave Whether to check the slave database first.
1439 * To improve performance, non-critical checks are done against slaves.
1440 * Check when actually saving should be done against master.
1442 private function getBlockedStatus( $bFromSlave = true ) {
1443 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1445 if ( -1 != $this->mBlockedby ) {
1446 return;
1449 wfProfileIn( __METHOD__ );
1450 wfDebug( __METHOD__ . ": checking...\n" );
1452 // Initialize data...
1453 // Otherwise something ends up stomping on $this->mBlockedby when
1454 // things get lazy-loaded later, causing false positive block hits
1455 // due to -1 !== 0. Probably session-related... Nothing should be
1456 // overwriting mBlockedby, surely?
1457 $this->load();
1459 # We only need to worry about passing the IP address to the Block generator if the
1460 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1461 # know which IP address they're actually coming from
1462 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1463 $ip = $this->getRequest()->getIP();
1464 } else {
1465 $ip = null;
1468 // User/IP blocking
1469 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1471 // Proxy blocking
1472 if ( !$block instanceof Block && $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1473 && !in_array( $ip, $wgProxyWhitelist )
1475 // Local list
1476 if ( self::isLocallyBlockedProxy( $ip ) ) {
1477 $block = new Block;
1478 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1479 $block->mReason = wfMessage( 'proxyblockreason' )->text();
1480 $block->setTarget( $ip );
1481 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1482 $block = new Block;
1483 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1484 $block->mReason = wfMessage( 'sorbsreason' )->text();
1485 $block->setTarget( $ip );
1489 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1490 if ( !$block instanceof Block
1491 && $wgApplyIpBlocksToXff
1492 && $ip !== null
1493 && !$this->isAllowed( 'proxyunbannable' )
1494 && !in_array( $ip, $wgProxyWhitelist )
1496 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1497 $xff = array_map( 'trim', explode( ',', $xff ) );
1498 $xff = array_diff( $xff, array( $ip ) );
1499 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1500 $block = Block::chooseBlock( $xffblocks, $xff );
1501 if ( $block instanceof Block ) {
1502 # Mangle the reason to alert the user that the block
1503 # originated from matching the X-Forwarded-For header.
1504 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->text();
1508 if ( $block instanceof Block ) {
1509 wfDebug( __METHOD__ . ": Found block.\n" );
1510 $this->mBlock = $block;
1511 $this->mBlockedby = $block->getByName();
1512 $this->mBlockreason = $block->mReason;
1513 $this->mHideName = $block->mHideName;
1514 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1515 } else {
1516 $this->mBlockedby = '';
1517 $this->mHideName = 0;
1518 $this->mAllowUsertalk = false;
1521 // Extensions
1522 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1524 wfProfileOut( __METHOD__ );
1528 * Whether the given IP is in a DNS blacklist.
1530 * @param string $ip IP to check
1531 * @param bool $checkWhitelist Whether to check the whitelist first
1532 * @return bool True if blacklisted.
1534 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1535 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1536 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1538 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs ) {
1539 return false;
1542 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1543 return false;
1546 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1547 return $this->inDnsBlacklist( $ip, $urls );
1551 * Whether the given IP is in a given DNS blacklist.
1553 * @param string $ip IP to check
1554 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1555 * @return bool True if blacklisted.
1557 public function inDnsBlacklist( $ip, $bases ) {
1558 wfProfileIn( __METHOD__ );
1560 $found = false;
1561 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1562 if ( IP::isIPv4( $ip ) ) {
1563 // Reverse IP, bug 21255
1564 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1566 foreach ( (array)$bases as $base ) {
1567 // Make hostname
1568 // If we have an access key, use that too (ProjectHoneypot, etc.)
1569 if ( is_array( $base ) ) {
1570 if ( count( $base ) >= 2 ) {
1571 // Access key is 1, base URL is 0
1572 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1573 } else {
1574 $host = "$ipReversed.{$base[0]}";
1576 } else {
1577 $host = "$ipReversed.$base";
1580 // Send query
1581 $ipList = gethostbynamel( $host );
1583 if ( $ipList ) {
1584 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1585 $found = true;
1586 break;
1587 } else {
1588 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1593 wfProfileOut( __METHOD__ );
1594 return $found;
1598 * Check if an IP address is in the local proxy list
1600 * @param string $ip
1602 * @return bool
1604 public static function isLocallyBlockedProxy( $ip ) {
1605 global $wgProxyList;
1607 if ( !$wgProxyList ) {
1608 return false;
1610 wfProfileIn( __METHOD__ );
1612 if ( !is_array( $wgProxyList ) ) {
1613 // Load from the specified file
1614 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1617 if ( !is_array( $wgProxyList ) ) {
1618 $ret = false;
1619 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1620 $ret = true;
1621 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1622 // Old-style flipped proxy list
1623 $ret = true;
1624 } else {
1625 $ret = false;
1627 wfProfileOut( __METHOD__ );
1628 return $ret;
1632 * Is this user subject to rate limiting?
1634 * @return bool True if rate limited
1636 public function isPingLimitable() {
1637 global $wgRateLimitsExcludedIPs;
1638 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1639 // No other good way currently to disable rate limits
1640 // for specific IPs. :P
1641 // But this is a crappy hack and should die.
1642 return false;
1644 return !$this->isAllowed( 'noratelimit' );
1648 * Primitive rate limits: enforce maximum actions per time period
1649 * to put a brake on flooding.
1651 * The method generates both a generic profiling point and a per action one
1652 * (suffix being "-$action".
1654 * @note When using a shared cache like memcached, IP-address
1655 * last-hit counters will be shared across wikis.
1657 * @param string $action Action to enforce; 'edit' if unspecified
1658 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1659 * @return bool True if a rate limiter was tripped
1661 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1662 // Call the 'PingLimiter' hook
1663 $result = false;
1664 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1665 return $result;
1668 global $wgRateLimits;
1669 if ( !isset( $wgRateLimits[$action] ) ) {
1670 return false;
1673 // Some groups shouldn't trigger the ping limiter, ever
1674 if ( !$this->isPingLimitable() ) {
1675 return false;
1678 global $wgMemc;
1679 wfProfileIn( __METHOD__ );
1680 wfProfileIn( __METHOD__ . '-' . $action );
1682 $limits = $wgRateLimits[$action];
1683 $keys = array();
1684 $id = $this->getId();
1685 $userLimit = false;
1687 if ( isset( $limits['anon'] ) && $id == 0 ) {
1688 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1691 if ( isset( $limits['user'] ) && $id != 0 ) {
1692 $userLimit = $limits['user'];
1694 if ( $this->isNewbie() ) {
1695 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1696 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1698 if ( isset( $limits['ip'] ) ) {
1699 $ip = $this->getRequest()->getIP();
1700 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1702 if ( isset( $limits['subnet'] ) ) {
1703 $ip = $this->getRequest()->getIP();
1704 $matches = array();
1705 $subnet = false;
1706 if ( IP::isIPv6( $ip ) ) {
1707 $parts = IP::parseRange( "$ip/64" );
1708 $subnet = $parts[0];
1709 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1710 // IPv4
1711 $subnet = $matches[1];
1713 if ( $subnet !== false ) {
1714 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1718 // Check for group-specific permissions
1719 // If more than one group applies, use the group with the highest limit
1720 foreach ( $this->getGroups() as $group ) {
1721 if ( isset( $limits[$group] ) ) {
1722 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1723 $userLimit = $limits[$group];
1727 // Set the user limit key
1728 if ( $userLimit !== false ) {
1729 list( $max, $period ) = $userLimit;
1730 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
1731 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1734 $triggered = false;
1735 foreach ( $keys as $key => $limit ) {
1736 list( $max, $period ) = $limit;
1737 $summary = "(limit $max in {$period}s)";
1738 $count = $wgMemc->get( $key );
1739 // Already pinged?
1740 if ( $count ) {
1741 if ( $count >= $max ) {
1742 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1743 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1744 $triggered = true;
1745 } else {
1746 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1748 } else {
1749 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1750 if ( $incrBy > 0 ) {
1751 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1754 if ( $incrBy > 0 ) {
1755 $wgMemc->incr( $key, $incrBy );
1759 wfProfileOut( __METHOD__ . '-' . $action );
1760 wfProfileOut( __METHOD__ );
1761 return $triggered;
1765 * Check if user is blocked
1767 * @param bool $bFromSlave Whether to check the slave database instead of
1768 * the master. Hacked from false due to horrible probs on site.
1769 * @return bool True if blocked, false otherwise
1771 public function isBlocked( $bFromSlave = true ) {
1772 return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
1776 * Get the block affecting the user, or null if the user is not blocked
1778 * @param bool $bFromSlave Whether to check the slave database instead of the master
1779 * @return Block|null
1781 public function getBlock( $bFromSlave = true ) {
1782 $this->getBlockedStatus( $bFromSlave );
1783 return $this->mBlock instanceof Block ? $this->mBlock : null;
1787 * Check if user is blocked from editing a particular article
1789 * @param Title $title Title to check
1790 * @param bool $bFromSlave Whether to check the slave database instead of the master
1791 * @return bool
1793 public function isBlockedFrom( $title, $bFromSlave = false ) {
1794 global $wgBlockAllowsUTEdit;
1795 wfProfileIn( __METHOD__ );
1797 $blocked = $this->isBlocked( $bFromSlave );
1798 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1799 // If a user's name is suppressed, they cannot make edits anywhere
1800 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName()
1801 && $title->getNamespace() == NS_USER_TALK ) {
1802 $blocked = false;
1803 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1806 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1808 wfProfileOut( __METHOD__ );
1809 return $blocked;
1813 * If user is blocked, return the name of the user who placed the block
1814 * @return string Name of blocker
1816 public function blockedBy() {
1817 $this->getBlockedStatus();
1818 return $this->mBlockedby;
1822 * If user is blocked, return the specified reason for the block
1823 * @return string Blocking reason
1825 public function blockedFor() {
1826 $this->getBlockedStatus();
1827 return $this->mBlockreason;
1831 * If user is blocked, return the ID for the block
1832 * @return int Block ID
1834 public function getBlockId() {
1835 $this->getBlockedStatus();
1836 return ( $this->mBlock ? $this->mBlock->getId() : false );
1840 * Check if user is blocked on all wikis.
1841 * Do not use for actual edit permission checks!
1842 * This is intended for quick UI checks.
1844 * @param string $ip IP address, uses current client if none given
1845 * @return bool True if blocked, false otherwise
1847 public function isBlockedGlobally( $ip = '' ) {
1848 if ( $this->mBlockedGlobally !== null ) {
1849 return $this->mBlockedGlobally;
1851 // User is already an IP?
1852 if ( IP::isIPAddress( $this->getName() ) ) {
1853 $ip = $this->getName();
1854 } elseif ( !$ip ) {
1855 $ip = $this->getRequest()->getIP();
1857 $blocked = false;
1858 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1859 $this->mBlockedGlobally = (bool)$blocked;
1860 return $this->mBlockedGlobally;
1864 * Check if user account is locked
1866 * @return bool True if locked, false otherwise
1868 public function isLocked() {
1869 if ( $this->mLocked !== null ) {
1870 return $this->mLocked;
1872 global $wgAuth;
1873 StubObject::unstub( $wgAuth );
1874 $authUser = $wgAuth->getUserInstance( $this );
1875 $this->mLocked = (bool)$authUser->isLocked();
1876 return $this->mLocked;
1880 * Check if user account is hidden
1882 * @return bool True if hidden, false otherwise
1884 public function isHidden() {
1885 if ( $this->mHideName !== null ) {
1886 return $this->mHideName;
1888 $this->getBlockedStatus();
1889 if ( !$this->mHideName ) {
1890 global $wgAuth;
1891 StubObject::unstub( $wgAuth );
1892 $authUser = $wgAuth->getUserInstance( $this );
1893 $this->mHideName = (bool)$authUser->isHidden();
1895 return $this->mHideName;
1899 * Get the user's ID.
1900 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1902 public function getId() {
1903 if ( $this->mId === null && $this->mName !== null && User::isIP( $this->mName ) ) {
1904 // Special case, we know the user is anonymous
1905 return 0;
1906 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1907 // Don't load if this was initialized from an ID
1908 $this->load();
1910 return $this->mId;
1914 * Set the user and reload all fields according to a given ID
1915 * @param int $v User ID to reload
1917 public function setId( $v ) {
1918 $this->mId = $v;
1919 $this->clearInstanceCache( 'id' );
1923 * Get the user name, or the IP of an anonymous user
1924 * @return string User's name or IP address
1926 public function getName() {
1927 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1928 // Special case optimisation
1929 return $this->mName;
1930 } else {
1931 $this->load();
1932 if ( $this->mName === false ) {
1933 // Clean up IPs
1934 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
1936 return $this->mName;
1941 * Set the user name.
1943 * This does not reload fields from the database according to the given
1944 * name. Rather, it is used to create a temporary "nonexistent user" for
1945 * later addition to the database. It can also be used to set the IP
1946 * address for an anonymous user to something other than the current
1947 * remote IP.
1949 * @note User::newFromName() has roughly the same function, when the named user
1950 * does not exist.
1951 * @param string $str New user name to set
1953 public function setName( $str ) {
1954 $this->load();
1955 $this->mName = $str;
1959 * Get the user's name escaped by underscores.
1960 * @return string Username escaped by underscores.
1962 public function getTitleKey() {
1963 return str_replace( ' ', '_', $this->getName() );
1967 * Check if the user has new messages.
1968 * @return bool True if the user has new messages
1970 public function getNewtalk() {
1971 $this->load();
1973 // Load the newtalk status if it is unloaded (mNewtalk=-1)
1974 if ( $this->mNewtalk === -1 ) {
1975 $this->mNewtalk = false; # reset talk page status
1977 // Check memcached separately for anons, who have no
1978 // entire User object stored in there.
1979 if ( !$this->mId ) {
1980 global $wgDisableAnonTalk;
1981 if ( $wgDisableAnonTalk ) {
1982 // Anon newtalk disabled by configuration.
1983 $this->mNewtalk = false;
1984 } else {
1985 global $wgMemc;
1986 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1987 $newtalk = $wgMemc->get( $key );
1988 if ( strval( $newtalk ) !== '' ) {
1989 $this->mNewtalk = (bool)$newtalk;
1990 } else {
1991 // Since we are caching this, make sure it is up to date by getting it
1992 // from the master
1993 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1994 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1997 } else {
1998 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
2002 return (bool)$this->mNewtalk;
2006 * Return the data needed to construct links for new talk page message
2007 * alerts. If there are new messages, this will return an associative array
2008 * with the following data:
2009 * wiki: The database name of the wiki
2010 * link: Root-relative link to the user's talk page
2011 * rev: The last talk page revision that the user has seen or null. This
2012 * is useful for building diff links.
2013 * If there are no new messages, it returns an empty array.
2014 * @note This function was designed to accomodate multiple talk pages, but
2015 * currently only returns a single link and revision.
2016 * @return array
2018 public function getNewMessageLinks() {
2019 $talks = array();
2020 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2021 return $talks;
2022 } elseif ( !$this->getNewtalk() ) {
2023 return array();
2025 $utp = $this->getTalkPage();
2026 $dbr = wfGetDB( DB_SLAVE );
2027 // Get the "last viewed rev" timestamp from the oldest message notification
2028 $timestamp = $dbr->selectField( 'user_newtalk',
2029 'MIN(user_last_timestamp)',
2030 $this->isAnon() ? array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2031 __METHOD__ );
2032 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2033 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2037 * Get the revision ID for the last talk page revision viewed by the talk
2038 * page owner.
2039 * @return int|null Revision ID or null
2041 public function getNewMessageRevisionId() {
2042 $newMessageRevisionId = null;
2043 $newMessageLinks = $this->getNewMessageLinks();
2044 if ( $newMessageLinks ) {
2045 // Note: getNewMessageLinks() never returns more than a single link
2046 // and it is always for the same wiki, but we double-check here in
2047 // case that changes some time in the future.
2048 if ( count( $newMessageLinks ) === 1
2049 && $newMessageLinks[0]['wiki'] === wfWikiID()
2050 && $newMessageLinks[0]['rev']
2052 $newMessageRevision = $newMessageLinks[0]['rev'];
2053 $newMessageRevisionId = $newMessageRevision->getId();
2056 return $newMessageRevisionId;
2060 * Internal uncached check for new messages
2062 * @see getNewtalk()
2063 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2064 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2065 * @param bool $fromMaster true to fetch from the master, false for a slave
2066 * @return bool True if the user has new messages
2068 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
2069 if ( $fromMaster ) {
2070 $db = wfGetDB( DB_MASTER );
2071 } else {
2072 $db = wfGetDB( DB_SLAVE );
2074 $ok = $db->selectField( 'user_newtalk', $field,
2075 array( $field => $id ), __METHOD__ );
2076 return $ok !== false;
2080 * Add or update the new messages flag
2081 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2082 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2083 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2084 * @return bool True if successful, false otherwise
2086 protected function updateNewtalk( $field, $id, $curRev = null ) {
2087 // Get timestamp of the talk page revision prior to the current one
2088 $prevRev = $curRev ? $curRev->getPrevious() : false;
2089 $ts = $prevRev ? $prevRev->getTimestamp() : null;
2090 // Mark the user as having new messages since this revision
2091 $dbw = wfGetDB( DB_MASTER );
2092 $dbw->insert( 'user_newtalk',
2093 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2094 __METHOD__,
2095 'IGNORE' );
2096 if ( $dbw->affectedRows() ) {
2097 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
2098 return true;
2099 } else {
2100 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
2101 return false;
2106 * Clear the new messages flag for the given user
2107 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2108 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2109 * @return bool True if successful, false otherwise
2111 protected function deleteNewtalk( $field, $id ) {
2112 $dbw = wfGetDB( DB_MASTER );
2113 $dbw->delete( 'user_newtalk',
2114 array( $field => $id ),
2115 __METHOD__ );
2116 if ( $dbw->affectedRows() ) {
2117 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
2118 return true;
2119 } else {
2120 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
2121 return false;
2126 * Update the 'You have new messages!' status.
2127 * @param bool $val Whether the user has new messages
2128 * @param Revision $curRev New, as yet unseen revision of the user talk
2129 * page. Ignored if null or !$val.
2131 public function setNewtalk( $val, $curRev = null ) {
2132 if ( wfReadOnly() ) {
2133 return;
2136 $this->load();
2137 $this->mNewtalk = $val;
2139 if ( $this->isAnon() ) {
2140 $field = 'user_ip';
2141 $id = $this->getName();
2142 } else {
2143 $field = 'user_id';
2144 $id = $this->getId();
2146 global $wgMemc;
2148 if ( $val ) {
2149 $changed = $this->updateNewtalk( $field, $id, $curRev );
2150 } else {
2151 $changed = $this->deleteNewtalk( $field, $id );
2154 if ( $this->isAnon() ) {
2155 // Anons have a separate memcached space, since
2156 // user records aren't kept for them.
2157 $key = wfMemcKey( 'newtalk', 'ip', $id );
2158 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
2160 if ( $changed ) {
2161 $this->invalidateCache();
2166 * Generate a current or new-future timestamp to be stored in the
2167 * user_touched field when we update things.
2168 * @return string Timestamp in TS_MW format
2170 private static function newTouchedTimestamp() {
2171 global $wgClockSkewFudge;
2172 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
2176 * Clear user data from memcached.
2177 * Use after applying fun updates to the database; caller's
2178 * responsibility to update user_touched if appropriate.
2180 * Called implicitly from invalidateCache() and saveSettings().
2182 private function clearSharedCache() {
2183 $this->load();
2184 if ( $this->mId ) {
2185 global $wgMemc;
2186 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
2191 * Immediately touch the user data cache for this account.
2192 * Updates user_touched field, and removes account data from memcached
2193 * for reload on the next hit.
2195 public function invalidateCache() {
2196 if ( wfReadOnly() ) {
2197 return;
2199 $this->load();
2200 if ( $this->mId ) {
2201 $this->mTouched = self::newTouchedTimestamp();
2203 $dbw = wfGetDB( DB_MASTER );
2204 $userid = $this->mId;
2205 $touched = $this->mTouched;
2206 $method = __METHOD__;
2207 $dbw->onTransactionIdle( function() use ( $dbw, $userid, $touched, $method ) {
2208 // Prevent contention slams by checking user_touched first
2209 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2210 $needsPurge = $dbw->selectField( 'user', '1',
2211 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2212 if ( $needsPurge ) {
2213 $dbw->update( 'user',
2214 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2215 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2216 $method
2219 } );
2220 $this->clearSharedCache();
2225 * Validate the cache for this account.
2226 * @param string $timestamp A timestamp in TS_MW format
2227 * @return bool
2229 public function validateCache( $timestamp ) {
2230 $this->load();
2231 return ( $timestamp >= $this->mTouched );
2235 * Get the user touched timestamp
2236 * @return string Timestamp
2238 public function getTouched() {
2239 $this->load();
2240 return $this->mTouched;
2244 * Set the password and reset the random token.
2245 * Calls through to authentication plugin if necessary;
2246 * will have no effect if the auth plugin refuses to
2247 * pass the change through or if the legal password
2248 * checks fail.
2250 * As a special case, setting the password to null
2251 * wipes it, so the account cannot be logged in until
2252 * a new password is set, for instance via e-mail.
2254 * @param string $str New password to set
2255 * @throws PasswordError on failure
2257 * @return bool
2259 public function setPassword( $str ) {
2260 global $wgAuth;
2262 if ( $str !== null ) {
2263 if ( !$wgAuth->allowPasswordChange() ) {
2264 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2267 if ( !$this->isValidPassword( $str ) ) {
2268 global $wgMinimalPasswordLength;
2269 $valid = $this->getPasswordValidity( $str );
2270 if ( is_array( $valid ) ) {
2271 $message = array_shift( $valid );
2272 $params = $valid;
2273 } else {
2274 $message = $valid;
2275 $params = array( $wgMinimalPasswordLength );
2277 throw new PasswordError( wfMessage( $message, $params )->text() );
2281 if ( !$wgAuth->setPassword( $this, $str ) ) {
2282 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2285 $this->setInternalPassword( $str );
2287 return true;
2291 * Set the password and reset the random token unconditionally.
2293 * @param string|null $str New password to set or null to set an invalid
2294 * password hash meaning that the user will not be able to log in
2295 * through the web interface.
2297 public function setInternalPassword( $str ) {
2298 $this->load();
2299 $this->setToken();
2301 if ( $str === null ) {
2302 // Save an invalid hash...
2303 $this->mPassword = '';
2304 } else {
2305 $this->mPassword = self::crypt( $str );
2307 $this->mNewpassword = '';
2308 $this->mNewpassTime = null;
2312 * Get the user's current token.
2313 * @param bool $forceCreation Force the generation of a new token if the
2314 * user doesn't have one (default=true for backwards compatibility).
2315 * @return string Token
2317 public function getToken( $forceCreation = true ) {
2318 $this->load();
2319 if ( !$this->mToken && $forceCreation ) {
2320 $this->setToken();
2322 return $this->mToken;
2326 * Set the random token (used for persistent authentication)
2327 * Called from loadDefaults() among other places.
2329 * @param string|bool $token If specified, set the token to this value
2331 public function setToken( $token = false ) {
2332 $this->load();
2333 if ( !$token ) {
2334 $this->mToken = MWCryptRand::generateHex( USER_TOKEN_LENGTH );
2335 } else {
2336 $this->mToken = $token;
2341 * Set the password for a password reminder or new account email
2343 * @param string $str New password to set or null to set an invalid
2344 * password hash meaning that the user will not be able to use it
2345 * @param bool $throttle If true, reset the throttle timestamp to the present
2347 public function setNewpassword( $str, $throttle = true ) {
2348 $this->load();
2350 if ( $str === null ) {
2351 $this->mNewpassword = '';
2352 $this->mNewpassTime = null;
2353 } else {
2354 $this->mNewpassword = self::crypt( $str );
2355 if ( $throttle ) {
2356 $this->mNewpassTime = wfTimestampNow();
2362 * Has password reminder email been sent within the last
2363 * $wgPasswordReminderResendTime hours?
2364 * @return bool
2366 public function isPasswordReminderThrottled() {
2367 global $wgPasswordReminderResendTime;
2368 $this->load();
2369 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
2370 return false;
2372 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
2373 return time() < $expiry;
2377 * Get the user's e-mail address
2378 * @return string User's email address
2380 public function getEmail() {
2381 $this->load();
2382 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
2383 return $this->mEmail;
2387 * Get the timestamp of the user's e-mail authentication
2388 * @return string TS_MW timestamp
2390 public function getEmailAuthenticationTimestamp() {
2391 $this->load();
2392 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2393 return $this->mEmailAuthenticated;
2397 * Set the user's e-mail address
2398 * @param string $str New e-mail address
2400 public function setEmail( $str ) {
2401 $this->load();
2402 if ( $str == $this->mEmail ) {
2403 return;
2405 $this->mEmail = $str;
2406 $this->invalidateEmail();
2407 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
2411 * Set the user's e-mail address and a confirmation mail if needed.
2413 * @since 1.20
2414 * @param string $str New e-mail address
2415 * @return Status
2417 public function setEmailWithConfirmation( $str ) {
2418 global $wgEnableEmail, $wgEmailAuthentication;
2420 if ( !$wgEnableEmail ) {
2421 return Status::newFatal( 'emaildisabled' );
2424 $oldaddr = $this->getEmail();
2425 if ( $str === $oldaddr ) {
2426 return Status::newGood( true );
2429 $this->setEmail( $str );
2431 if ( $str !== '' && $wgEmailAuthentication ) {
2432 // Send a confirmation request to the new address if needed
2433 $type = $oldaddr != '' ? 'changed' : 'set';
2434 $result = $this->sendConfirmationMail( $type );
2435 if ( $result->isGood() ) {
2436 // Say the the caller that a confirmation mail has been sent
2437 $result->value = 'eauth';
2439 } else {
2440 $result = Status::newGood( true );
2443 return $result;
2447 * Get the user's real name
2448 * @return string User's real name
2450 public function getRealName() {
2451 if ( !$this->isItemLoaded( 'realname' ) ) {
2452 $this->load();
2455 return $this->mRealName;
2459 * Set the user's real name
2460 * @param string $str New real name
2462 public function setRealName( $str ) {
2463 $this->load();
2464 $this->mRealName = $str;
2468 * Get the user's current setting for a given option.
2470 * @param string $oname The option to check
2471 * @param string $defaultOverride A default value returned if the option does not exist
2472 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2473 * @return string User's current value for the option
2474 * @see getBoolOption()
2475 * @see getIntOption()
2477 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2478 global $wgHiddenPrefs;
2479 $this->loadOptions();
2481 # We want 'disabled' preferences to always behave as the default value for
2482 # users, even if they have set the option explicitly in their settings (ie they
2483 # set it, and then it was disabled removing their ability to change it). But
2484 # we don't want to erase the preferences in the database in case the preference
2485 # is re-enabled again. So don't touch $mOptions, just override the returned value
2486 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2487 return self::getDefaultOption( $oname );
2490 if ( array_key_exists( $oname, $this->mOptions ) ) {
2491 return $this->mOptions[$oname];
2492 } else {
2493 return $defaultOverride;
2498 * Get all user's options
2500 * @return array
2502 public function getOptions() {
2503 global $wgHiddenPrefs;
2504 $this->loadOptions();
2505 $options = $this->mOptions;
2507 # We want 'disabled' preferences to always behave as the default value for
2508 # users, even if they have set the option explicitly in their settings (ie they
2509 # set it, and then it was disabled removing their ability to change it). But
2510 # we don't want to erase the preferences in the database in case the preference
2511 # is re-enabled again. So don't touch $mOptions, just override the returned value
2512 foreach ( $wgHiddenPrefs as $pref ) {
2513 $default = self::getDefaultOption( $pref );
2514 if ( $default !== null ) {
2515 $options[$pref] = $default;
2519 return $options;
2523 * Get the user's current setting for a given option, as a boolean value.
2525 * @param string $oname The option to check
2526 * @return bool User's current value for the option
2527 * @see getOption()
2529 public function getBoolOption( $oname ) {
2530 return (bool)$this->getOption( $oname );
2534 * Get the user's current setting for a given option, as an integer value.
2536 * @param string $oname The option to check
2537 * @param int $defaultOverride A default value returned if the option does not exist
2538 * @return int User's current value for the option
2539 * @see getOption()
2541 public function getIntOption( $oname, $defaultOverride = 0 ) {
2542 $val = $this->getOption( $oname );
2543 if ( $val == '' ) {
2544 $val = $defaultOverride;
2546 return intval( $val );
2550 * Set the given option for a user.
2552 * You need to call saveSettings() to actually write to the database.
2554 * @param string $oname The option to set
2555 * @param mixed $val New value to set
2557 public function setOption( $oname, $val ) {
2558 $this->loadOptions();
2560 // Explicitly NULL values should refer to defaults
2561 if ( is_null( $val ) ) {
2562 $val = self::getDefaultOption( $oname );
2565 $this->mOptions[$oname] = $val;
2569 * Get a token stored in the preferences (like the watchlist one),
2570 * resetting it if it's empty (and saving changes).
2572 * @param string $oname The option name to retrieve the token from
2573 * @return string|bool User's current value for the option, or false if this option is disabled.
2574 * @see resetTokenFromOption()
2575 * @see getOption()
2577 public function getTokenFromOption( $oname ) {
2578 global $wgHiddenPrefs;
2579 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2580 return false;
2583 $token = $this->getOption( $oname );
2584 if ( !$token ) {
2585 $token = $this->resetTokenFromOption( $oname );
2586 $this->saveSettings();
2588 return $token;
2592 * Reset a token stored in the preferences (like the watchlist one).
2593 * *Does not* save user's preferences (similarly to setOption()).
2595 * @param string $oname The option name to reset the token in
2596 * @return string|bool New token value, or false if this option is disabled.
2597 * @see getTokenFromOption()
2598 * @see setOption()
2600 public function resetTokenFromOption( $oname ) {
2601 global $wgHiddenPrefs;
2602 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2603 return false;
2606 $token = MWCryptRand::generateHex( 40 );
2607 $this->setOption( $oname, $token );
2608 return $token;
2612 * Return a list of the types of user options currently returned by
2613 * User::getOptionKinds().
2615 * Currently, the option kinds are:
2616 * - 'registered' - preferences which are registered in core MediaWiki or
2617 * by extensions using the UserGetDefaultOptions hook.
2618 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2619 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2620 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2621 * be used by user scripts.
2622 * - 'special' - "preferences" that are not accessible via User::getOptions
2623 * or User::setOptions.
2624 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2625 * These are usually legacy options, removed in newer versions.
2627 * The API (and possibly others) use this function to determine the possible
2628 * option types for validation purposes, so make sure to update this when a
2629 * new option kind is added.
2631 * @see User::getOptionKinds
2632 * @return array Option kinds
2634 public static function listOptionKinds() {
2635 return array(
2636 'registered',
2637 'registered-multiselect',
2638 'registered-checkmatrix',
2639 'userjs',
2640 'special',
2641 'unused'
2646 * Return an associative array mapping preferences keys to the kind of a preference they're
2647 * used for. Different kinds are handled differently when setting or reading preferences.
2649 * See User::listOptionKinds for the list of valid option types that can be provided.
2651 * @see User::listOptionKinds
2652 * @param IContextSource $context
2653 * @param array $options Assoc. array with options keys to check as keys.
2654 * Defaults to $this->mOptions.
2655 * @return array the key => kind mapping data
2657 public function getOptionKinds( IContextSource $context, $options = null ) {
2658 $this->loadOptions();
2659 if ( $options === null ) {
2660 $options = $this->mOptions;
2663 $prefs = Preferences::getPreferences( $this, $context );
2664 $mapping = array();
2666 // Pull out the "special" options, so they don't get converted as
2667 // multiselect or checkmatrix.
2668 $specialOptions = array_fill_keys( Preferences::getSaveBlacklist(), true );
2669 foreach ( $specialOptions as $name => $value ) {
2670 unset( $prefs[$name] );
2673 // Multiselect and checkmatrix options are stored in the database with
2674 // one key per option, each having a boolean value. Extract those keys.
2675 $multiselectOptions = array();
2676 foreach ( $prefs as $name => $info ) {
2677 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2678 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2679 $opts = HTMLFormField::flattenOptions( $info['options'] );
2680 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2682 foreach ( $opts as $value ) {
2683 $multiselectOptions["$prefix$value"] = true;
2686 unset( $prefs[$name] );
2689 $checkmatrixOptions = array();
2690 foreach ( $prefs as $name => $info ) {
2691 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2692 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2693 $columns = HTMLFormField::flattenOptions( $info['columns'] );
2694 $rows = HTMLFormField::flattenOptions( $info['rows'] );
2695 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2697 foreach ( $columns as $column ) {
2698 foreach ( $rows as $row ) {
2699 $checkmatrixOptions["$prefix-$column-$row"] = true;
2703 unset( $prefs[$name] );
2707 // $value is ignored
2708 foreach ( $options as $key => $value ) {
2709 if ( isset( $prefs[$key] ) ) {
2710 $mapping[$key] = 'registered';
2711 } elseif ( isset( $multiselectOptions[$key] ) ) {
2712 $mapping[$key] = 'registered-multiselect';
2713 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2714 $mapping[$key] = 'registered-checkmatrix';
2715 } elseif ( isset( $specialOptions[$key] ) ) {
2716 $mapping[$key] = 'special';
2717 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2718 $mapping[$key] = 'userjs';
2719 } else {
2720 $mapping[$key] = 'unused';
2724 return $mapping;
2728 * Reset certain (or all) options to the site defaults
2730 * The optional parameter determines which kinds of preferences will be reset.
2731 * Supported values are everything that can be reported by getOptionKinds()
2732 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2734 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2735 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2736 * for backwards-compatibility.
2737 * @param IContextSource|null $context Context source used when $resetKinds
2738 * does not contain 'all', passed to getOptionKinds().
2739 * Defaults to RequestContext::getMain() when null.
2741 public function resetOptions(
2742 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2743 IContextSource $context = null
2745 $this->load();
2746 $defaultOptions = self::getDefaultOptions();
2748 if ( !is_array( $resetKinds ) ) {
2749 $resetKinds = array( $resetKinds );
2752 if ( in_array( 'all', $resetKinds ) ) {
2753 $newOptions = $defaultOptions;
2754 } else {
2755 if ( $context === null ) {
2756 $context = RequestContext::getMain();
2759 $optionKinds = $this->getOptionKinds( $context );
2760 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
2761 $newOptions = array();
2763 // Use default values for the options that should be deleted, and
2764 // copy old values for the ones that shouldn't.
2765 foreach ( $this->mOptions as $key => $value ) {
2766 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2767 if ( array_key_exists( $key, $defaultOptions ) ) {
2768 $newOptions[$key] = $defaultOptions[$key];
2770 } else {
2771 $newOptions[$key] = $value;
2776 $this->mOptions = $newOptions;
2777 $this->mOptionsLoaded = true;
2781 * Get the user's preferred date format.
2782 * @return string User's preferred date format
2784 public function getDatePreference() {
2785 // Important migration for old data rows
2786 if ( is_null( $this->mDatePreference ) ) {
2787 global $wgLang;
2788 $value = $this->getOption( 'date' );
2789 $map = $wgLang->getDatePreferenceMigrationMap();
2790 if ( isset( $map[$value] ) ) {
2791 $value = $map[$value];
2793 $this->mDatePreference = $value;
2795 return $this->mDatePreference;
2799 * Determine based on the wiki configuration and the user's options,
2800 * whether this user must be over HTTPS no matter what.
2802 * @return bool
2804 public function requiresHTTPS() {
2805 global $wgSecureLogin;
2806 if ( !$wgSecureLogin ) {
2807 return false;
2808 } else {
2809 $https = $this->getBoolOption( 'prefershttps' );
2810 wfRunHooks( 'UserRequiresHTTPS', array( $this, &$https ) );
2811 if ( $https ) {
2812 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2814 return $https;
2819 * Get the user preferred stub threshold
2821 * @return int
2823 public function getStubThreshold() {
2824 global $wgMaxArticleSize; # Maximum article size, in Kb
2825 $threshold = $this->getIntOption( 'stubthreshold' );
2826 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2827 // If they have set an impossible value, disable the preference
2828 // so we can use the parser cache again.
2829 $threshold = 0;
2831 return $threshold;
2835 * Get the permissions this user has.
2836 * @return array Array of String permission names
2838 public function getRights() {
2839 if ( is_null( $this->mRights ) ) {
2840 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2841 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
2842 // Force reindexation of rights when a hook has unset one of them
2843 $this->mRights = array_values( array_unique( $this->mRights ) );
2845 return $this->mRights;
2849 * Get the list of explicit group memberships this user has.
2850 * The implicit * and user groups are not included.
2851 * @return array Array of String internal group names
2853 public function getGroups() {
2854 $this->load();
2855 $this->loadGroups();
2856 return $this->mGroups;
2860 * Get the list of implicit group memberships this user has.
2861 * This includes all explicit groups, plus 'user' if logged in,
2862 * '*' for all accounts, and autopromoted groups
2863 * @param bool $recache Whether to avoid the cache
2864 * @return array Array of String internal group names
2866 public function getEffectiveGroups( $recache = false ) {
2867 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
2868 wfProfileIn( __METHOD__ );
2869 $this->mEffectiveGroups = array_unique( array_merge(
2870 $this->getGroups(), // explicit groups
2871 $this->getAutomaticGroups( $recache ) // implicit groups
2872 ) );
2873 // Hook for additional groups
2874 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
2875 // Force reindexation of groups when a hook has unset one of them
2876 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
2877 wfProfileOut( __METHOD__ );
2879 return $this->mEffectiveGroups;
2883 * Get the list of implicit group memberships this user has.
2884 * This includes 'user' if logged in, '*' for all accounts,
2885 * and autopromoted groups
2886 * @param bool $recache Whether to avoid the cache
2887 * @return array Array of String internal group names
2889 public function getAutomaticGroups( $recache = false ) {
2890 if ( $recache || is_null( $this->mImplicitGroups ) ) {
2891 wfProfileIn( __METHOD__ );
2892 $this->mImplicitGroups = array( '*' );
2893 if ( $this->getId() ) {
2894 $this->mImplicitGroups[] = 'user';
2896 $this->mImplicitGroups = array_unique( array_merge(
2897 $this->mImplicitGroups,
2898 Autopromote::getAutopromoteGroups( $this )
2899 ) );
2901 if ( $recache ) {
2902 // Assure data consistency with rights/groups,
2903 // as getEffectiveGroups() depends on this function
2904 $this->mEffectiveGroups = null;
2906 wfProfileOut( __METHOD__ );
2908 return $this->mImplicitGroups;
2912 * Returns the groups the user has belonged to.
2914 * The user may still belong to the returned groups. Compare with getGroups().
2916 * The function will not return groups the user had belonged to before MW 1.17
2918 * @return array Names of the groups the user has belonged to.
2920 public function getFormerGroups() {
2921 if ( is_null( $this->mFormerGroups ) ) {
2922 $dbr = wfGetDB( DB_MASTER );
2923 $res = $dbr->select( 'user_former_groups',
2924 array( 'ufg_group' ),
2925 array( 'ufg_user' => $this->mId ),
2926 __METHOD__ );
2927 $this->mFormerGroups = array();
2928 foreach ( $res as $row ) {
2929 $this->mFormerGroups[] = $row->ufg_group;
2932 return $this->mFormerGroups;
2936 * Get the user's edit count.
2937 * @return int|null null for anonymous users
2939 public function getEditCount() {
2940 if ( !$this->getId() ) {
2941 return null;
2944 if ( !isset( $this->mEditCount ) ) {
2945 /* Populate the count, if it has not been populated yet */
2946 wfProfileIn( __METHOD__ );
2947 $dbr = wfGetDB( DB_SLAVE );
2948 // check if the user_editcount field has been initialized
2949 $count = $dbr->selectField(
2950 'user', 'user_editcount',
2951 array( 'user_id' => $this->mId ),
2952 __METHOD__
2955 if ( $count === null ) {
2956 // it has not been initialized. do so.
2957 $count = $this->initEditCount();
2959 $this->mEditCount = $count;
2960 wfProfileOut( __METHOD__ );
2962 return (int)$this->mEditCount;
2966 * Add the user to the given group.
2967 * This takes immediate effect.
2968 * @param string $group Name of the group to add
2970 public function addGroup( $group ) {
2971 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2972 $dbw = wfGetDB( DB_MASTER );
2973 if ( $this->getId() ) {
2974 $dbw->insert( 'user_groups',
2975 array(
2976 'ug_user' => $this->getID(),
2977 'ug_group' => $group,
2979 __METHOD__,
2980 array( 'IGNORE' ) );
2983 $this->loadGroups();
2984 $this->mGroups[] = $group;
2985 // In case loadGroups was not called before, we now have the right twice.
2986 // Get rid of the duplicate.
2987 $this->mGroups = array_unique( $this->mGroups );
2989 // Refresh the groups caches, and clear the rights cache so it will be
2990 // refreshed on the next call to $this->getRights().
2991 $this->getEffectiveGroups( true );
2992 $this->mRights = null;
2994 $this->invalidateCache();
2998 * Remove the user from the given group.
2999 * This takes immediate effect.
3000 * @param string $group Name of the group to remove
3002 public function removeGroup( $group ) {
3003 $this->load();
3004 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3005 $dbw = wfGetDB( DB_MASTER );
3006 $dbw->delete( 'user_groups',
3007 array(
3008 'ug_user' => $this->getID(),
3009 'ug_group' => $group,
3010 ), __METHOD__ );
3011 // Remember that the user was in this group
3012 $dbw->insert( 'user_former_groups',
3013 array(
3014 'ufg_user' => $this->getID(),
3015 'ufg_group' => $group,
3017 __METHOD__,
3018 array( 'IGNORE' ) );
3020 $this->loadGroups();
3021 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
3023 // Refresh the groups caches, and clear the rights cache so it will be
3024 // refreshed on the next call to $this->getRights().
3025 $this->getEffectiveGroups( true );
3026 $this->mRights = null;
3028 $this->invalidateCache();
3032 * Get whether the user is logged in
3033 * @return bool
3035 public function isLoggedIn() {
3036 return $this->getID() != 0;
3040 * Get whether the user is anonymous
3041 * @return bool
3043 public function isAnon() {
3044 return !$this->isLoggedIn();
3048 * Check if user is allowed to access a feature / make an action
3050 * @internal param \String $varargs permissions to test
3051 * @return bool True if user is allowed to perform *any* of the given actions
3053 * @return bool
3055 public function isAllowedAny( /*...*/ ) {
3056 $permissions = func_get_args();
3057 foreach ( $permissions as $permission ) {
3058 if ( $this->isAllowed( $permission ) ) {
3059 return true;
3062 return false;
3067 * @internal param $varargs string
3068 * @return bool True if the user is allowed to perform *all* of the given actions
3070 public function isAllowedAll( /*...*/ ) {
3071 $permissions = func_get_args();
3072 foreach ( $permissions as $permission ) {
3073 if ( !$this->isAllowed( $permission ) ) {
3074 return false;
3077 return true;
3081 * Internal mechanics of testing a permission
3082 * @param string $action
3083 * @return bool
3085 public function isAllowed( $action = '' ) {
3086 if ( $action === '' ) {
3087 return true; // In the spirit of DWIM
3089 // Patrolling may not be enabled
3090 if ( $action === 'patrol' || $action === 'autopatrol' ) {
3091 global $wgUseRCPatrol, $wgUseNPPatrol;
3092 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3093 return false;
3096 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3097 // by misconfiguration: 0 == 'foo'
3098 return in_array( $action, $this->getRights(), true );
3102 * Check whether to enable recent changes patrol features for this user
3103 * @return bool True or false
3105 public function useRCPatrol() {
3106 global $wgUseRCPatrol;
3107 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3111 * Check whether to enable new pages patrol features for this user
3112 * @return bool True or false
3114 public function useNPPatrol() {
3115 global $wgUseRCPatrol, $wgUseNPPatrol;
3116 return (
3117 ( $wgUseRCPatrol || $wgUseNPPatrol )
3118 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3123 * Get the WebRequest object to use with this object
3125 * @return WebRequest
3127 public function getRequest() {
3128 if ( $this->mRequest ) {
3129 return $this->mRequest;
3130 } else {
3131 global $wgRequest;
3132 return $wgRequest;
3137 * Get the current skin, loading it if required
3138 * @return Skin The current skin
3139 * @todo FIXME: Need to check the old failback system [AV]
3140 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3142 public function getSkin() {
3143 wfDeprecated( __METHOD__, '1.18' );
3144 return RequestContext::getMain()->getSkin();
3148 * Get a WatchedItem for this user and $title.
3150 * @since 1.22 $checkRights parameter added
3151 * @param Title $title
3152 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3153 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3154 * @return WatchedItem
3156 public function getWatchedItem( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3157 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3159 if ( isset( $this->mWatchedItems[$key] ) ) {
3160 return $this->mWatchedItems[$key];
3163 if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
3164 $this->mWatchedItems = array();
3167 $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title, $checkRights );
3168 return $this->mWatchedItems[$key];
3172 * Check the watched status of an article.
3173 * @since 1.22 $checkRights parameter added
3174 * @param Title $title Title of the article to look at
3175 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3176 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3177 * @return bool
3179 public function isWatched( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3180 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3184 * Watch an article.
3185 * @since 1.22 $checkRights parameter added
3186 * @param Title $title Title of the article to look at
3187 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3188 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3190 public function addWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3191 $this->getWatchedItem( $title, $checkRights )->addWatch();
3192 $this->invalidateCache();
3196 * Stop watching an article.
3197 * @since 1.22 $checkRights parameter added
3198 * @param Title $title Title of the article to look at
3199 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3200 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3202 public function removeWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3203 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3204 $this->invalidateCache();
3208 * Clear the user's notification timestamp for the given title.
3209 * If e-notif e-mails are on, they will receive notification mails on
3210 * the next change of the page if it's watched etc.
3211 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3212 * @param Title $title Title of the article to look at
3213 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3215 public function clearNotification( &$title, $oldid = 0 ) {
3216 global $wgUseEnotif, $wgShowUpdatedMarker;
3218 // Do nothing if the database is locked to writes
3219 if ( wfReadOnly() ) {
3220 return;
3223 // Do nothing if not allowed to edit the watchlist
3224 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3225 return;
3228 // If we're working on user's talk page, we should update the talk page message indicator
3229 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3230 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3231 return;
3234 $nextid = $oldid ? $title->getNextRevisionID( $oldid ) : null;
3236 if ( !$oldid || !$nextid ) {
3237 // If we're looking at the latest revision, we should definitely clear it
3238 $this->setNewtalk( false );
3239 } else {
3240 // Otherwise we should update its revision, if it's present
3241 if ( $this->getNewtalk() ) {
3242 // Naturally the other one won't clear by itself
3243 $this->setNewtalk( false );
3244 $this->setNewtalk( true, Revision::newFromId( $nextid ) );
3249 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3250 return;
3253 if ( $this->isAnon() ) {
3254 // Nothing else to do...
3255 return;
3258 // Only update the timestamp if the page is being watched.
3259 // The query to find out if it is watched is cached both in memcached and per-invocation,
3260 // and when it does have to be executed, it can be on a slave
3261 // If this is the user's newtalk page, we always update the timestamp
3262 $force = '';
3263 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3264 $force = 'force';
3267 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3271 * Resets all of the given user's page-change notification timestamps.
3272 * If e-notif e-mails are on, they will receive notification mails on
3273 * the next change of any watched page.
3274 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3276 public function clearAllNotifications() {
3277 if ( wfReadOnly() ) {
3278 return;
3281 // Do nothing if not allowed to edit the watchlist
3282 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3283 return;
3286 global $wgUseEnotif, $wgShowUpdatedMarker;
3287 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3288 $this->setNewtalk( false );
3289 return;
3291 $id = $this->getId();
3292 if ( $id != 0 ) {
3293 $dbw = wfGetDB( DB_MASTER );
3294 $dbw->update( 'watchlist',
3295 array( /* SET */ 'wl_notificationtimestamp' => null ),
3296 array( /* WHERE */ 'wl_user' => $id ),
3297 __METHOD__
3299 // We also need to clear here the "you have new message" notification for the own user_talk page;
3300 // it's cleared one page view later in WikiPage::doViewUpdates().
3305 * Set a cookie on the user's client. Wrapper for
3306 * WebResponse::setCookie
3307 * @param string $name Name of the cookie to set
3308 * @param string $value Value to set
3309 * @param int $exp Expiration time, as a UNIX time value;
3310 * if 0 or not specified, use the default $wgCookieExpiration
3311 * @param bool $secure
3312 * true: Force setting the secure attribute when setting the cookie
3313 * false: Force NOT setting the secure attribute when setting the cookie
3314 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3315 * @param array $params Array of options sent passed to WebResponse::setcookie()
3317 protected function setCookie( $name, $value, $exp = 0, $secure = null, $params = array() ) {
3318 $params['secure'] = $secure;
3319 $this->getRequest()->response()->setcookie( $name, $value, $exp, $params );
3323 * Clear a cookie on the user's client
3324 * @param string $name Name of the cookie to clear
3325 * @param bool $secure
3326 * true: Force setting the secure attribute when setting the cookie
3327 * false: Force NOT setting the secure attribute when setting the cookie
3328 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3329 * @param array $params Array of options sent passed to WebResponse::setcookie()
3331 protected function clearCookie( $name, $secure = null, $params = array() ) {
3332 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3336 * Set the default cookies for this session on the user's client.
3338 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3339 * is passed.
3340 * @param bool $secure Whether to force secure/insecure cookies or use default
3341 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3343 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3344 if ( $request === null ) {
3345 $request = $this->getRequest();
3348 $this->load();
3349 if ( 0 == $this->mId ) {
3350 return;
3352 if ( !$this->mToken ) {
3353 // When token is empty or NULL generate a new one and then save it to the database
3354 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3355 // Simply by setting every cell in the user_token column to NULL and letting them be
3356 // regenerated as users log back into the wiki.
3357 $this->setToken();
3358 $this->saveSettings();
3360 $session = array(
3361 'wsUserID' => $this->mId,
3362 'wsToken' => $this->mToken,
3363 'wsUserName' => $this->getName()
3365 $cookies = array(
3366 'UserID' => $this->mId,
3367 'UserName' => $this->getName(),
3369 if ( $rememberMe ) {
3370 $cookies['Token'] = $this->mToken;
3371 } else {
3372 $cookies['Token'] = false;
3375 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3377 foreach ( $session as $name => $value ) {
3378 $request->setSessionData( $name, $value );
3380 foreach ( $cookies as $name => $value ) {
3381 if ( $value === false ) {
3382 $this->clearCookie( $name );
3383 } else {
3384 $this->setCookie( $name, $value, 0, $secure );
3389 * If wpStickHTTPS was selected, also set an insecure cookie that
3390 * will cause the site to redirect the user to HTTPS, if they access
3391 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3392 * as the one set by centralauth (bug 53538). Also set it to session, or
3393 * standard time setting, based on if rememberme was set.
3395 if ( $request->getCheck( 'wpStickHTTPS' ) || $this->requiresHTTPS() ) {
3396 $this->setCookie(
3397 'forceHTTPS',
3398 'true',
3399 $rememberMe ? 0 : null,
3400 false,
3401 array( 'prefix' => '' ) // no prefix
3407 * Log this user out.
3409 public function logout() {
3410 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3411 $this->doLogout();
3416 * Clear the user's cookies and session, and reset the instance cache.
3417 * @see logout()
3419 public function doLogout() {
3420 $this->clearInstanceCache( 'defaults' );
3422 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3424 $this->clearCookie( 'UserID' );
3425 $this->clearCookie( 'Token' );
3426 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3428 // Remember when user logged out, to prevent seeing cached pages
3429 $this->setCookie( 'LoggedOut', time(), time() + 86400 );
3433 * Save this user's settings into the database.
3434 * @todo Only rarely do all these fields need to be set!
3436 public function saveSettings() {
3437 global $wgAuth;
3439 $this->load();
3440 if ( wfReadOnly() ) {
3441 return;
3443 if ( 0 == $this->mId ) {
3444 return;
3447 $this->mTouched = self::newTouchedTimestamp();
3448 if ( !$wgAuth->allowSetLocalPassword() ) {
3449 $this->mPassword = '';
3452 $dbw = wfGetDB( DB_MASTER );
3453 $dbw->update( 'user',
3454 array( /* SET */
3455 'user_name' => $this->mName,
3456 'user_password' => $this->mPassword,
3457 'user_newpassword' => $this->mNewpassword,
3458 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3459 'user_real_name' => $this->mRealName,
3460 'user_email' => $this->mEmail,
3461 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3462 'user_touched' => $dbw->timestamp( $this->mTouched ),
3463 'user_token' => strval( $this->mToken ),
3464 'user_email_token' => $this->mEmailToken,
3465 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3466 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires ),
3467 ), array( /* WHERE */
3468 'user_id' => $this->mId
3469 ), __METHOD__
3472 $this->saveOptions();
3474 wfRunHooks( 'UserSaveSettings', array( $this ) );
3475 $this->clearSharedCache();
3476 $this->getUserPage()->invalidateCache();
3480 * If only this user's username is known, and it exists, return the user ID.
3481 * @return int
3483 public function idForName() {
3484 $s = trim( $this->getName() );
3485 if ( $s === '' ) {
3486 return 0;
3489 $dbr = wfGetDB( DB_SLAVE );
3490 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
3491 if ( $id === false ) {
3492 $id = 0;
3494 return $id;
3498 * Add a user to the database, return the user object
3500 * @param string $name Username to add
3501 * @param array $params Array of Strings Non-default parameters to save to
3502 * the database as user_* fields:
3503 * - password: The user's password hash. Password logins will be disabled
3504 * if this is omitted.
3505 * - newpassword: Hash for a temporary password that has been mailed to
3506 * the user.
3507 * - email: The user's email address.
3508 * - email_authenticated: The email authentication timestamp.
3509 * - real_name: The user's real name.
3510 * - options: An associative array of non-default options.
3511 * - token: Random authentication token. Do not set.
3512 * - registration: Registration timestamp. Do not set.
3514 * @return User|null User object, or null if the username already exists.
3516 public static function createNew( $name, $params = array() ) {
3517 $user = new User;
3518 $user->load();
3519 $user->setToken(); // init token
3520 if ( isset( $params['options'] ) ) {
3521 $user->mOptions = $params['options'] + (array)$user->mOptions;
3522 unset( $params['options'] );
3524 $dbw = wfGetDB( DB_MASTER );
3525 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3527 $fields = array(
3528 'user_id' => $seqVal,
3529 'user_name' => $name,
3530 'user_password' => $user->mPassword,
3531 'user_newpassword' => $user->mNewpassword,
3532 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
3533 'user_email' => $user->mEmail,
3534 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3535 'user_real_name' => $user->mRealName,
3536 'user_token' => strval( $user->mToken ),
3537 'user_registration' => $dbw->timestamp( $user->mRegistration ),
3538 'user_editcount' => 0,
3539 'user_touched' => $dbw->timestamp( self::newTouchedTimestamp() ),
3541 foreach ( $params as $name => $value ) {
3542 $fields["user_$name"] = $value;
3544 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
3545 if ( $dbw->affectedRows() ) {
3546 $newUser = User::newFromId( $dbw->insertId() );
3547 } else {
3548 $newUser = null;
3550 return $newUser;
3554 * Add this existing user object to the database. If the user already
3555 * exists, a fatal status object is returned, and the user object is
3556 * initialised with the data from the database.
3558 * Previously, this function generated a DB error due to a key conflict
3559 * if the user already existed. Many extension callers use this function
3560 * in code along the lines of:
3562 * $user = User::newFromName( $name );
3563 * if ( !$user->isLoggedIn() ) {
3564 * $user->addToDatabase();
3566 * // do something with $user...
3568 * However, this was vulnerable to a race condition (bug 16020). By
3569 * initialising the user object if the user exists, we aim to support this
3570 * calling sequence as far as possible.
3572 * Note that if the user exists, this function will acquire a write lock,
3573 * so it is still advisable to make the call conditional on isLoggedIn(),
3574 * and to commit the transaction after calling.
3576 * @throws MWException
3577 * @return Status
3579 public function addToDatabase() {
3580 $this->load();
3581 if ( !$this->mToken ) {
3582 $this->setToken(); // init token
3585 $this->mTouched = self::newTouchedTimestamp();
3587 $dbw = wfGetDB( DB_MASTER );
3588 $inWrite = $dbw->writesOrCallbacksPending();
3589 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3590 $dbw->insert( 'user',
3591 array(
3592 'user_id' => $seqVal,
3593 'user_name' => $this->mName,
3594 'user_password' => $this->mPassword,
3595 'user_newpassword' => $this->mNewpassword,
3596 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3597 'user_email' => $this->mEmail,
3598 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3599 'user_real_name' => $this->mRealName,
3600 'user_token' => strval( $this->mToken ),
3601 'user_registration' => $dbw->timestamp( $this->mRegistration ),
3602 'user_editcount' => 0,
3603 'user_touched' => $dbw->timestamp( $this->mTouched ),
3604 ), __METHOD__,
3605 array( 'IGNORE' )
3607 if ( !$dbw->affectedRows() ) {
3608 if ( !$inWrite ) {
3609 // XXX: Get out of REPEATABLE-READ so the SELECT below works.
3610 // Often this case happens early in views before any writes.
3611 // This shows up at least with CentralAuth.
3612 $dbw->commit( __METHOD__, 'flush' );
3614 $this->mId = $dbw->selectField( 'user', 'user_id',
3615 array( 'user_name' => $this->mName ), __METHOD__ );
3616 $loaded = false;
3617 if ( $this->mId ) {
3618 if ( $this->loadFromDatabase() ) {
3619 $loaded = true;
3622 if ( !$loaded ) {
3623 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
3624 "to insert user '{$this->mName}' row, but it was not present in select!" );
3626 return Status::newFatal( 'userexists' );
3628 $this->mId = $dbw->insertId();
3630 // Clear instance cache other than user table data, which is already accurate
3631 $this->clearInstanceCache();
3633 $this->saveOptions();
3634 return Status::newGood();
3638 * If this user is logged-in and blocked,
3639 * block any IP address they've successfully logged in from.
3640 * @return bool A block was spread
3642 public function spreadAnyEditBlock() {
3643 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3644 return $this->spreadBlock();
3646 return false;
3650 * If this (non-anonymous) user is blocked,
3651 * block the IP address they've successfully logged in from.
3652 * @return bool A block was spread
3654 protected function spreadBlock() {
3655 wfDebug( __METHOD__ . "()\n" );
3656 $this->load();
3657 if ( $this->mId == 0 ) {
3658 return false;
3661 $userblock = Block::newFromTarget( $this->getName() );
3662 if ( !$userblock ) {
3663 return false;
3666 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3670 * Get whether the user is explicitly blocked from account creation.
3671 * @return bool|Block
3673 public function isBlockedFromCreateAccount() {
3674 $this->getBlockedStatus();
3675 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
3676 return $this->mBlock;
3679 # bug 13611: if the IP address the user is trying to create an account from is
3680 # blocked with createaccount disabled, prevent new account creation there even
3681 # when the user is logged in
3682 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3683 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
3685 return $this->mBlockedFromCreateAccount instanceof Block
3686 && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
3687 ? $this->mBlockedFromCreateAccount
3688 : false;
3692 * Get whether the user is blocked from using Special:Emailuser.
3693 * @return bool
3695 public function isBlockedFromEmailuser() {
3696 $this->getBlockedStatus();
3697 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
3701 * Get whether the user is allowed to create an account.
3702 * @return bool
3704 public function isAllowedToCreateAccount() {
3705 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3709 * Get this user's personal page title.
3711 * @return Title User's personal page title
3713 public function getUserPage() {
3714 return Title::makeTitle( NS_USER, $this->getName() );
3718 * Get this user's talk page title.
3720 * @return Title User's talk page title
3722 public function getTalkPage() {
3723 $title = $this->getUserPage();
3724 return $title->getTalkPage();
3728 * Determine whether the user is a newbie. Newbies are either
3729 * anonymous IPs, or the most recently created accounts.
3730 * @return bool
3732 public function isNewbie() {
3733 return !$this->isAllowed( 'autoconfirmed' );
3737 * Check to see if the given clear-text password is one of the accepted passwords
3738 * @param string $password user password.
3739 * @return bool True if the given password is correct, otherwise False.
3741 public function checkPassword( $password ) {
3742 global $wgAuth, $wgLegacyEncoding;
3743 $this->load();
3745 // Certain authentication plugins do NOT want to save
3746 // domain passwords in a mysql database, so we should
3747 // check this (in case $wgAuth->strict() is false).
3749 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3750 return true;
3751 } elseif ( $wgAuth->strict() ) {
3752 // Auth plugin doesn't allow local authentication
3753 return false;
3754 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3755 // Auth plugin doesn't allow local authentication for this user name
3756 return false;
3758 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
3759 return true;
3760 } elseif ( $wgLegacyEncoding ) {
3761 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3762 // Check for this with iconv
3763 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3764 if ( $cp1252Password != $password
3765 && self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId )
3767 return true;
3770 return false;
3774 * Check if the given clear-text password matches the temporary password
3775 * sent by e-mail for password reset operations.
3777 * @param string $plaintext
3779 * @return bool True if matches, false otherwise
3781 public function checkTemporaryPassword( $plaintext ) {
3782 global $wgNewPasswordExpiry;
3784 $this->load();
3785 if ( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) {
3786 if ( is_null( $this->mNewpassTime ) ) {
3787 return true;
3789 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
3790 return ( time() < $expiry );
3791 } else {
3792 return false;
3797 * Alias for getEditToken.
3798 * @deprecated since 1.19, use getEditToken instead.
3800 * @param string|array $salt of Strings Optional function-specific data for hashing
3801 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3802 * @return string The new edit token
3804 public function editToken( $salt = '', $request = null ) {
3805 wfDeprecated( __METHOD__, '1.19' );
3806 return $this->getEditToken( $salt, $request );
3810 * Initialize (if necessary) and return a session token value
3811 * which can be used in edit forms to show that the user's
3812 * login credentials aren't being hijacked with a foreign form
3813 * submission.
3815 * @since 1.19
3817 * @param string|array $salt of Strings Optional function-specific data for hashing
3818 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3819 * @return string The new edit token
3821 public function getEditToken( $salt = '', $request = null ) {
3822 if ( $request == null ) {
3823 $request = $this->getRequest();
3826 if ( $this->isAnon() ) {
3827 return EDIT_TOKEN_SUFFIX;
3828 } else {
3829 $token = $request->getSessionData( 'wsEditToken' );
3830 if ( $token === null ) {
3831 $token = MWCryptRand::generateHex( 32 );
3832 $request->setSessionData( 'wsEditToken', $token );
3834 if ( is_array( $salt ) ) {
3835 $salt = implode( '|', $salt );
3837 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
3842 * Generate a looking random token for various uses.
3844 * @return string The new random token
3845 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
3846 * wfRandomString for pseudo-randomness.
3848 public static function generateToken() {
3849 return MWCryptRand::generateHex( 32 );
3853 * Check given value against the token value stored in the session.
3854 * A match should confirm that the form was submitted from the
3855 * user's own login session, not a form submission from a third-party
3856 * site.
3858 * @param string $val Input value to compare
3859 * @param string $salt Optional function-specific data for hashing
3860 * @param WebRequest|null $request Object to use or null to use $wgRequest
3861 * @return bool Whether the token matches
3863 public function matchEditToken( $val, $salt = '', $request = null ) {
3864 $sessionToken = $this->getEditToken( $salt, $request );
3865 if ( $val != $sessionToken ) {
3866 wfDebug( "User::matchEditToken: broken session data\n" );
3869 return $val == $sessionToken;
3873 * Check given value against the token value stored in the session,
3874 * ignoring the suffix.
3876 * @param string $val Input value to compare
3877 * @param string $salt Optional function-specific data for hashing
3878 * @param WebRequest|null $request object to use or null to use $wgRequest
3879 * @return bool Whether the token matches
3881 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3882 $sessionToken = $this->getEditToken( $salt, $request );
3883 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3887 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3888 * mail to the user's given address.
3890 * @param string $type Message to send, either "created", "changed" or "set"
3891 * @return Status
3893 public function sendConfirmationMail( $type = 'created' ) {
3894 global $wgLang;
3895 $expiration = null; // gets passed-by-ref and defined in next line.
3896 $token = $this->confirmationToken( $expiration );
3897 $url = $this->confirmationTokenUrl( $token );
3898 $invalidateURL = $this->invalidationTokenUrl( $token );
3899 $this->saveSettings();
3901 if ( $type == 'created' || $type === false ) {
3902 $message = 'confirmemail_body';
3903 } elseif ( $type === true ) {
3904 $message = 'confirmemail_body_changed';
3905 } else {
3906 // Messages: confirmemail_body_changed, confirmemail_body_set
3907 $message = 'confirmemail_body_' . $type;
3910 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3911 wfMessage( $message,
3912 $this->getRequest()->getIP(),
3913 $this->getName(),
3914 $url,
3915 $wgLang->timeanddate( $expiration, false ),
3916 $invalidateURL,
3917 $wgLang->date( $expiration, false ),
3918 $wgLang->time( $expiration, false ) )->text() );
3922 * Send an e-mail to this user's account. Does not check for
3923 * confirmed status or validity.
3925 * @param string $subject Message subject
3926 * @param string $body Message body
3927 * @param string $from Optional From address; if unspecified, default
3928 * $wgPasswordSender will be used.
3929 * @param string $replyto Reply-To address
3930 * @return Status
3932 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3933 if ( is_null( $from ) ) {
3934 global $wgPasswordSender;
3935 $sender = new MailAddress( $wgPasswordSender,
3936 wfMessage( 'emailsender' )->inContentLanguage()->text() );
3937 } else {
3938 $sender = new MailAddress( $from );
3941 $to = new MailAddress( $this );
3942 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
3946 * Generate, store, and return a new e-mail confirmation code.
3947 * A hash (unsalted, since it's used as a key) is stored.
3949 * @note Call saveSettings() after calling this function to commit
3950 * this change to the database.
3952 * @param string &$expiration Accepts the expiration time
3953 * @return string New token
3955 protected function confirmationToken( &$expiration ) {
3956 global $wgUserEmailConfirmationTokenExpiry;
3957 $now = time();
3958 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
3959 $expiration = wfTimestamp( TS_MW, $expires );
3960 $this->load();
3961 $token = MWCryptRand::generateHex( 32 );
3962 $hash = md5( $token );
3963 $this->mEmailToken = $hash;
3964 $this->mEmailTokenExpires = $expiration;
3965 return $token;
3969 * Return a URL the user can use to confirm their email address.
3970 * @param string $token Accepts the email confirmation token
3971 * @return string New token URL
3973 protected function confirmationTokenUrl( $token ) {
3974 return $this->getTokenUrl( 'ConfirmEmail', $token );
3978 * Return a URL the user can use to invalidate their email address.
3979 * @param string $token Accepts the email confirmation token
3980 * @return string New token URL
3982 protected function invalidationTokenUrl( $token ) {
3983 return $this->getTokenUrl( 'InvalidateEmail', $token );
3987 * Internal function to format the e-mail validation/invalidation URLs.
3988 * This uses a quickie hack to use the
3989 * hardcoded English names of the Special: pages, for ASCII safety.
3991 * @note Since these URLs get dropped directly into emails, using the
3992 * short English names avoids insanely long URL-encoded links, which
3993 * also sometimes can get corrupted in some browsers/mailers
3994 * (bug 6957 with Gmail and Internet Explorer).
3996 * @param string $page Special page
3997 * @param string $token Token
3998 * @return string Formatted URL
4000 protected function getTokenUrl( $page, $token ) {
4001 // Hack to bypass localization of 'Special:'
4002 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
4003 return $title->getCanonicalURL();
4007 * Mark the e-mail address confirmed.
4009 * @note Call saveSettings() after calling this function to commit the change.
4011 * @return bool
4013 public function confirmEmail() {
4014 // Check if it's already confirmed, so we don't touch the database
4015 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4016 if ( !$this->isEmailConfirmed() ) {
4017 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4018 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
4020 return true;
4024 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4025 * address if it was already confirmed.
4027 * @note Call saveSettings() after calling this function to commit the change.
4028 * @return bool Returns true
4030 public function invalidateEmail() {
4031 $this->load();
4032 $this->mEmailToken = null;
4033 $this->mEmailTokenExpires = null;
4034 $this->setEmailAuthenticationTimestamp( null );
4035 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
4036 return true;
4040 * Set the e-mail authentication timestamp.
4041 * @param string $timestamp TS_MW timestamp
4043 public function setEmailAuthenticationTimestamp( $timestamp ) {
4044 $this->load();
4045 $this->mEmailAuthenticated = $timestamp;
4046 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
4050 * Is this user allowed to send e-mails within limits of current
4051 * site configuration?
4052 * @return bool
4054 public function canSendEmail() {
4055 global $wgEnableEmail, $wgEnableUserEmail;
4056 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4057 return false;
4059 $canSend = $this->isEmailConfirmed();
4060 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
4061 return $canSend;
4065 * Is this user allowed to receive e-mails within limits of current
4066 * site configuration?
4067 * @return bool
4069 public function canReceiveEmail() {
4070 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4074 * Is this user's e-mail address valid-looking and confirmed within
4075 * limits of the current site configuration?
4077 * @note If $wgEmailAuthentication is on, this may require the user to have
4078 * confirmed their address by returning a code or using a password
4079 * sent to the address from the wiki.
4081 * @return bool
4083 public function isEmailConfirmed() {
4084 global $wgEmailAuthentication;
4085 $this->load();
4086 $confirmed = true;
4087 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4088 if ( $this->isAnon() ) {
4089 return false;
4091 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4092 return false;
4094 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4095 return false;
4097 return true;
4098 } else {
4099 return $confirmed;
4104 * Check whether there is an outstanding request for e-mail confirmation.
4105 * @return bool
4107 public function isEmailConfirmationPending() {
4108 global $wgEmailAuthentication;
4109 return $wgEmailAuthentication &&
4110 !$this->isEmailConfirmed() &&
4111 $this->mEmailToken &&
4112 $this->mEmailTokenExpires > wfTimestamp();
4116 * Get the timestamp of account creation.
4118 * @return string|bool|null Timestamp of account creation, false for
4119 * non-existent/anonymous user accounts, or null if existing account
4120 * but information is not in database.
4122 public function getRegistration() {
4123 if ( $this->isAnon() ) {
4124 return false;
4126 $this->load();
4127 return $this->mRegistration;
4131 * Get the timestamp of the first edit
4133 * @return string|bool Timestamp of first edit, or false for
4134 * non-existent/anonymous user accounts.
4136 public function getFirstEditTimestamp() {
4137 if ( $this->getId() == 0 ) {
4138 return false; // anons
4140 $dbr = wfGetDB( DB_SLAVE );
4141 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4142 array( 'rev_user' => $this->getId() ),
4143 __METHOD__,
4144 array( 'ORDER BY' => 'rev_timestamp ASC' )
4146 if ( !$time ) {
4147 return false; // no edits
4149 return wfTimestamp( TS_MW, $time );
4153 * Get the permissions associated with a given list of groups
4155 * @param array $groups Array of Strings List of internal group names
4156 * @return array Array of Strings List of permission key names for given groups combined
4158 public static function getGroupPermissions( $groups ) {
4159 global $wgGroupPermissions, $wgRevokePermissions;
4160 $rights = array();
4161 // grant every granted permission first
4162 foreach ( $groups as $group ) {
4163 if ( isset( $wgGroupPermissions[$group] ) ) {
4164 $rights = array_merge( $rights,
4165 // array_filter removes empty items
4166 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4169 // now revoke the revoked permissions
4170 foreach ( $groups as $group ) {
4171 if ( isset( $wgRevokePermissions[$group] ) ) {
4172 $rights = array_diff( $rights,
4173 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4176 return array_unique( $rights );
4180 * Get all the groups who have a given permission
4182 * @param string $role Role to check
4183 * @return array Array of Strings List of internal group names with the given permission
4185 public static function getGroupsWithPermission( $role ) {
4186 global $wgGroupPermissions;
4187 $allowedGroups = array();
4188 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4189 if ( self::groupHasPermission( $group, $role ) ) {
4190 $allowedGroups[] = $group;
4193 return $allowedGroups;
4197 * Check, if the given group has the given permission
4199 * If you're wanting to check whether all users have a permission, use
4200 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4201 * from anyone.
4203 * @since 1.21
4204 * @param string $group Group to check
4205 * @param string $role Role to check
4206 * @return bool
4208 public static function groupHasPermission( $group, $role ) {
4209 global $wgGroupPermissions, $wgRevokePermissions;
4210 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4211 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4215 * Check if all users have the given permission
4217 * @since 1.22
4218 * @param string $right Right to check
4219 * @return bool
4221 public static function isEveryoneAllowed( $right ) {
4222 global $wgGroupPermissions, $wgRevokePermissions;
4223 static $cache = array();
4225 // Use the cached results, except in unit tests which rely on
4226 // being able change the permission mid-request
4227 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4228 return $cache[$right];
4231 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
4232 $cache[$right] = false;
4233 return false;
4236 // If it's revoked anywhere, then everyone doesn't have it
4237 foreach ( $wgRevokePermissions as $rights ) {
4238 if ( isset( $rights[$right] ) && $rights[$right] ) {
4239 $cache[$right] = false;
4240 return false;
4244 // Allow extensions (e.g. OAuth) to say false
4245 if ( !wfRunHooks( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4246 $cache[$right] = false;
4247 return false;
4250 $cache[$right] = true;
4251 return true;
4255 * Get the localized descriptive name for a group, if it exists
4257 * @param string $group Internal group name
4258 * @return string Localized descriptive group name
4260 public static function getGroupName( $group ) {
4261 $msg = wfMessage( "group-$group" );
4262 return $msg->isBlank() ? $group : $msg->text();
4266 * Get the localized descriptive name for a member of a group, if it exists
4268 * @param string $group Internal group name
4269 * @param string $username Username for gender (since 1.19)
4270 * @return string Localized name for group member
4272 public static function getGroupMember( $group, $username = '#' ) {
4273 $msg = wfMessage( "group-$group-member", $username );
4274 return $msg->isBlank() ? $group : $msg->text();
4278 * Return the set of defined explicit groups.
4279 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4280 * are not included, as they are defined automatically, not in the database.
4281 * @return array Array of internal group names
4283 public static function getAllGroups() {
4284 global $wgGroupPermissions, $wgRevokePermissions;
4285 return array_diff(
4286 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4287 self::getImplicitGroups()
4292 * Get a list of all available permissions.
4293 * @return array Array of permission names
4295 public static function getAllRights() {
4296 if ( self::$mAllRights === false ) {
4297 global $wgAvailableRights;
4298 if ( count( $wgAvailableRights ) ) {
4299 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
4300 } else {
4301 self::$mAllRights = self::$mCoreRights;
4303 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
4305 return self::$mAllRights;
4309 * Get a list of implicit groups
4310 * @return array Array of Strings Array of internal group names
4312 public static function getImplicitGroups() {
4313 global $wgImplicitGroups;
4315 $groups = $wgImplicitGroups;
4316 # Deprecated, use $wgImplictGroups instead
4317 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) );
4319 return $groups;
4323 * Get the title of a page describing a particular group
4325 * @param string $group Internal group name
4326 * @return Title|bool Title of the page if it exists, false otherwise
4328 public static function getGroupPage( $group ) {
4329 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4330 if ( $msg->exists() ) {
4331 $title = Title::newFromText( $msg->text() );
4332 if ( is_object( $title ) ) {
4333 return $title;
4336 return false;
4340 * Create a link to the group in HTML, if available;
4341 * else return the group name.
4343 * @param string $group Internal name of the group
4344 * @param string $text The text of the link
4345 * @return string HTML link to the group
4347 public static function makeGroupLinkHTML( $group, $text = '' ) {
4348 if ( $text == '' ) {
4349 $text = self::getGroupName( $group );
4351 $title = self::getGroupPage( $group );
4352 if ( $title ) {
4353 return Linker::link( $title, htmlspecialchars( $text ) );
4354 } else {
4355 return $text;
4360 * Create a link to the group in Wikitext, if available;
4361 * else return the group name.
4363 * @param string $group Internal name of the group
4364 * @param string $text The text of the link
4365 * @return string Wikilink to the group
4367 public static function makeGroupLinkWiki( $group, $text = '' ) {
4368 if ( $text == '' ) {
4369 $text = self::getGroupName( $group );
4371 $title = self::getGroupPage( $group );
4372 if ( $title ) {
4373 $page = $title->getPrefixedText();
4374 return "[[$page|$text]]";
4375 } else {
4376 return $text;
4381 * Returns an array of the groups that a particular group can add/remove.
4383 * @param string $group The group to check for whether it can add/remove
4384 * @return array array( 'add' => array( addablegroups ),
4385 * 'remove' => array( removablegroups ),
4386 * 'add-self' => array( addablegroups to self),
4387 * 'remove-self' => array( removable groups from self) )
4389 public static function changeableByGroup( $group ) {
4390 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4392 $groups = array(
4393 'add' => array(),
4394 'remove' => array(),
4395 'add-self' => array(),
4396 'remove-self' => array()
4399 if ( empty( $wgAddGroups[$group] ) ) {
4400 // Don't add anything to $groups
4401 } elseif ( $wgAddGroups[$group] === true ) {
4402 // You get everything
4403 $groups['add'] = self::getAllGroups();
4404 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4405 $groups['add'] = $wgAddGroups[$group];
4408 // Same thing for remove
4409 if ( empty( $wgRemoveGroups[$group] ) ) {
4410 } elseif ( $wgRemoveGroups[$group] === true ) {
4411 $groups['remove'] = self::getAllGroups();
4412 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4413 $groups['remove'] = $wgRemoveGroups[$group];
4416 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4417 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4418 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4419 if ( is_int( $key ) ) {
4420 $wgGroupsAddToSelf['user'][] = $value;
4425 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4426 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4427 if ( is_int( $key ) ) {
4428 $wgGroupsRemoveFromSelf['user'][] = $value;
4433 // Now figure out what groups the user can add to him/herself
4434 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4435 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4436 // No idea WHY this would be used, but it's there
4437 $groups['add-self'] = User::getAllGroups();
4438 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4439 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4442 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4443 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4444 $groups['remove-self'] = User::getAllGroups();
4445 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4446 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4449 return $groups;
4453 * Returns an array of groups that this user can add and remove
4454 * @return array array( 'add' => array( addablegroups ),
4455 * 'remove' => array( removablegroups ),
4456 * 'add-self' => array( addablegroups to self),
4457 * 'remove-self' => array( removable groups from self) )
4459 public function changeableGroups() {
4460 if ( $this->isAllowed( 'userrights' ) ) {
4461 // This group gives the right to modify everything (reverse-
4462 // compatibility with old "userrights lets you change
4463 // everything")
4464 // Using array_merge to make the groups reindexed
4465 $all = array_merge( User::getAllGroups() );
4466 return array(
4467 'add' => $all,
4468 'remove' => $all,
4469 'add-self' => array(),
4470 'remove-self' => array()
4474 // Okay, it's not so simple, we will have to go through the arrays
4475 $groups = array(
4476 'add' => array(),
4477 'remove' => array(),
4478 'add-self' => array(),
4479 'remove-self' => array()
4481 $addergroups = $this->getEffectiveGroups();
4483 foreach ( $addergroups as $addergroup ) {
4484 $groups = array_merge_recursive(
4485 $groups, $this->changeableByGroup( $addergroup )
4487 $groups['add'] = array_unique( $groups['add'] );
4488 $groups['remove'] = array_unique( $groups['remove'] );
4489 $groups['add-self'] = array_unique( $groups['add-self'] );
4490 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4492 return $groups;
4496 * Increment the user's edit-count field.
4497 * Will have no effect for anonymous users.
4499 public function incEditCount() {
4500 if ( !$this->isAnon() ) {
4501 $dbw = wfGetDB( DB_MASTER );
4502 $dbw->update(
4503 'user',
4504 array( 'user_editcount=user_editcount+1' ),
4505 array( 'user_id' => $this->getId() ),
4506 __METHOD__
4509 // Lazy initialization check...
4510 if ( $dbw->affectedRows() == 0 ) {
4511 // Now here's a goddamn hack...
4512 $dbr = wfGetDB( DB_SLAVE );
4513 if ( $dbr !== $dbw ) {
4514 // If we actually have a slave server, the count is
4515 // at least one behind because the current transaction
4516 // has not been committed and replicated.
4517 $this->initEditCount( 1 );
4518 } else {
4519 // But if DB_SLAVE is selecting the master, then the
4520 // count we just read includes the revision that was
4521 // just added in the working transaction.
4522 $this->initEditCount();
4526 // edit count in user cache too
4527 $this->invalidateCache();
4531 * Initialize user_editcount from data out of the revision table
4533 * @param int $add Edits to add to the count from the revision table
4534 * @return int Number of edits
4536 protected function initEditCount( $add = 0 ) {
4537 // Pull from a slave to be less cruel to servers
4538 // Accuracy isn't the point anyway here
4539 $dbr = wfGetDB( DB_SLAVE );
4540 $count = (int)$dbr->selectField(
4541 'revision',
4542 'COUNT(rev_user)',
4543 array( 'rev_user' => $this->getId() ),
4544 __METHOD__
4546 $count = $count + $add;
4548 $dbw = wfGetDB( DB_MASTER );
4549 $dbw->update(
4550 'user',
4551 array( 'user_editcount' => $count ),
4552 array( 'user_id' => $this->getId() ),
4553 __METHOD__
4556 return $count;
4560 * Get the description of a given right
4562 * @param string $right Right to query
4563 * @return string Localized description of the right
4565 public static function getRightDescription( $right ) {
4566 $key = "right-$right";
4567 $msg = wfMessage( $key );
4568 return $msg->isBlank() ? $right : $msg->text();
4572 * Make an old-style password hash
4574 * @param string $password Plain-text password
4575 * @param string $userId User ID
4576 * @return string Password hash
4578 public static function oldCrypt( $password, $userId ) {
4579 global $wgPasswordSalt;
4580 if ( $wgPasswordSalt ) {
4581 return md5( $userId . '-' . md5( $password ) );
4582 } else {
4583 return md5( $password );
4588 * Make a new-style password hash
4590 * @param string $password Plain-text password
4591 * @param bool|string $salt Optional salt, may be random or the user ID.
4592 * If unspecified or false, will generate one automatically
4593 * @return string Password hash
4595 public static function crypt( $password, $salt = false ) {
4596 global $wgPasswordSalt;
4598 $hash = '';
4599 if ( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
4600 return $hash;
4603 if ( $wgPasswordSalt ) {
4604 if ( $salt === false ) {
4605 $salt = MWCryptRand::generateHex( 8 );
4607 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
4608 } else {
4609 return ':A:' . md5( $password );
4614 * Compare a password hash with a plain-text password. Requires the user
4615 * ID if there's a chance that the hash is an old-style hash.
4617 * @param string $hash Password hash
4618 * @param string $password Plain-text password to compare
4619 * @param string|bool $userId User ID for old-style password salt
4621 * @return bool
4623 public static function comparePasswords( $hash, $password, $userId = false ) {
4624 $type = substr( $hash, 0, 3 );
4626 $result = false;
4627 if ( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
4628 return $result;
4631 if ( $type == ':A:' ) {
4632 // Unsalted
4633 return md5( $password ) === substr( $hash, 3 );
4634 } elseif ( $type == ':B:' ) {
4635 // Salted
4636 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
4637 return md5( $salt . '-' . md5( $password ) ) === $realHash;
4638 } else {
4639 // Old-style
4640 return self::oldCrypt( $password, $userId ) === $hash;
4645 * Add a newuser log entry for this user.
4646 * Before 1.19 the return value was always true.
4648 * @param string|bool $action Account creation type.
4649 * - String, one of the following values:
4650 * - 'create' for an anonymous user creating an account for himself.
4651 * This will force the action's performer to be the created user itself,
4652 * no matter the value of $wgUser
4653 * - 'create2' for a logged in user creating an account for someone else
4654 * - 'byemail' when the created user will receive its password by e-mail
4655 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4656 * - Boolean means whether the account was created by e-mail (deprecated):
4657 * - true will be converted to 'byemail'
4658 * - false will be converted to 'create' if this object is the same as
4659 * $wgUser and to 'create2' otherwise
4661 * @param string $reason User supplied reason
4663 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4665 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4666 global $wgUser, $wgNewUserLog;
4667 if ( empty( $wgNewUserLog ) ) {
4668 return true; // disabled
4671 if ( $action === true ) {
4672 $action = 'byemail';
4673 } elseif ( $action === false ) {
4674 if ( $this->getName() == $wgUser->getName() ) {
4675 $action = 'create';
4676 } else {
4677 $action = 'create2';
4681 if ( $action === 'create' || $action === 'autocreate' ) {
4682 $performer = $this;
4683 } else {
4684 $performer = $wgUser;
4687 $logEntry = new ManualLogEntry( 'newusers', $action );
4688 $logEntry->setPerformer( $performer );
4689 $logEntry->setTarget( $this->getUserPage() );
4690 $logEntry->setComment( $reason );
4691 $logEntry->setParameters( array(
4692 '4::userid' => $this->getId(),
4693 ) );
4694 $logid = $logEntry->insert();
4696 if ( $action !== 'autocreate' ) {
4697 $logEntry->publish( $logid );
4700 return (int)$logid;
4704 * Add an autocreate newuser log entry for this user
4705 * Used by things like CentralAuth and perhaps other authplugins.
4706 * Consider calling addNewUserLogEntry() directly instead.
4708 * @return bool
4710 public function addNewUserLogEntryAutoCreate() {
4711 $this->addNewUserLogEntry( 'autocreate' );
4713 return true;
4717 * Load the user options either from cache, the database or an array
4719 * @param array $data Rows for the current user out of the user_properties table
4721 protected function loadOptions( $data = null ) {
4722 global $wgContLang;
4724 $this->load();
4726 if ( $this->mOptionsLoaded ) {
4727 return;
4730 $this->mOptions = self::getDefaultOptions();
4732 if ( !$this->getId() ) {
4733 // For unlogged-in users, load language/variant options from request.
4734 // There's no need to do it for logged-in users: they can set preferences,
4735 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4736 // so don't override user's choice (especially when the user chooses site default).
4737 $variant = $wgContLang->getDefaultVariant();
4738 $this->mOptions['variant'] = $variant;
4739 $this->mOptions['language'] = $variant;
4740 $this->mOptionsLoaded = true;
4741 return;
4744 // Maybe load from the object
4745 if ( !is_null( $this->mOptionOverrides ) ) {
4746 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4747 foreach ( $this->mOptionOverrides as $key => $value ) {
4748 $this->mOptions[$key] = $value;
4750 } else {
4751 if ( !is_array( $data ) ) {
4752 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4753 // Load from database
4754 $dbr = wfGetDB( DB_SLAVE );
4756 $res = $dbr->select(
4757 'user_properties',
4758 array( 'up_property', 'up_value' ),
4759 array( 'up_user' => $this->getId() ),
4760 __METHOD__
4763 $this->mOptionOverrides = array();
4764 $data = array();
4765 foreach ( $res as $row ) {
4766 $data[$row->up_property] = $row->up_value;
4769 foreach ( $data as $property => $value ) {
4770 $this->mOptionOverrides[$property] = $value;
4771 $this->mOptions[$property] = $value;
4775 $this->mOptionsLoaded = true;
4777 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
4781 * Saves the non-default options for this user, as previously set e.g. via
4782 * setOption(), in the database's "user_properties" (preferences) table.
4783 * Usually used via saveSettings().
4785 protected function saveOptions() {
4786 $this->loadOptions();
4788 // Not using getOptions(), to keep hidden preferences in database
4789 $saveOptions = $this->mOptions;
4791 // Allow hooks to abort, for instance to save to a global profile.
4792 // Reset options to default state before saving.
4793 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4794 return;
4797 $userId = $this->getId();
4799 $insert_rows = array(); // all the new preference rows
4800 foreach ( $saveOptions as $key => $value ) {
4801 // Don't bother storing default values
4802 $defaultOption = self::getDefaultOption( $key );
4803 if ( ( $defaultOption === null && $value !== false && $value !== null )
4804 || $value != $defaultOption
4806 $insert_rows[] = array(
4807 'up_user' => $userId,
4808 'up_property' => $key,
4809 'up_value' => $value,
4814 $dbw = wfGetDB( DB_MASTER );
4816 $res = $dbw->select( 'user_properties',
4817 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__ );
4819 // Find prior rows that need to be removed or updated. These rows will
4820 // all be deleted (the later so that INSERT IGNORE applies the new values).
4821 $keysDelete = array();
4822 foreach ( $res as $row ) {
4823 if ( !isset( $saveOptions[$row->up_property] )
4824 || strcmp( $saveOptions[$row->up_property], $row->up_value ) != 0
4826 $keysDelete[] = $row->up_property;
4830 if ( count( $keysDelete ) ) {
4831 // Do the DELETE by PRIMARY KEY for prior rows.
4832 // In the past a very large portion of calls to this function are for setting
4833 // 'rememberpassword' for new accounts (a preference that has since been removed).
4834 // Doing a blanket per-user DELETE for new accounts with no rows in the table
4835 // caused gap locks on [max user ID,+infinity) which caused high contention since
4836 // updates would pile up on each other as they are for higher (newer) user IDs.
4837 // It might not be necessary these days, but it shouldn't hurt either.
4838 $dbw->delete( 'user_properties',
4839 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__ );
4841 // Insert the new preference rows
4842 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, array( 'IGNORE' ) );
4846 * Provide an array of HTML5 attributes to put on an input element
4847 * intended for the user to enter a new password. This may include
4848 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4850 * Do *not* use this when asking the user to enter his current password!
4851 * Regardless of configuration, users may have invalid passwords for whatever
4852 * reason (e.g., they were set before requirements were tightened up).
4853 * Only use it when asking for a new password, like on account creation or
4854 * ResetPass.
4856 * Obviously, you still need to do server-side checking.
4858 * NOTE: A combination of bugs in various browsers means that this function
4859 * actually just returns array() unconditionally at the moment. May as
4860 * well keep it around for when the browser bugs get fixed, though.
4862 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4864 * @return array Array of HTML attributes suitable for feeding to
4865 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4866 * That will get confused by the boolean attribute syntax used.)
4868 public static function passwordChangeInputAttribs() {
4869 global $wgMinimalPasswordLength;
4871 if ( $wgMinimalPasswordLength == 0 ) {
4872 return array();
4875 # Note that the pattern requirement will always be satisfied if the
4876 # input is empty, so we need required in all cases.
4878 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4879 # if e-mail confirmation is being used. Since HTML5 input validation
4880 # is b0rked anyway in some browsers, just return nothing. When it's
4881 # re-enabled, fix this code to not output required for e-mail
4882 # registration.
4883 #$ret = array( 'required' );
4884 $ret = array();
4886 # We can't actually do this right now, because Opera 9.6 will print out
4887 # the entered password visibly in its error message! When other
4888 # browsers add support for this attribute, or Opera fixes its support,
4889 # we can add support with a version check to avoid doing this on Opera
4890 # versions where it will be a problem. Reported to Opera as
4891 # DSK-262266, but they don't have a public bug tracker for us to follow.
4893 if ( $wgMinimalPasswordLength > 1 ) {
4894 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4895 $ret['title'] = wfMessage( 'passwordtooshort' )
4896 ->numParams( $wgMinimalPasswordLength )->text();
4900 return $ret;
4904 * Return the list of user fields that should be selected to create
4905 * a new user object.
4906 * @return array
4908 public static function selectFields() {
4909 return array(
4910 'user_id',
4911 'user_name',
4912 'user_real_name',
4913 'user_password',
4914 'user_newpassword',
4915 'user_newpass_time',
4916 'user_email',
4917 'user_touched',
4918 'user_token',
4919 'user_email_authenticated',
4920 'user_email_token',
4921 'user_email_token_expires',
4922 'user_password_expires',
4923 'user_registration',
4924 'user_editcount',
4929 * Factory function for fatal permission-denied errors
4931 * @since 1.22
4932 * @param string $permission User right required
4933 * @return Status
4935 static function newFatalPermissionDeniedStatus( $permission ) {
4936 global $wgLang;
4938 $groups = array_map(
4939 array( 'User', 'makeGroupLinkWiki' ),
4940 User::getGroupsWithPermission( $permission )
4943 if ( $groups ) {
4944 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
4945 } else {
4946 return Status::newFatal( 'badaccess-group0' );